fastapi logo fastapi: type validation

1 2 3 4 5 6 7 8 9
Notes

Json can have a lot of different types and before doing anything serious with data that we receive from the client we should confirm that the data is correctly formatted. This is something that we can confirm with pydantic, which FastAPI tightly integrates with.

The app.py file at the end of our video looks like this;

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def root():
    return {"message": "hello world again"}

@app.get("/users/{user_id}")
def read_user(user_id: str):
    return {"user_id": user_id}

from pydantic import BaseModel, validator

class Item(BaseModel):
    name: str
    price: float

    @validator("price")
    def price_must_be_positive(cls, value):
        if value <= 0:
            raise ValueError(f"we expect price >= 0, we received {value}")
        return value

@app.post("/items/")
def create_item(item: Item):
    return item

Don't forget that you need to import the validator decorator from pydantic.