Write a Class for Calling APIs Based on Python
Nowadays, back - end development mainly involves writing various APIs for others to use. In my daily work, I not only write APIs but also frequently call APIs written by others.
Let me share the module for calling APIs that I often use.
Before looking at the code, there are some assumptions that can help you understand the code.
Some Assumptions
Suppose we have an API: http://127.0.0.1:8000/api/token. For detailed information, you can refer to simple jwt.
Here, I’ll provide a simple interface document as follows.
Request Method
POST
Request Parameters
The following data in JSON format needs to be provided in the request body:
username
: Usernamepassword
: Password
Example:
1 | { "username": "<username>", "password": "<password>" } |
Response Content
If the authentication is successful, the interface will return a response in the following format:
1 | { "access": "<Access_Token>", "refresh": "<Refresh_Token>" } |
Among them:
<Access_Token>
: Access token, which can be used for subsequent protected operations.<Refresh_Token>
: Refresh token, which can be used to obtain a new access token after the access token expires.
Error Handling
- If the username or password is incorrect, a 401 Unauthorized error will be returned, along with a descriptive error message.
- If an internal server error occurs, a 500 Internal Server Error will be returned.
Usage Example
Request
1 | curl --header "Content-Type: application/json" \ --request POST \ --data '{"username":"admin", "password":"123456"}' \ http://localhost:8000/token/ |
Response
1 | { "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv...", "refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpv..." } |
APIConnection
With the above assumptions, we can now look at the code.
The following is the entire code, and the explanations are placed in the comments.
1 | import json |
When writing this blog, I found that this code is really not that good. There are the following problems:
- The exception handling is only through logging.
- Each method requests
self.request_jwt()
separately, which not only puts unnecessary pressure on the backend but also increases its own time consumption. request.Session()
can be used to maintain some header parameters and utilize the connection pool to improve performance.
This is probably the significance of writing a blog. When writing, you are actually doing a review.