Pydantic model

Pydantic model#

from fastapi import FastAPI
from fastapi.testclient import TestClient

from pydantic import BaseModel

Default arguments#

All defined arguments you’ve specified for the pydantic model will be interpreted by python as default values in case parameter doesn’t passed.


The following cell defines an endpoint that uses BaseModel where param1 has a default value and param2 doesn’t have a default value.

class Item(BaseModel):
    param1: int = 33
    param2: str

app = FastAPI()

@app.post("/")
def read_json(item: Item):
    return f"""I have got:
    param1={item.param1};
    param2={item.param2}."""

test_client = TestClient(app=app)

Here api is called with param1 doesn’t specified.

data = {"param2": "test line"}
print(
    test_client.post(url="/", json=data)
    .content
    .decode("utf-8")
    .replace("\\n", "\n")
)
"I have got:
    param1=33;
    param2=test line."

Result shows that the default value has been replaced.

But if you don’t pass a parameter without a default value, you will get a 422 error.

ans = test_client.post(url="/", json={})
print(ans)
print(ans.content.decode())
<Response [422 Unprocessable Entity]>
{"detail":[{"type":"missing","loc":["body","param2"],"msg":"Field required","input":{}}]}
test_client.close()