Requests and Responses¶
In this section, you'll learn how to handle input and output data using request and response models in Esmerald.
Using Pydantic Models for Requests¶
Esmerald uses Pydantic to define and validate incoming request bodies:
from pydantic import BaseModel
from esmerald import post
class Item(BaseModel):
name: str
price: float
@post("/items")
def create_item(data: Item) -> dict:
return {"name": data.name, "price": data.price}
Sending invalid data returns:
{
"detail": [
{
"loc": ["body", "price"],
"msg": "field required",
"type": "value_error.missing"
}
]
}
Query Parameters and Path Parameters¶
You can use type annotations to declare query and path parameters:
from esmerald import get
@get("/items/{item_id}")
def get_item(item_id: int, q: str = "") -> dict:
return {"item_id": item_id, "query": q}
Response Models¶
You can also define a response model:
class ResponseModel(BaseModel):
name: str
price: float
@post("/items")
def create_item(data: Item) -> ResponseModel:
return ResponseModel(name=data.name, price=data.price)
Custom JSONResponse¶
You can return your own response:
from esmerald.responses import JSONResponse
@get("/custom")
def custom() -> JSONResponse:
return JSONResponse({"message": "Custom"}, status_code=201)
Extra: Headers, Cookies, Files¶
You can also extract headers, cookies, and file uploads via parameters:
from esmerald import Header, Cookie, UploadFile, post, File
@post("/upload")
async def upload(
file: UploadFile = File(),
token: str = Header(value="X-API-TOKEN"),
session: str = Cookie(value="session")
):
return {"filename": file.filename, "token": token, "session": session}
What's Next?¶
You've now learned how to use request and response models with validation.
👉 Continue to routing to organize routes and build modular applications.