API Documentation with swagger in Flask…
- General
API Documentation with swagger in Flask…
What is API Documentation and why is it required?
Whenever we code for any API, only we know how this API works and what are the needed inputs for this API, and what it will give the response in different cases. If some other dev wants to consume our API, then we need to explain to him about the request and response. Let suppose any other dev wants to consume the same API, then again we have to explain to him about the required inputs and response data. And we can not do this all the time, so here our API docs work for us. When we create an API, we create a doc for the API and deploy it with the API. and This doc should be enough to explain all about our API.
There are many ways to create API Docs, one of them is SWAGGER. For swagger mostly every language has a library, in python we have flasgger. Flasgger is quite amazing, it provides all features which are required for API docs.
Now we understood about the API documentation, so…
First, we install flasgger by following command: pip3 install flasgger.
Now, in flask we have a create_app function, there we will add the following lines
1 2 3 4 |
def create_app(config_name: str = 'default', override_settings=None): app = Flask(__name__) swagger = Swagger(app) return app |
“If we don’t have create_app function, then we can simply add” –
1 |
swagger = Swagger(app) |
It will add swagger API documentation to the default endpoint “/apidocs”.
Now run your app and access, http://localhost:5000/apidocs/index.html and you will play with Swagger UI!
Swagger UI will look something like this
I am assuming you know how to create API in the flask, so let’s start with API doc.
There are many ways to add API doc code in the flask. One is to add API documentation code with API code, but I preferred to keep them separate in the .yml file. It keeps our business code and API documentation code separate and our code is much more readable and understandable.
There are a few parameters which we will use in this session, let’s understand them first:
- Summary: Heading for our API
- Description: Describe our API like what will this API do.
- Consumes: Data type of our request
- “application/json”
- “formdata”
- Produces: Datatype of our response
- “application/json”
- Parameters: What are the required parameters needed for API will be added here. There are many ways to pass requests in an API like, in header, body, args, formdata. We will see examples for all these types in this blog.
- Type: used for describe type of param, It can be “number”, “string”, “float”, “object”
- In: It is used to place our param at a specific location. Values for in can be – “query” (For pass param in get request), “body” (used when API method type is POST), “header” (If you want to pass param in the header).
- Responses: What API will give a response, will add here.
- Properties: It will describe all properties of the requested param or response variable.
Now, let’s start with API documentation, create a new api_doc.yml file and add it to your flask code like this:
Case 1:
1 2 3 4 |
from flasgger.utils import swag_from @swag_from("/path/to/api_doc.yml") def get_otp(): |
API method type: GET
Request perms goes in args
Now our api_doc.yml will look like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
summary: "Get OTP" description: "This is a simple API to send OTP." produces: - "application/json" parameters: - in: "query" name: "phone" type: "string" required: "true" responses: 200: description: "Success" schema: type: "object" properties: data: type: "object" status: type: "string" message: type: "string" 400: description: "Same response is for 202, 400" |
Swagger UI for this doc is:
Let’s understand this:
- At lines 1 and 2, we have a summary and description of API.
- At line 3, we have produces, which means the API response is in JSON format.
- At line 5, we have the required parameters needed for the API success response.
- At line 6, We have “IN” that has the value “query”, which means this parameter will pass in arguments.
For example, our url will look like
“http://localhost:5000/api/v2/get-otp?phone=919876543210“
- At line 7, we have the name, which is the key name of our requested parameter.
- At line 8, we have type, which describes the type of parameter. Type can be string, number, object, float.
- At line 9, we have required, as it is understood with its name. It makes our param mandatory if it is true.
- At line 10, we have our responses. We know a single API can return multiple responses respective to the status code. If the API gives a successful result, then the status code would be 200, if nothing is found for the requested parameter, then it gives 404. Similarly, there can be more status codes. So here we can add documentation for all status codes. Currently, we have added for 200 and 400, if you want to add more, then similarly you guys can add code for multiple status codes.
- At line 11, we have status code.
- From line 12 to 21, we have a response for status code 200.
- At line 13, we have a description of our response.
- At line 14, we are explaining the schema which will be the response of our api, when we got 200 status code.
Case 2:
1 2 3 4 |
from flasgger.utils import swag_from @swag_from("/path/to/api_doc.yml") def place_order(): |
API method type: POST
Request perms go in body
Now our api_doc.yml will look like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
summary: "Place Order" description: "This is a simple API to place order.” consumes: - "application/json" produces: - "application/json" parameters: - in: "body" name: "body" description: "Accepts a input dictionary of orders" required: "true" schema: type: "object" properties: order: type: "object" example: {'order':[{'product_id': '10001', 'quantity': 2, 'product_delivery_date': 'Sat, 20 March 2020', 'selling_price': 23, 'source': ['BANNER']}], 'wallet_amount': 50} responses: 400: description: "Same response is for 202, 400, 403" schema: type: "object" properties: status: type: "string" message: type: "string" |
Here in parameters, we have a single param in body i.e order. This “order” param is a type of object, which contains a list of objects. So for a better explanation, we added an example that can be shown on the Swagger UI page.
So, now it is much easier to understand. So now we understood how examples can be added in API docs and how it is helpful for us.
Let’s move on to our 3rd case. In many APIs, we pass some values in the header, like device-token, device-information, ap-version, etc. so for header param we use the header in parameter.
Here I am simply showing how we can add a param for header, it is quite easy, just similar to our query type.
1 2 3 4 5 6 7 8 9 |
parameters: - in: "header" name: "app-version" type: "string" required: "true" - in: "header" name: "device-token" type: "string" required: "true" |
So, now we can create API documentation for any kind of APIs.
Wait…, something is still missing, but what? Authorization
We all know we mostly have secured API, and before calling them we should have access-token or secure-token. For these secure tokens, we have a separate interesting part in swagger, we don’t do this in a normal way.
We can simply pass this token in the header too, but Swagger provides us with a different way to add it in our API documentation.
For that, we need to add a template.
1 2 3 4 |
SWAGGER_TEMPLATE = { "securityDefinitions": {"APIKeyHeader": {"type": "apiKey", "name": "x-access-token", "in": "header"}}} swagger = Swagger(app, template=SWAGGER_TEMPLATE) |
What it will do? this question will be in your mind. Well, this templates can do a lot of things in our swagger UI page, but for now, we will focus on our Auth part. Here we added a security definition. In the API header, it will add an “x-access-token”. You can see this Authorize button at the top right corner.
When you click on this button an input field will appear, there you can save your security-token.
But how will you add this to a specific API?
So, for that, we need to add something to our API documentation code.
1 2 3 4 5 6 7 8 |
summary: "Place Order" description: "This is a simple API to place order”. consumes: - "application/json" produces: - "application/json" security: - APIKeyHeader: [ 'x-access-token' ] |
When you add security to API doc, a lock icon will be shown with API on the left side.
This lock icon indicates that this API is secured, and we need to pass security-token to access this API. Also, we don’t need to add this param in the request part for each API, we just need to add this security key, and it will send that secure-token in the header itself.
So, guys, this is all about the API documentation with swagger in the flask, if you feel there is something missing or you have any queries then we can discuss them in the comment section.
Recommended links
https://github.com/flasgger/flasgger
If you enjoyed this article, share it with your friends and colleagues!
Related content
Auriga: Leveling Up for Enterprise Growth!
Auriga’s journey began in 2010 crafting products for India’s