- Hands-On Docker for Microservices with Python
- Jaime Buelta
- 355字
- 2021-06-24 12:35:50
Introducing Flask-RESTPlus
Flask is capable of implementing a RESTful interface, but Flask-RESTPlus adds some very interesting capabilities that allow for good developing practices and speed of development:
- It defines namespaces, which are ways of creating prefixes and structuring the code. This helps long-term maintenance and helps with the design when creating new endpoints.
If you have more than 10 endpoints in a single namespace, it may be a good time to consider dividing it. Use one namespace per file, and allow the size of the file to hint when it's a good idea to try to make a division.
- It has a full solution for parsing input parameters. This means that we have an easy way of dealing with endpoints that requires several parameters and validates them. Using the Request Parsing (https://flask-restplus.readthedocs.io/en/stable/parsing.html) module is similar to using the argparse command-line module (https://docs.python.org/3/library/argparse.html) that's included in the Python standard library. It allows defining arguments in the body of the request, headers, query strings, or even cookies.
- In the same way, it has a serialization framework for the resulting objects. Flask-RESTful calls it response marshalling (https://flask-restplus.readthedocs.io/en/stable/marshalling.html). This helps to define objects that can be reused, clarifying the interface and simplifying the development. If enabled, it also allows for field masks, which return partial objects.
- It has full Swagger API documentation support. Swagger (https://swagger.io/) is an open source project to help in the design, implementation, documentation, and testing of RESTful API web services, following standard OpenAPI specifications. Flask-RESTPlus automatically generates a Swagger specification and self-documenting page:
The main Swagger documentation page for the Thoughts Backend API, generated automatically
Other nice elements of Flask are derived from the fact that it's a popular project and has a lot of supported tools:
- We will use the connector for SQLAlchemy, Flask-SQLAlchemy (https://flask-sqlalchemy.palletsprojects.com/en/2.x/). Its documentation covers most of the common cases, while the SQLAlchemy documentation is more detailed and can be a bit overwhelming.
- To run the tests, the pytest-flask module (https://pytest-flask.readthedocs.io/en/latest/) creates some fixtures ready to work with a Flask application. We will talk more about this in the Testing the code section.