Careeroza
Request Body
Receiving JSON
Example
A parameter typed with a Pydantic model is read from the JSON body. FastAPI validates it before your function runs:
from fastapi import FastAPI
from pydantic import BaseModel
class CourseIn(BaseModel):
title: str
price: float
is_free: bool = False
app = FastAPI()
@app.post("/courses")
def create_course(course: CourseIn):
total = 0 if course.is_free else round(course.price * 1.18, 2)
return {"title": course.title, "price_with_gst": total}Requests and responses
POST /courses {"title": "Docker", "price": 499}
→ 200 {"title": "Docker", "price_with_gst": 588.82}
POST /courses {"title": "Docker"}
→ 422 {"detail": [{"type": "missing", "loc": ["body", "price"], "msg": "Field required", "input": {"title": "Docker"}}]}Body + Path + Query Together
Example
FastAPI tells them apart: names in the path are path parameters, Pydantic models are the body, other simple types are query parameters:
from fastapi import FastAPI
from pydantic import BaseModel
class Update(BaseModel):
title: str
app = FastAPI()
@app.put("/courses/{course_id}")
def update_course(course_id: int, data: Update, notify: bool = False):
return {"id": course_id, "title": data.title, "notify": notify}Requests and responses
PUT /courses/3?notify=true {"title": "CSS Grid"}
→ 200 {"id": 3, "title": "CSS Grid", "notify": true}