Search code examples
flaskflask-restful

Using flask web/html and flask restful/json together


I'm building an flask application that makes resources available via an restful API and the Web. Both parts of the app use the same models/business logic. The URL (/api/) and the request type should determine which part handles each request.

What is the best way to achieve this with flask? The error messages (e.g. 404 or 500) should have the right content type (html or json). Can I use the flask-restful extention (together with render_html etc.) or do I have to use 2 parallel apps?


Solution

  • Two parallel apps can be easy to work and scale but you can do it in one single app. Create blueprints for each module of your app (api, auth, etc...) just return json for api and render template for web. In case of errors you need to create error handlers for each blueprint (errors for API should return JSON and web should return HTML pages).