Request & Response Types
Leverage the full power of Pydantic models for type-safe request validation and response serialization.
Request Validation
JEC uses Pydantic models to define and validate request bodies. Simply define a Pydantic model and use it as a type hint for your route method argument.
Note: The first argument after self is treated as the request body. JEC will automatically validate the incoming JSON against your model.
from pydantic import BaseModel
from jec_api import Route
# Define your request model
class CreateItemRequest(BaseModel):
name: str
price: float
description: str | None = None
is_offer: bool = False
class Items(Route):
# Use the model as a type hint
async def post(self, item: CreateItemRequest):
# 'item' is now a valid instance of CreateItemRequest
# If validation fails, JEC returns a 422 error automatically
return {"name": item.name, "price": item.price}Response Serialization
Define the structure of your API responses using Pydantic models. By specifying the return type hint, JEC automatically filters and serializes your data to match the model.
from pydantic import BaseModel, EmailStr
from jec_api import Route
class User(BaseModel):
id: int
username: str
email: EmailStr
# Private fields like 'password_hash' are excluded
class UserProfile(Route):
# Define the return type
async def get(self) -> User:
user_data = self.db.get_user(1)
# JEC ensures only fields defined in 'User' are returned
return user_dataAccessing the Request Object
Sometimes you need access to the raw request object (e.g., to read headers, cookies, or client details). You can import Request from FastAPI (or Starlette) and add it as a parameter to your method.
from fastapi import Request
from jec_api import Route
class Debug(Route):
async def get(self, request: Request):
return {
"client_host": request.client.host,
"user_agent": request.headers.get("user-agent")
}