Custom endpoint handlers with Eve

On Stack Overflow and the Eve mailing list, but also in my mailbox and even on Twitter, I get a lot of enquiries on how to build custom endpoints within a Eve-powered RESTful application. Now, since within Eve all endpoints are fully customizable, what they really mean is:

How do I setup endpoints without any binding to a data entity, just connected to a custom method?

They would like to call something like /mycustomendpoint and get the response from a method they have defined somewhere in the Python sources. The standard endpoint-entity mapping provided by Eve covers 90% of their needs, but sometimes they just need endpoints that have nothing to do with data entities.

This is very easy to achieve. I’m writing it down so I can point people to this post in the future.

Eve is Flask

Eve is a Flask application and I really mean it since it is, in fact, a Flask subclass. Eve adds out-of-the-box RESTful capabilities to the Flask micro-framework. Most of the time you will be happy with just Eve’s own features but remember, the full Flask (and Werkzeug at a lower level) features set is also part of your arsenal.

Whatever you can do with Flask, you can do with Eve

So yes, of course you can easily set some functions to be invoked when a custom endpoint is hit with a request. The following snippet is a slightly modified version of Flask’s very own Quickstart tutorial:

By decorating the hello_world method with the route decorator we added a new endpoint to the application. Each time a request to /hello comes in, it will be routed to our custom method. Of course the regular API endpoints (either defined in settings.py, passed as a dict at launch, or registered live by calling the register_resource method) will also be available.

If you have an Eve authentication class securing regular API endpoints, you can apply it to your custom endpoint too. Just add a requires_auth decorator:

Say that you saved the above snippet as run.py and also have your RESTful endpoints properly configured. Launch the script:

You can now point your browser to http://localhost:5000/hello/ and enjoy the application greeting. Or you can consume any other configured API endpoint.

As all of Flask features are at your fingertips you might as well opt for registering a blueprint, which is what the awesome Eve-Docs extension is doing in order to provide a static HTML /docs endpoint on top of any Eve powered API.