This is the 9th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Commonly used base nesting

Using the FastAPI, you can define, validate, document, and use any deeply nested model (thanks to Pydantic).

Basic model

class Item(BaseModel) :
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
    tags: list = []
Copy the code

Defines the word type of the type

Suppose we need to define a field tags:list whose elements are of type STR. How do we do that?

The answer: use the List class in typing. (The same is true for specifying other word types)

from typing import List

tags: List[str]
Copy the code

As above, you define a list of elements of type STR.

A nested model

To facilitate composite disassembly, we can declare certain model objects separately and then refer to them in other models.

class Image(BaseModel) :
    url: str
    name: str


class Item(BaseModel) :
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
    tags: Set[str] = []
    image: Optional[Image] = None
Copy the code

Above, we defined an Image model, which is used directly in the Item model.

In the actual request, we just send the request body in the following format.

{
    "name": "Foo"."description": "The pretender"."price": 42.0."tax": 3.2."tags": ["rock"."metal"."bar"]."image": {
        "url": "http://example.com/baz.jpg"."name": "The Foo live"}}Copy the code

Special type

HttpUrl: Provided by Pydantic.

class Image(BaseModel) :
    url: HttpUrl
    name: str
Copy the code

In the above ways, FastApi supports automatic associative completion, data conversion, data verification, and automatic document generation.

practice

The base type

class Md1(BaseModel) :
    name:str
    age:int

@app.post('/model/1')
async def m1(md:Md1) :
    return {'msg':'model is ok! '}
Copy the code

Execute tests:

According to the test results, we can know: ①FastApi model checking function is very easy to use. (2) When an integer is enclosed in double quotes, the FastApi can automatically convert it according to its qualified type. ③ There are clear hints for data structure inspection.

Nested types

class Md1(BaseModel) :
    name:str
    age:int

class Md2(BaseModel) :
    city_info:str
    people_info:Md1

@app.post('/model/1')
async def m1(md:Md1) :
    return {'msg':'model is ok! '}

@app.put('/model/2')
async def m2(md:Md2) :
    return {'msg':'relation model cheking pass! '}
Copy the code

Execute tests:

Based on the above test results, it is clear that the FastApi implementation with Pydantic model nesting is very elegant. Model nesting combined with dynamic request body enables us to easily respond to changes in the data model caused by business changes.

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