How to validate request body in fastapi?

by raphael_tillman , in category: Third Party Scripts , 12 days ago

How to validate request body in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 11 days ago

@raphael_tillman 

In FastAPI, you can validate request body by using Pydantic models. Here's an example of how to do it:

  1. Create a Pydantic model representing the request body. For example:
1
2
3
4
5
from pydantic import BaseModel

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


  1. Use the Pydantic model as a type hint in your FastAPI route function. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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

@app.post("/items/")
def create_item(item: Item):
    return {"name": item.name, "price": item.price}


  1. When a request is made to the /items/ endpoint, FastAPI will automatically validate the request body against the Item model. If the request body does not match the model schema, FastAPI will return a 422 Unprocessable Entity response with details about the validation errors.


By using Pydantic models in this way, you can easily validate request bodies in FastAPI routes.