Why Swagger
Integrating Swagger with Flask can significantly enhance API development and documentation.
This powerful combination allows developers to create well-documented, interactive APIs that are easier to understand, test, and maintain.
The benefits of using Swagger:
- Improved Developer Experience: Swagger provides clear and concise API documentation, making it easier for developers to understand and interact with your API.
- Reduced Errors: By allowing developers to test API calls directly from the Swagger UI, it can help identify and fix potential integration issues early on.
- Increased Accessibility: Swagger makes your API more discoverable and user-friendly for a wider developer audience.
Yet, I’d prefer the REST Client extension on Visual Studio Code.
Getting started
Here’s how you can integrate it with your Flask API:
1. Flask-RESTful Extensions:
Several Flask extensions simplify Swagger integration. Popular options include:
- Flask-RESTPlus: This extension offers automatic Swagger UI generation alongside functionalities like request/response decorators and data marshaling (https://flask-restplus.readthedocs.io/en/stable/swagger.html).
- Flask-RESTful-Swagger: This extension focuses specifically on Swagger integration, providing functionalities like endpoint documentation and interactive UI generation (https://flask-restx.readthedocs.io/en/latest/swagger.html).
⚠️ Below, I will detail the “Flask-RESTful-Swagger” option, because Flask-RESTPlus is dead apparently.
2. Manual Integration:
While extensions offer convenience, you can also integrate Swagger manually. Here’s the general approach:
- Define API specification: use the OpenAPI Specification (OAS) format (a successor to Swagger) to define your API’s endpoints, data models, and functionalities. Tools like Swagger Editor (https://editor.swagger.io/) can aid this process.
- Serve the specification: Flask allows serving static files. You can configure your Flask app to serve the generated OAS file at a specific URL (e.g.
/swagger.json
). - Client-side Integration: Frontend clients can utilize Swagger UI, a web-based interface that fetches and parses the OAS file, providing an interactive API documentation explorer. You can include Swagger UI’s static files within your Flask app and serve them at a designated URL (e.g.
/swagger
).
Below, I’ll detail the implementation with an extension.
Integrating Swagger to my REST API
Recommendation
Use PyCharm IDE to develop in Python. It’ll save you the hassle to setup Visual Studio Code and the extensions you need.
First, you need to install the extension:
|
|
Then, you need to declare the API. I personally use:
- an
app.py
for the Flask app, - an
api.py
for the main API entry point, - and an individual
api_business_1.py
to separate the various APIs I have.
Introducing Swagger prompted me to introduce api_swagger.py
that I can reuse in api_business_1.py
to declare the route.
The full example in the doc in great to get started.
Declaring the API
First, we need to instantiate the API with the high-level information:
|
|
Implementation in a Controller
Then, you’ll need to implement your controller.
First, define the namespace for the controller:
|
|
For each action in the controller, you organize them by routes.
Below the /
route is the root route (full route based on the namespace is therefore api/v2.0/projects/
).
Consequently, the POST api/v2.0/projects/
(adding a project) and GET api/v2.0/projects
(getting all projects) will go under a class ProjectList
.
|
|
Then, we deal with the single resource endpoints under the Project
class. The full route then is api/v2.0/projects/<string:id>
.
It groups the GET api/v2.0/projects/<string:id>
, PUT api/v2.0/projects/<string:id>
and DELETE api/v2.0/projects/<string:id>
.
|
|
If you need, you can add other routes like the one below for getting all records for a given project.
|
|
As you may have noticed, each route declares:
@ns-route
decorator to define the route path.@ns.response
decorator, if needed, to define the HTTP response codes that the API could raise.@ns.param
decorator to detail the input parameters the route receives.@ns.doc
decorator to provide a quick description of the action.@ns.expect
decorator to validate the input payload.@ns.marshal_with
decorator to validate the output.
Handling error
I discontinued my get_response_json
that I used before Swagger to create two methods.
The services would use the raise_business_error
when the code finds a business error.
|
|
The usage could be:
|
|
Then, the handle_ex
, as a generic catch all, including business error, normalized the API response. It was a challenge to code this one, but I’ve learned a few things about the native utilities in Python.
|
|
The usage in the services is simple:
|
|
As I look at this, three months after the development, I think a decorator would be better. Then I’d have one single try...expect
and the syntax would look like:
|
|
Conclusion
There you have it!
Swagger provides a neat documentation and testing capabilities. Though I’d not use for testing large API, it comes in handy when you want to check an endpoint definition or to test an endpoint.
I hope you enjoyed this article.
Follow me
Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.
Credit: Python logo of the header image is from WorldVectorLogo. You can find the original images here: I built the image with Sketchpad of Sketch.io.