Requests
Validate incoming payloads with FormRequest, shape responses with FormResponse, and read request data anywhere.
Alata models every JSON payload as a typed class. alata.http.request provides two base classes — FormRequest for incoming bodies and FormResponse for outgoing ones — that wrap pydantic models with framework-level conveniences: automatic whitespace trimming, rejection of unknown fields, and helper methods for slicing validated data.
Form Requests
Subclass FormRequest in app/http/requests/ for every endpoint that accepts a JSON body. Field and model_validator are re-exported from alata.http.request, so your request files never import pydantic directly:
from alata.http.request import FormRequest, Field
class StorePostRequest(FormRequest):
title: str = Field(..., min_length=1)
body: str = Field(...)Type-hint a route handler with the class and validation happens before your code runs:
@api_router.post("/posts", status_code=201)
async def store_post(request: StorePostRequest):
print(request.title) # attribute access, fully typedTwo behaviours are built into every FormRequest:
- String trimming — leading and trailing whitespace is stripped from every
strfield before validation (str_strip_whitespace). - Unknown fields are rejected — any JSON key the client sends that is not declared on the model triggers a 422 error (
extra: "forbid"). This prevents mass-assignment style attacks by default.
Because extras are forbidden, adding a field to your API means adding it to the request class — a client sending an undeclared key gets a 422, not a silent drop. If a specific request must tolerate extra keys, override model_config on that subclass.
Validation failures never reach your handler. The central exception handler renders them as a structured 422 response:
{
"error": "Unprocessable Entity",
"message": "The given data was invalid.",
"errors": { "title": "String should have at least 1 character" }
}Retrieving Validated Input
Every FormRequest carries three helpers for working with the validated data as plain dicts:
data = request.validated() # all fields as a dict
data = request.only("title", "body") # just these keys
data = request.except_("password_confirmation") # everything but thesevalidated() is handy when passing the whole payload to a model or service; only() and except_() let you slice it without dict comprehensions in your handlers.
Cross-Field Validation
Use the re-exported model_validator for rules that span multiple fields:
from alata.http.request import FormRequest, model_validator
class RegisterRequest(FormRequest):
password: str
password_confirmation: str
@model_validator(mode="after")
def passwords_match(self):
if self.password != self.password_confirmation:
raise ValueError("Passwords do not match.")
return selfForm Responses
FormResponse is the mirror image for outgoing payloads. It enables from_attributes, so you can build a response directly from a database model instance, and ignores extra attributes — your model can carry more columns than the response exposes:
from alata.http.request import FormResponse
class UserResponse(FormResponse):
id: int
name: str
email: str@api_router.get("/users/{user_id}", response_model=UserResponse)
async def show_user(user_id: int):
user = await User.afind_or_fail(user_id)
return UserResponse.model_validate(user)Declaring response_model also filters the OpenAPI schema, so /docs shows exactly what the endpoint returns.
Headers, Query Strings, and Client Info
FormRequest covers the JSON body. For everything else about the incoming request — headers, cookies, the client address, the raw URL — type-hint the standard Request object in any handler:
from alata.http import Request
@api_router.get("/whoami")
async def whoami(request: Request):
return {
"ip": request.client.host,
"user_agent": request.headers.get("User-Agent"),
"path": request.url.path,
"query": dict(request.query_params),
}Request State
Middleware stores per-request values on request.state. Out of the box:
request.state.request_id— set by the request-logging middleware (from the incomingX-Request-IDheader, or generated), and echoed on responses except for paths excluded from request logging.request.state.user_id— set by the scaffold'sIdentityMiddlewarefrom theX-User-Id/X-Guest-Idheaders, falling back to"anonymous".
The dependencies in app/http/dependencies.py expose this identity to handlers. The scaffold reads identity headers for demonstration; it does not verify credentials. Replace this with validated session or token authentication before using these helpers to protect routes.
Request Context Outside the Request
Services and actions often need to know who is acting without threading a request object through every call. alata.context provides async-safe, request-scoped context variables for exactly this:
from alata.context import user_id_context, request_contextuser_id_context: ContextVar[str | None]— the acting user's id.request_context: ContextVar[dict | None]— arbitrary per-request metadata.
They default to None. The scaffold's identity middleware sets user_id_context when an identity header is present and resets it after the request. Populate request_context yourself when you need additional metadata; see request context.
The "anonymous" fallback belongs on request.state only. Leaving user_id_context unset lets the rate limiter use the client's IP for anonymous requests.
from alata.context import user_id_context
def audit(action: str):
actor = user_id_context.get() or "system"
...The exception handler reads user_id_context automatically — when it is set, every reported exception includes the acting user's id in its log context. Because ContextVar is task-local, values never leak between concurrent requests.