Loading...
Loading...
Backend interview guide
Routes, validation with Pydantic, dependencies, async endpoints and security. Every answer is short enough to say aloud, and every question links to the lesson that teaches it.
54 questionsLast updated
If the name is in the path template, it is a path parameter. If the type is a Pydantic model, it is read from the JSON body. Any other simple type (int, str, bool, list with Query) is a query parameter. You can force the source with Path, Query, Header, Cookie or Body.
Lesson: Routes and Parameters422 is what FastAPI sends by itself when a path, query or body value fails validation. 404 is raised by your code with HTTPException when a record does not exist. 400 is a general bad request that you choose for rules the type check cannot see, such as a date range where the start is after the end.
Lesson: Routes and ParametersFastAPI tries routes in the order they were added and uses the first match. A path with a parameter such as /orders/{order_id} would capture /orders/latest, so the fixed path must be defined first.
Lesson: Routes and ParametersPass status_code to the decorator, for example @app.post("/orders", status_code=201). Use 201 for created, 202 for accepted and 204 for success with no body. The fastapi.status module has named constants such as status.HTTP_201_CREATED.
Lesson: Routes and ParametersAnnotated attaches extra information to a type, so the type stays int while Path(ge=1) or Query(max_length=10) adds the rules. It also lets a default value stay a normal default. It is the style the FastAPI docs recommend now.
Lesson: Routes and ParametersFastAPI returns 422 with a detail list. Each item has loc (where), msg (the message) and type (the error kind). Your function is not called at all.
Lesson: Routes and ParametersYes. FastAPI reads the path parameter from the URL and the model argument from the body. This is common for PUT and PATCH routes such as PUT /customers/{id}.
Lesson: Routes and ParametersUse def when the body calls blocking code such as a normal database driver, because FastAPI runs it in a thread pool. Use async def only when you await async libraries. A blocking call inside async def freezes the whole event loop.
Lesson: Routes and ParametersPydantic is a library that checks and converts data using Python type hints. FastAPI uses it to read request bodies, validate query and path values, filter responses and build the OpenAPI schema, so one class does all four jobs.
Lesson: Pydantic Models and ValidationA request model describes what the client may send, for example email and password. A response model describes what the API sends back, for example id and email. Keeping them separate stops secrets and internal fields from leaking and lets each one change on its own.
Lesson: Pydantic Models and ValidationFastAPI runs the returned value through the response model, drops the fields the model does not have and converts types. It also writes the response shape into the docs. response_model_exclude_unset=True can further skip fields that were never set.
Lesson: Pydantic Models and ValidationFastAPI sends it automatically when request validation fails. The body is {"detail": [...]} and each item has type, loc, msg and input. Your function never runs. You can change the shape with an exception handler for RequestValidationError.
Lesson: Pydantic Models and ValidationA default such as [] would be shared if it were one object. Pydantic copies simple defaults, but default_factory states the intent clearly and works for any value that must be new per object, such as list, dict or a timestamp function.
Lesson: Pydantic Models and ValidationUse @field_validator("field_name") on a classmethod. It receives the value, may change it and returns it, or raises ValueError. For a rule that compares two fields, use @model_validator(mode="after").
Lesson: Pydantic Models and Validationmodel_dump() makes a plain dict, useful for saving or merging. A FastAPI route can return the model directly and FastAPI converts it to JSON. With response_model set, the returned value is checked again against that model.
Lesson: Pydantic Models and ValidationNo. A Pydantic model checks data going in and out of the API. A SQLAlchemy model maps a table. Keeping them apart lets the API shape and the table change independently. Pydantic can read database objects with from_attributes=True.
Lesson: Pydantic Models and ValidationFastAPI reads route decorators, function signatures, type hints and Pydantic models, and builds an OpenAPI schema from them. It serves that schema as JSON and renders Swagger UI at /docs and ReDoc at /redoc from it. Because the docs come from the code, they match the real behaviour.
Lesson: Automatic Docs and OpenAPIBoth read the same OpenAPI schema. Swagger UI is interactive: you can fill in parameters and send requests from the page. ReDoc is a clean reading view, often used as the public reference. FastAPI serves both by default.
Lesson: Automatic Docs and OpenAPITools can read /openapi.json to generate client libraries, create mock servers, run contract tests and check for breaking changes between releases. Teams treat the schema as the API contract.
Lesson: Automatic Docs and OpenAPIPass docs_url=None and redoc_url=None, and openapi_url=None if even the schema should be hidden, to FastAPI(). Often these values are chosen from a setting such as the environment name. include_in_schema=False hides one route only.
Lesson: Automatic Docs and OpenAPIUse Field(description="...", examples=[...]) on a field, or model_config with json_schema_extra for the whole model. They are copied into the schema and shown on the docs page, which helps people who call the API.
Lesson: Automatic Docs and OpenAPIAny route with path, query or body input can fail validation, so FastAPI adds a 422 response with the HTTPValidationError schema. You can add other responses, such as 404, with the responses argument of the decorator.
Lesson: Automatic Docs and OpenAPIPass responses={404: {"description": "Order not found"}} to the decorator, optionally with a model. The code still has to raise HTTPException itself; the responses argument only documents it.
Lesson: Automatic Docs and OpenAPIList the resources and routes first (method, path, success and failure codes). Write input and output Pydantic models, then the route functions, with HTTPException for missing records. Test every route with TestClient for success and failure, and check the docs. Later, move storage into a database layer.
Lesson: FastAPI Basics Checkpoint422 comes from FastAPI when the request shape or types are wrong. Your code returns 404 when a record is missing, 409 for a conflict such as a duplicate email, and 400 for a business rule that the schema cannot express. Each code tells the client what it can do next.
Lesson: FastAPI Basics CheckpointThe input has fields the client controls, such as a password. The output has fields the server controls, such as id and created time. Separate models stop clients from setting server fields and stop the server from leaking private fields, and the docs show both shapes clearly.
Lesson: FastAPI Basics CheckpointUse fastapi.testclient.TestClient(app). It calls the ASGI app in-process, so client.get(), client.post(json=...) return real responses with status_code and json(). Tests run fast and need no network.
Lesson: FastAPI Basics CheckpointAdd skip and limit query parameters with defaults and limits (Query(ge=0), Query(le=100)), then slice or use OFFSET and LIMIT in the database. Bounded limits prevent one request from returning a whole table.
Lesson: FastAPI Basics CheckpointIt works for demos and tests, but data is lost on restart, is not shared between worker processes, and is not safe for concurrent writes. A real app uses a database; the route code should talk to a storage layer so the change is easy.
Lesson: FastAPI Basics CheckpointEach part has one job: routers handle HTTP, services hold business rules, repositories talk to storage. The code stays readable as it grows, rules can be tested without HTTP, and the database can change without rewriting the routes.
Lesson: Routers and LayersIt groups routes by topic into separate files, with a shared prefix, tags and dependencies. The main app includes each router, so main.py stays small, and teams can work on different routers at the same time.
Lesson: Routers and LayersIn the route (or a handler). The service raises its own domain errors such as DuplicateProduct, which carry meaning but not HTTP codes. The route, or one exception handler for the whole app, converts them to 409, 404 and so on. This keeps services reusable from scripts and background jobs.
Lesson: Routers and LayersA repository hides how data is stored behind methods such as add, get and find_by_email. The service calls those methods and does not know whether the data is in SQL, a dict or an API. It makes tests easy with a fake repository.
Lesson: Routers and LayersYes, it can be. Start with one file, then split when a file becomes hard to read or when you need to test rules alone. The layers are a tool to manage growth, not a rule for every project.
Lesson: Routers and LayersCreate a router per version, for example api_v1 with prefix /api/v1, include the topic routers in it, and include it in the app. A later /api/v2 can reuse some routers and replace others.
Lesson: Routers and LayersThe Pydantic models for requests and responses, such as ProductIn and ProductOut. They describe the API shape. Keep them apart from the database models, because the table and the API contract change for different reasons.
Lesson: Routers and LayersA function declares what it needs instead of creating it. In FastAPI you write a parameter with Depends(provider). FastAPI calls the provider for each request, resolves the providers it needs in turn, and passes the results in. It makes code shorter, shared and easier to test.
Lesson: Dependency Injection with DependsThe code before yield runs before the route and the yielded value is passed to it. The code after yield runs after the response is prepared, so it is the place to close sessions and release resources. Put it in try/finally so the cleanup also runs when the route raises an error.
Lesson: Dependency Injection with DependsSet app.dependency_overrides[get_db] to a function that yields a test session, for example one bound to an in-memory SQLite engine with StaticPool, then call the route with TestClient and clear the overrides afterwards. The route code stays unchanged.
Lesson: Dependency Injection with DependsOnce per request by default. If two parameters or two sub-dependencies use the same provider, FastAPI caches the result for that request. You can turn this off with Depends(provider, use_cache=False) when each use must get a fresh value.
Lesson: Dependency Injection with DependsOn a single parameter, in the decorator with dependencies=[Depends(...)] when the value is not needed, on a router with APIRouter(dependencies=[...]), or on the whole app with FastAPI(dependencies=[...]). Router and app level dependencies suit checks such as authentication.
Lesson: Dependency Injection with DependsA class can be a dependency because calling a class is calling a callable. FastAPI reads its __init__ parameters like a function, and the route receives the object. Classes are useful when you want attributes and methods, such as a pagination object with an offset property.
Lesson: Dependency Injection with DependsA single shared session would be used by all requests at the same time, leaking state and mixing transactions. A per-request session from a dependency is created, committed or rolled back and closed for exactly one request.
Lesson: Dependency Injection with DependsThe twelve-factor approach keeps configuration out of the code, so one build can run in development, test and production with different values. Secrets stay out of Git, and hosting services let you set variables without changing files.
Lesson: Settings and EnvironmentsOne place to read the environment makes the app easy to follow: you can see every setting, validate them at start-up, and pass the object to code that needs it. Code that reads os.environ directly is hard to test and hides its needs.
Lesson: Settings and EnvironmentsIt is a separate package with a BaseSettings class that reads environment variables and .env files, converts types and validates them. In a real project it replaces a hand-written loader. A small loader with a plain BaseModel gives the same idea when the package is not available.
Lesson: Settings and EnvironmentsEvery environment value is a string and any non-empty string is truthy, so bool("false") is True. A loader must compare text, for example value.lower() in ("1", "true", "yes"), or let Pydantic parse it.
Lesson: Settings and EnvironmentsDo not read the environment inside the code under test. Build a Settings object with test values and pass it in, or override the get_settings dependency in FastAPI. When you must change the environment, use patch.dict and clear any cached settings.
Lesson: Settings and EnvironmentsThe settings are built once per process, so changing the environment later has no effect until cache_clear() is called. That is the wanted behaviour in production, but a surprise in tests that change variables after the first call.
Lesson: Settings and EnvironmentsDo not commit them. Set them as environment variables or in the host secret manager, give the code only the names, and fail at start-up in production when a secret is missing or still has its development default. Rotate a secret that was ever exposed.
Lesson: Settings and EnvironmentsRaise HTTPException with a status code and detail from a route or dependency. For errors that come from deeper layers, raise your own exception classes and register handlers with @app.exception_handler so one place maps them to responses.
Lesson: Error HandlingA returned dict would be sent with status 200 unless you also set the status, and the route keeps running code after the error. Raising ends the route at once, sets the right code and works from helper functions and dependencies too.
Lesson: Error HandlingPick one body shape, use it in custom exception handlers, and override the handlers for RequestValidationError and StarletteHTTPException so FastAPI-made errors (422, 404 for unknown paths, 405) use it too. Document the shape in the docs.
Lesson: Error HandlingFastAPI HTTPException subclasses the Starlette one. FastAPI raises its own in your code, but Starlette raises its class for unknown paths and wrong methods. Register your handler for the Starlette class so both are caught.
Lesson: Error HandlingEach lesson has quizzes, practice and more interview questions on the same topic.
Open the first lesson