Python Flask Resource Endpoints

Python Flask Resource Endpoints

Flask Resource Endpoints

An API endpoint is a point at which an application program interface (API) the code that allows two software programs to communicate with each other connects with the software program. APIs work by sending requests for information from a web application or web server and receiving a response.

POST resource handler

This view function is wrapped in a permission_required decorator (shown in an upcoming example) that ensures that the authenticated user has the permission to write blog posts. The actual creation of the blog post is straightforward due to the error handling support that was implemented previously. A blog post is created from the JSON data and its author is explicitly assigned as the authenticated user. After the model is written to the database, a 201 status code is returned and a Location header is added with the URL of the newly created resource. 
Note that as a convenience to clients, the body of the response includes the new resource. This will save the client from having to issue a GET request for it immediately after creating the resource.

Permission Required Decorator

The permission_required decorator used to prevent unauthorized users from creating new blog posts is similar to the one used in the application but is customized for the API blueprint

The permission checks are more complex in this case. The standard check for permission to write blog posts is done with the decorator, but to allow a user to edit a blog post the function must also ensure that the user is the author of the post or else is an administrator. This check is added explicitly to the view function. If this check had to be added in many view functions, building a decorator for it would be a good way to avoid code repetition.
Since the application does not allow deletion of posts, the handler for the DELETE request method does not need to be implemented.

Flasky API resources

Note that the resources that were implemented offer only a subset of the functionality that is available through the web application. The list of supported resources could be expanded if necessary, such as to expose followers, to enable comment moderation, and to implement any other features that an API client might need.