Serving html requests with Eve

I am trying to create a Flask application with MongoDB support that works from the same endpoints:

  • The default HTML web interface
  • JSON response if Content-Type == application/json

The idea is that both a user using my browser application and a service using my API can programmatically hit http://myapp.com/users/12345 . the HTML response is served, and the second is the JSON response.

As I understand it, this corresponds to a "pure" REST, in contrast to the tradition of serving the API using a separate path, such as http://myapp.com/api/users/12345 .

There is no discussion in the Eve docs, except to say that the results are executed as JSON by default, and XML - on request.

Is there any clean way to override this behavior, for example:

  • Standard response Eve JSON served if Content-Type == application/json
  • Otherwise, the view applies the template to the data returned by Eve to generate an HTML response?

This seems to be an elegant means of creating an application that is both RESTful and DRY.

+2
source share
1 answer

You can see the Eve-Docs extension, which implements the HTML /docs endpoint on top of the existing Eve-supported MongoDB REST service.

Remember that Eve is a Flask application (actually it is a subclass), so anything you can do with Flask you can do with Eve (for example, decorate rendering functions, etc.).

UPDATED: Here is a snippet of a small example that adds a custom /hello endpoint to the Eve ( source ) API. As you can see, pretty much identical to the Flask standard endpoint:

 from eve import Eve app = Eve() @app.route('/hello') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() 
+3
source

Source: https://habr.com/ru/post/1210471/


All Articles