Python Flask RestFul API














































Python Flask RestFul API



FLASK RESTFUL API

The client application sends requests to the server at the established resource URLs. and uses the request method to indicate the desired operation. To obtain the list of available blog posts in the blogging API the client would send a GET request to http:// www.example.com/api/posts/, and to insert a new blog post it would send a POST request to the same URL, with the contents of the blog post in the request body. To
retrieve blog post 12345 the client would send a GET request to http://www.example.com/api/posts/12345.


Flask makes it very easy to create RESTful web services. The familiar route() decorator along with its methods optional argument can be used to declare the routes that handle the resource URLs exposed by the service. Working with JSON data is also simple, as JSON data included with a request can be obtained in dictionary format by calling request.get_json(), and a response that needs to contain JSON can be easily generated from a Python dictionary using Flask's jsonify() helper function. The following sections show how Flasky can be extended with a RESTful web service that gives clients access to blog posts and related resources.

Creating API Blueprint

The routes associated with a RESTful API form a self-contained subset of the application, so putting them in their own blueprint is the best way to keep them well organized.


API blueprint structure




Modules to take
care of authentication and error handling and to provide custom decorators are also
included


The API blueprint is registered with a URL prefix so that all its routes will have their URLs prefixed with  /api/v1. Adding a prefix when registering the blueprint is a good idea because it eliminates the need to hardcode the version number in every blueprint route.



Comments