Parameters in FastAPI

Posted by Daksh on Tuesday, November 15, 2022

FastAPI - Parameters (POST Requests)

Request Body

Request body is used to send data to the server. Therefore it is a POST method. Under the hood, FastAPI uses Pydantic to validate and convert the data from JSON (incoming request) to BaseModel.


class ItemModel(BaseModel):
    name: str
    price: float
    is_available: Optional[bool] = None

@router.post("/new/")
# in the docs UI, the request body will be shown as a JSON
# with parameters name, price and is_available shown inside request body
def create_item(item: ItemModel):
    # the response will be shown as a JSON inside the response body
    return item

Path & Query Parameters

Combines all 3 parameters: dataModel, path and query parameters.

@router.post("/items/{item_id}")
def read_item(item: ItemModel, item_id: int, q: Optional[str] = None):
    return {"id": item_id, 
            "item": item, 
            "q": q}

Parameter Metadata

We can add metadata to the parameters. This metadata will be shown in the docs UI. This is done using the Query, Path and Body classes.

from fastapi import Query, Path, Body

@router.post("/new/{item_id}/comments/")
def create_comment(item: ItemModel, item_id: int, comment_id: int = Query(None, title="Comment ID", description="The ID of the comment to create", alias="commentId", deprecated=False)):
    # do something

Validators

We can add validators to the parameters. It validates data passed to parameters. This can be done either by providing a default value. Example: comment_content: str = Body('This is a comment').

To specify a mandatory parameter, we can use ... instead of a default value. Example: comment_content: str = Body(...). The ... means that the parameter is mandatory and it is called a Ellipsis. You can also use Body(Ellipsis) instead of Body(...).

Other types of validators available are min_length, max_length, gt, lt, ge, le, regex, email, url, etc.