Pydantic and FastAPI
Practice this questionOverview
- Pydantic validates data against Python model definitions.
- FastAPI uses declared routes and schemas to build HTTP services with validation and API documentation.
- Think of Pydantic as a role similar to Zod and FastAPI as a Python web framework with typed request handling.
Why this matters
Document pipelines and model outputs need explicit runtime contracts, and Node services need a stable way to call Python capabilities.
An everyday example
The reception desk checks that a submitted form contains the right fields before passing it to an assessor.
A technical example
A /extract route accepts a bounded description and returns validated fields.
How it works
- HTTP body
- Request schema validation
- Authentication/authorization dependency
- Application logic
- Response schema validation
- JSON response.
Architecture and flow
Node API → authenticated FastAPI endpoint → Pydantic → extraction service → validated result.
The insurance assistant example
Python extracts fields from a repair invoice, while Node continues to own customer identity and claim transactions.
When to use it
When Python libraries, local inference, or numerical processing materially improve the solution.
When to avoid it
Do not add another service solely because AI is associated with Python. A hosted LLM call works well from Node.
Interview answer
“FastAPI provides the HTTP boundary and Pydantic validates the data. Neither replaces authentication, business rules, or durable jobs for long processing.”
Benefits, trade-offs, and production considerations
- Pydantic may coerce values unless strict behavior is configured.
- Keep this deliberate for external input.
- Do not send a 200 response for a failed model extraction.
- Pydantic models.
# Minimal teaching route; production requires auth, quotas, tracing, and an extractor.
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, Field
app = FastAPI()
class DescriptionInput(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
text: str = Field(min_length=1, max_length=10000)
class DescriptionSummary(BaseModel):
character_count: int
needs_document_review: bool
@app.post("/inspect", response_model=DescriptionSummary)
async def inspect(body: DescriptionInput) -> DescriptionSummary:
# Deterministic example: demonstrates routing and validation, not AI extraction.
return DescriptionSummary(
character_count=len(body.text),
needs_document_review="invoice" in body.text.lower(),
)