tezvyn:

How FastAPI uses type hints for validation

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Whether you know FastAPI leans on Pydantic and type hints.

OUTLINE

Hints drive parsing, validation, and conversion; a path declared int is coerced or returns 422; OpenAPI is auto-generated.

WHAT THIS TESTS The interviewer wants to confirm you understand FastAPI's defining idea: ordinary Python type hints, interpreted by Pydantic, become the validation and serialization layer. Python ignores hints at runtime, but FastAPI inspects them and acts on them.

A GOOD ANSWER COVERS When you annotate a parameter, FastAPI uses that annotation to parse the raw request value, validate it, and convert it to the declared type. For path and query parameters, which arrive as strings, an int annotation tells FastAPI to coerce the string to an integer. If coercion fails, FastAPI returns an automatic HTTP 422 Unprocessable Entity with a structured error describing what was wrong, and your function body never runs with bad data. The same hints feed the auto-generated OpenAPI schema and the interactive docs, and give editors autocompletion. For request bodies you declare a Pydantic BaseModel, and FastAPI validates the JSON against it the same way.

COMMON WRONG ANSWERS Saying Python enforces the type hints itself; it does not, hints are ignored by the interpreter at runtime and FastAPI is what reads them. Describing manual parsing with int() and try/except, which defeats the declarative point. Forgetting that a validation failure yields a 422 automatically rather than a 500 or a crash.

LIKELY FOLLOW-UPS What status code is returned on a validation error and why? How do query parameters differ from path parameters here? How would you add constraints like a minimum value?

ONE CONCRETE EXAMPLE Consider an endpoint declared as async def read_item(item_id: int) decorated with the path /items/{item_id}. A request to /items/42 passes 42 as an integer into the function. A request to /items/abc cannot be coerced, so FastAPI returns 422 with a message that item_id should be a valid integer, and the handler is never invoked. Adding Path(gt=0) would further reject zero or negatives with the same automatic 422 behavior.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.