This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

What is the request Body

As the name implies, the request body is the data carried by the client during the request.

It is not necessary to carry the request body, and it is not recommended to use GET request to send the request body, we usually use POST request to send the request body, of course, you can also use PUT, DELETE, PATCH mode to send the request body.

Take a chestnut

Make the corresponding response according to the request body, and return the request body content as follows.

The FastApi request body needs to be in dict format

code

@app.post('/models/')
async def add_model(model:str) :
    return model
Copy the code

The interface test

normal

Abnormal situation

FastApi will help us with type checking, basic format validation, etc

Request body check

Often, when we develop, we need users to make requests based on specific structures to prevent attacks and filter users.

FastApi data model

In FastApi, we can use the Pydantic BaseModel class to implement the definition of the request structure.

code

from pydantic import BaseModel

class Mds(BaseModel) :
    name: str
    age: int
    home: str

@app.post('/models/')
async def add_model(model:Mds) :
    return model
Copy the code

The interface test

normal

Abnormal situation

Error, missing struct fields are detected by FastApi.

Optional fields

Optional fields in FastApi have the following two scenarios

  1. Field has a default value
  2. The field type isOptional

code

from pydantic import BaseModel
from typing import Optional

class Mds(BaseModel) :
    name: str
    age: int = 18
    home: str
    height: Optional[str]

@app.post('/models/')
async def add_model(model:Mds) :
    return model
Copy the code

The interface test

This parameter is mandatory only

Carry all parameters

Extra arguments (extra arguments are ignored)

This parameter is not mandatory

conclusion

The fields of the request structure can be many, indispensable and mandatory.

Request body use

We can use the properties of the request body directly inside the view function.

code

from pydantic import BaseModel
from typing import Optional

class Mds(BaseModel) :
    name: str
    age: int = 18
    home: str
    height: Optional[str]

@app.post('/models/')
async def add_model(Mds:Mds) :
    ret = {}
    if Mds.name:
        ret.update({"Name":Mds.name})
    if Mds.height:
        ret.update({"height":Mds.height})
    return ret
Copy the code

The interface test

Thank you for reading, and don’t forget to follow, like, comment, and forward four times!