This is the 26th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021.
Since we learned about FastAPI and its simple use in the previous article, this article will take a look at FastAPI requests and see how FastAPI sets various request parameters.
The Path parameter
The Path argument is specified in braces {} in the route, and then accepted when defining the method. In addition, the type of argument can be specified, for example:
@app.get("/user/{user_id}")
async def hello_user(user_id: int) :
return {"Hello user": user_id}
Copy the code
In the above code, user_id: int specifies the type of the argument to be int. FastAPI will automatically check the Pydantic module. If the type passed in is incorrect, it will get an error message like the following:
{
"detail": [{"loc": [
"path"."user_id"]."msg": "value is not a valid integer"."type": "type_error.integer"}}]Copy the code
Instead of having to check parameters manually, we can focus on writing business code to improve development efficiency.
The Query parameter
When parameters declared by a function are not path parameters, they are automatically interpreted as Query parameters, which are urls, right? The key-value pair is then separated by &.
@app.get("/users")
async def users(page: int, page_size: int = 10, name: str = None) :
return {"page": page, "page_size": page_size, "data": []}
Copy the code
Also, we can specify the parameter type, and we can set the default value, such as the default value of the page_size parameter is 10, or if the parameter is not uploaded, the default value is 10. Of course, you can set the default value to None to indicate optional query parameters, such as the name parameter above, which can be passed or not.
In addition, the Pydantic model supports a wide range of data types, including time, date, and UUID, in addition to the usual STR, int, float, List, and Dict types.
Request body parameter
To set the request body parameters, we need to define a data model class that inherits Pydantic module’s BaseModel class as follows:
class User(BaseModel) :
name: str
password: str = '123456'
description: str = None
Copy the code
Similarly, if you specify a data type and a default value, if a default value is set, then this parameter is not mandatory.
Then, when defining the function, specify the parameter as the data model class User type:
@app.post("/add")
async def add(user: User) :
return {"name": user.name, "password": user.password}
Copy the code
FastAPI will automatically convert the defined model classes into JSON Schema, which becomes part of the OpenAPI generated Schema and is displayed in the API interaction document. View the API interaction document below, and the interface will receive application/ JSON type parameters.
We can also define more complex request model classes, such as a List of attributes, a Dict dictionary type, or a nested model class.
FastAPI allows you to define Path parameters, Query parameters, and request body parameters at the same time, and FastAPI will correctly identify and retrieve the data.
- If the parameter is also declared in the URL, it will be interpreted as a path parameter
- If the argument is of a single type (such as int, float, STR, bool, and so on), it will be interpreted as a Query argument
- If the parameter type is inherited from the Pydantic module
BaseModel
Class, which is interpreted as a request body parameter
Form Data
FastAPI can receive Form data using the Form component, which needs to be installed using the PIP install python-multipart command.
Form Data Form parameters are declared in the same way as Path or Query parameters:
@app.post("/login")
async def login(*, name: str = Form(.), password: str = Form(.)) :
return {"Hello user": name}
Copy the code
Parameters must be received using Form, otherwise the parameters will be interpreted as Query parameters or request body parameters.
Request Request object
If you want to access the Request object directly, you need to declare the Request type parameter in the function. FastAPI will automatically pass the Request object to this parameter, and we can obtain the Request object and its properties. For example, headers, URLS, cookies, and sessions.
@app.post("/login")
async def login(request: Request) :
return {"Hello": request.url}
Copy the code
In addition, if you want to obtain the requested cookie and header information, you can also declare the cookie type and header type parameters in the function to receive, FastAPI will automatically process and receive these information, very convenient.
The Path, Query, Body, Form, Cookie, and Header classes all inherit from the Param class so that we can easily declare different types of request parameters using them.
Original is not easy, if small partners feel helpful, please click a “like” and then go ~
Finally, thank my girlfriend for her tolerance, understanding and support in work and life!