Skip to content

Request

Request declaration⚓︎

First, you need to import BaseModel from pydantic:

1
from pydantic import BaseModel

path⚓︎

Request parameter in rules,@app.get('/book/{bid}').

You have to declare path model as a class that inherits from BaseModel:

1
2
3
4
5
6
7
class BookPath(BaseModel):
    bid: int = Field(..., description='book id')


@app.get('/book/{bid}', tags=[book_tag], security=security)
async def get_book(path: BookPath):
    ...

query⚓︎

Receive request query parameters.

like path, you need pass query to view function.

1
2
3
4
5
6
7
8
class BookQuery(BaseModel):
    age: int | None = Field(..., ge=2, le=4, description='Age')
    author: str = Field(None, min_length=2, max_length=4, description='Author')


@app.get('/book/{bid}', tags=[book_tag], security=security)
async def get_book(path: BookPath, query: BookQuery):
    ...

form⚓︎

Receive request form data and files.

1
2
3
4
5
6
7
8
class UploadFileForm(BaseModel):
    file: UploadFile  # request.files["file"]
    file_type: str = Field(None, description="File type")


@app.post('/upload')
async def upload_file(form: UploadFileForm):
    ...

body⚓︎

Receive request body.

1
2
3
4
5
6
7
8
class BookBody(BaseModel):
    age: int | None = Field(..., ge=2, le=4, description='Age')
    author: str = Field(None, min_length=2, max_length=4, description='Author')


@app.post('/book', tags=[book_tag])
async def create_book(body: BookBody):
    ...

Receive request headers.

Receive request cookies.

request⚓︎

Receive request from starlette.requests.Request.

Request model⚓︎

First, you need to define a pydantic model:

1
2
3
class BookQuery(BaseModel):
    age: int = Field(..., ge=2, le=4, description='Age')
    author: str = Field(None, description='Author')

More information to see BaseModel, and you can Customize the Field.

However, you can also use Field to extend Parameter Object. Here is an example:

age with example and author with deprecated.

1
2
3
class BookQuery(BaseModel):
    age: int = Field(..., ge=2, le=4, description='Age', json_schema_extra={"example": 3})
    author: str = Field(None, description='Author', json_schema_extra={"deprecated": True})

Magic:

More available fields to see Parameter Object Fixed Fields.