Python Flask Serializing JSON

Python Flask Serializing JSON

Flask Serializing JSON

A frequent need when writing a web service is to convert internal representations of resources to and from JSON, which is the transport format used in HTTP requests and responses. The process of converting an internal representation to a transport format such as JSON is called serialization.

The URL, author_url, and comments_url fields need to return the URLs for the respective resources, so these are generated with url_for() calls to other routes that will be defined in the API blueprint.
This example shows how it is possible to return made-up attributes in the representation of a resource. The comment_count field returns the number of comments that exist for the blog post. Although this is not a real attribute of the model, it is included in the resource representation as a convenience to the client. 

Converting user JSON serializable dictionary

Note how in this method some of the attributes of the user, such as email and role, are omitted from the response for privacy reasons. This example again demonstrates that the representation of a resource offered to clients does not need to be identical to the internal definition of the corresponding database model.
The inverse of serialization is called deserialization. Deserializing a JSON structure back to a model presents the challenge that some of the data coming from the client might be invalid, wrong, or unnecessary 

API error handler for ValidationError exceptions

The application now needs to handle this exception by providing the appropriate response to the client. To avoid having to add exception-catching code in-view functions, a global exception handler can be installed using Flask errorhandler decorator. A handler for the ValidationError exception is shown below

The error handler decorator is the same one that is used to register handlers for HTTP status codes, but in this usage, it takes an Exception class as an argument. The decorated function will be invoked any time an exception of the given class is raised. 
Note that the decorator is obtained from the API blueprint, so this handler will be invoked only when the exception is raised while a route from the blueprint is being handled. Using this technique, the code in view functions can be written very cleanly and concisely, without the need to include error checking.