Servicing html requests with Eve
Asked Answered
T

1

2

I am attempting to build a MongoDB-backed Flask application which serves from the same endpoints:

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

The idea is that both a user consuming my application with a browser and a service consuming my API programatically can both hit http://myapp.com/users/12345 The former is served a HTML response and the latter is served a JSON response.

As I understand this is in keeping with 'pure' REST, in contrast to the tradition of serving the API from a separate path such as http://myapp.com/api/users/12345.

There is no discussion of views in the Eve docs, other than to say that results are served as JSON by default and XML if requested.

Is there any clean way to override this behaviour such that:

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

This seems like it would be an elegant means of creating an application which is both RESTful and DRY.

Terefah answered 10/6, 2014 at 6:33 Comment(0)
C
3

You could look at the Eve-Docs extension which implements a HTML /docs endpoint on top of an existing, Eve-powered, MongoDB REST Service.

Remember Eve is a Flask application (a subclass actually), so everything you can do with Flask you can do with Eve too (like decorate rendering functions etc.)

UPDATED: Here's a little example snippet which adds a custom /hello endpoint to a Eve powered API (source). As you can see is pretty much identical to a standard Flask endpoint:

from eve import Eve
app = Eve()

@app.route('/hello')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
Checkrow answered 10/6, 2014 at 6:55 Comment(2)
Thanks for getting back to me so quickly Nicola!Terefah
Doesn't work for me. I get XML message 404: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. I suppose, the config file plays an important role in proper resolution, and in the referenced code the config file is big and complicated. I've tried to replace Eve by Flask in constructing the app and it instantly worked serving the static files.Rumanian

© 2022 - 2024 — McMap. All rights reserved.