Skip to content
tezvyn:

Top 30 Python & FastAPI Interview Questions and Answers

30 multiple-choice questions on Python & FastAPI, of the kind that come up in a technical interview, drawn from 30 bites in the Python & FastAPI library. Answer them here or read straight down. Every question carries the correct option, why it is correct, and a link to the bite it came from.

Python, Django, FastAPI, Flask, async Python

30 questions. Pick an answer, or open “Show the answer” to read it.

Answers are graded in your browser. Nothing is saved, and no XP or streak is earned here. The app keeps score.

  1. Question 1 of 30

    When you annotate a FastAPI route parameter with a Pydantic model, what does the framework do with that type hint?

    Show the answer

    Answer: a · It leverages the hint for automatic request validation and OpenAPI schema generation

    FastAPI reads type hints at startup to construct Pydantic models that validate incoming requests and generate OpenAPI schemas automatically. The distractor about runtime enforcement is wrong because Python itself ignores type hints during execution unless an external tool checks them.

    Read the full bite: Explain Python type hints and their importance in FastAPI

  2. Question 2 of 30

    You write an async def FastAPI endpoint that calls requests.get. What is the main risk?

    Show the answer

    Answer: c · The event loop is blocked, freezing concurrent request handling until the call finishes.

    The correct answer is C because calling a blocking library like requests inside async def stalls the event loop, stopping all other requests. The most tempting distractor is A because beginners often assume FastAPI magically threadpools any blocking code, but only def endpoints are run in a threadpool.

    Read the full bite: What is the difference between def and async def in Python and FastAPI?

  3. Question 3 of 30

    What mechanism triggers FastAPI to automatically validate and parse an incoming JSON request body against a schema?

    Show the answer

    Answer: b · Using a Pydantic model as the type hint for a route parameter

    FastAPI inspects function signature type hints at runtime, so using a Pydantic model as a parameter type hint automatically triggers request parsing and validation. Manually calling json.loads inside the route is a red flag that ignores this declarative mechanism, and response_model governs response serialization, not request validation.

    Read the full bite: How does FastAPI leverage Pydantic for request validation and serialization?

  4. Question 4 of 30

    When building an async execution-time decorator for FastAPI, why is omitting functools.wraps on the inner wrapper considered a red flag?

    Show the answer

    Answer: b · It strips the original function's metadata, which breaks FastAPI's OpenAPI schema generation and dependency injection.

    functools.wraps preserves the original function's name, signature, and metadata, which FastAPI relies on to generate OpenAPI docs and resolve dependencies; omitting it exposes the wrapper's metadata instead. Distractor A is wrong because wraps has no effect on whether code runs synchronously or blocks the event loop.

    Read the full bite: Write an async decorator that logs execution time for FastAPI

  5. Question 5 of 30

    Which implementation correctly minimizes total latency when a FastAPI endpoint must fetch data from two independent external APIs?

    Show the answer

    Answer: a · Inside an async def endpoint, pass two httpx.AsyncClient coroutines to asyncio.gather and await the result.

    asyncio.gather with an async HTTP client schedules both I/O-bound coroutines concurrently on the event loop, reducing total latency to roughly the slower call. Option C is tempting because it uses async/await correctly, but sequential awaiting means the second request cannot start until the first finishes, so latencies add up.

    Read the full bite: How do you structure concurrent API calls with asyncio.gather in FastAPI?

  6. Question 6 of 30

    When a FastAPI endpoint awaiting asyncpg is suspended during a database query, how can Uvicorn process another incoming connection in the same worker process?

    Show the answer

    Answer: d · The event loop yields the coroutine at the await, registers the socket with epoll or kqueue, and schedules the new connection's coroutine on the same thread.

    The correct answer describes cooperative multitasking: the event loop suspends the coroutine at await and interleaves I/O-bound tasks on a single thread. Distractor A is wrong because Uvicorn does not use multiple Python threads to handle requests; concurrency comes from the loop scheduling coroutines, not from threading or GIL behavior.

    Read the full bite: How does Uvicorn use asyncio to handle thousands of concurrent connections?

  7. Question 7 of 30

    In FastAPI, why should an async database session dependency wrap yield in try and place await session.close() in finally?

    Show the answer

    Answer: a · It guarantees cleanup runs even if the path operation raises an exception.

    A try/finally block guarantees that await session.close() runs even when the path operation raises an exception, preventing database connection leaks. The thread pool issue in distractor C is caused by using def instead of async def, not by omitting exception handling.

    Read the full bite: Implement an async database session dependency using yield for setup and teardown

  8. Question 8 of 30

    In Pydantic v2, what is the runtime validation behavior of a generic wrapper field typed as T when the model is used without parametrization?

    Show the answer

    Answer: a · The field is validated as Any, accepting arbitrary data and generating an overly permissive schema

    The card explicitly states that unparametrized TypeVars are treated as Any at validation time, yielding an overly permissive OpenAPI schema. Option C is a tempting distractor because developers often assume missing generic parameters cause runtime errors, but Pydantic v2 gracefully falls back to Any instead.

    Read the full bite: Create a generic Pydantic BaseModel for API response wrappers

  9. Question 9 of 30

    When an incoming GET request reaches a FastAPI app, how does @app.get("/") enable the correct function to run?

    Show the answer

    Answer: d · It registers the function in the app's route table at import time and generates OpenAPI metadata.

    The decorator actively registers the function for GET / in the app's internal route table when the module is imported and simultaneously populates the OpenAPI schema, enabling the ASGI layer to dispatch matching requests. Calling it pure syntax sugar is a common misconception because it fundamentally alters the application's routing registry and automatic documentation rather than leaving framework behavior unchanged.

    Read the full bite: What is the purpose of @app.get("/") in FastAPI?

  10. Question 10 of 30

    Which approach correctly defines a FastAPI endpoint that captures an integer item_id from a URL like /items/42?

    Show the answer

    Answer: a · Use app.get("/items/{item_id}") and define async def read_item(item_id: int): then use item_id directly inside the function

    FastAPI binds curly-braced path segments to function arguments with matching names and type hints, automatically converting and injecting the value. Option B is tempting because the route syntax is correct, but the mismatched argument name breaks the default binding unless you use a Path alias.

    Read the full bite: How do you define and access a FastAPI path parameter?

  11. Question 11 of 30

    A FastAPI endpoint declares a path parameter as item_id: int. A request arrives for /items/abc, which cannot be coerced to an integer. What happens?

    Show the answer

    Answer: a · FastAPI returns an automatic 422 error describing the invalid value, and the endpoint function body never executes

    FastAPI validates the coerced type before your function runs, so an uncoercible value short circuits into an automatic 422 with no handler code executing. Python itself does nothing with the int annotation at runtime, which is why expecting a TypeError or manual parsing misses the point of the hint.

    Read the full bite: How FastAPI uses type hints for validation

  12. Question 12 of 30

    Which FastAPI endpoint declaration identifies a user in the URL path and accepts an optional search term after the question mark?

    Show the answer

    Answer: a · Route /users/{user_id}/items with user_id in path and q optional

    Option A correctly places the user identifier in the path template and gives q a default of None so it becomes an optional query parameter. Option B is tempting because it also makes q optional, but it omits user_id from the path so FastAPI treats it as a query parameter, violating RESTful hierarchy.

    Read the full bite: What is the difference between a path parameter and a query parameter?

  13. Question 13 of 30

    An endpoint declares a query parameter as q: Optional[str] with no default value. What happens when a client omits it?

    Show the answer

    Answer: c · FastAPI returns a 422 Unprocessable Entity error

    FastAPI derives requirement from the presence or absence of a Python signature default, not from type hints, so Optional[str] without = None is still required and omitting it triggers a 422 error. Option D is a common misconception because Optional alone does not make a parameter optional in FastAPI.

    Read the full bite: How does FastAPI distinguish required optional and default query parameters

  14. Question 14 of 30

    What combination of standard and code sources enables FastAPI's automatic interactive documentation?

    Show the answer

    Answer: d · It dynamically builds an OpenAPI schema from type hints, Pydantic models, decorators, and docstrings

    FastAPI dynamically generates an OpenAPI schema by extracting metadata from type hints, Pydantic models, decorators, and docstrings, so no manual schema file is required. Option B is wrong because maintaining a separate openapi.yaml by hand is unnecessary and contradicts FastAPI's design.

    Read the full bite: What standard and code elements power FastAPI's auto-generated API docs?

  15. Question 15 of 30

    A client sends GET /items?limit=foo to an endpoint with parameter limit: int. What is FastAPI's default response?

    Show the answer

    Answer: a · HTTP 422 Unprocessable Entity with a JSON body whose detail array contains objects with loc, msg, and type fields

    FastAPI relies on Pydantic to automatically validate query parameters and returns a 422 Unprocessable Entity with a JSON detail array of objects containing loc, msg, and type fields. Option B is tempting because the status code is correct, but the body structure is actually a detailed array rather than a single string.

    Read the full bite: FastAPI non-integer query param default behavior

  16. Question 16 of 30

    To accept multiple values for a single query key and allow per-item length constraints in current FastAPI, which parameter declaration should you use?

    Show the answer

    Answer: c · tag: Annotated[list[str], Query()] = []

    Annotated[list[str], Query()] = [] is the modern pattern that separates validation metadata from the default value, enabling per-item constraints. tag: list[str] = Query(default=[]) is the outdated alternative that mixes the default with validation metadata.

    Read the full bite: How do you type-hint repeated query params in FastAPI?

  17. Question 17 of 30

    Which statement accurately describes the behavior of {file_path:path} compared to {file_path} in a FastAPI route definition?

    Show the answer

    Answer: c · {file_path:path} uses a Starlette converter to greedily match slashes across segments while {file_path} stops at the next slash

    {file_path:path} relies on Starlette's path converter to consume the rest of the URL including slashes, whereas a plain parameter matches only one segment regardless of the str type hint. Option B is wrong because a str annotation does not make routing greedy, and option A incorrectly confuses a router directive with Pydantic validation.

    Read the full bite: What is the :path converter in FastAPI?

  18. Question 18 of 30

    Which method correctly enables automatic JSON body validation in a FastAPI route?

    Show the answer

    Answer: a · Subclass BaseModel and declare it as the type of a path operation function parameter

    FastAPI inspects path operation parameter type annotations to automatically parse and validate incoming JSON against a Pydantic BaseModel. Manually calling request.json() bypasses this automatic pipeline, and response_model only defines the outgoing response schema rather than request validation.

    Read the full bite: How do you define a Pydantic model for FastAPI request body validation?

  19. Question 19 of 30

    When a FastAPI endpoint receives JSON with extra fields not defined in the Pydantic model, what occurs by default?

    Show the answer

    Answer: d · Pydantic silently drops the extra fields and the request succeeds

    By default Pydantic ignores extra fields, silently dropping them so the model instantiates and the request succeeds. Option C is wrong because that strict 422 behavior only happens when you explicitly configure extra to forbid in model_config.

    Read the full bite: How does Pydantic handle extra JSON fields, and how to configure it?

  20. Question 20 of 30

    What is the key difference between a Pydantic field defined as name: str = 'guest' and one defined as name: Optional[str] = None?

    Show the answer

    Answer: d · The first rejects None while the second accepts it, but both may be omitted from input.

    Both fields have defaults so neither is required, yet str = 'guest' rejects None while Optional[str] = None accepts it. Distractor A is tempting because Optional sounds optional, but requiredness is determined solely by the presence or absence of a default.

    Read the full bite: What is the difference between a Pydantic default and Optional field?

  21. Question 21 of 30

    In Pydantic V2, how should you enforce a positive price and a regex-formatted SKU without writing custom validators?

    Show the answer

    Answer: b · Set price: float = Field(gt=0) and sku: str = Field(pattern=r'^ITEM-\d{5}$') on standard types

    Field's built-in gt and pattern parameters enforce constraints natively without extra code, while @field_validator adds unnecessary boilerplate and ignores Pydantic V2's native capabilities.

    Read the full bite: Enforce positive price and SKU format using Pydantic Field without custom validators

  22. Question 22 of 30

    You are writing a Pydantic v2 model with a name field that must be at least 3 characters. Which implementation is correct?

    Show the answer

    Answer: c · Use @field_validator('name') on a classmethod that raises ValueError and returns the value.

    Pydantic v2 requires single-field validators to use @field_validator on a classmethod, raise ValueError on failure, and return the value so processing continues. Option B is tempting but wrong because omitting the return breaks the model lifecycle, and D uses the deprecated v1 pattern.

    Read the full bite: Implement a custom validator for a single Pydantic model field

  23. Question 23 of 30

    A FastAPI endpoint returns a UserDB model containing password_hash. Which strategy best prevents exposing the hash while keeping the API contract explicit and maintainable?

    Show the answer

    Answer: c · Create a separate UserOut model without password_hash and set response_model=UserOut on the endpoint.

    A dedicated output model declaratively isolates the API contract from the database schema and prevents accidental leaks if new sensitive fields are added later. Option B is a tempting quick fix, but it keeps the sensitive field in the source model and hides the contract outside the type system, making it harder to maintain.

    Read the full bite: How do you prevent password_hash from appearing in a FastAPI response?

  24. Question 24 of 30

    An Order model needs to hold a list of Product models. What is the idiomatic Pydantic way to ensure nested dictionaries are validated and coerced automatically?

    Show the answer

    Answer: b · Annotate the field as list[Product] where Product subclasses BaseModel, relying on Pydantic's recursive schema resolution.

    Annotating the field as list[Product] leverages Pydantic's core schema generation to recursively validate nested items and report precise error paths automatically. Overriding __init__ to manually build Product instances is a red flag because it ignores Pydantic's built-in recursive validation machinery.

    Read the full bite: Model an Order with a nested Product list in Pydantic

  25. Question 25 of 30

    In Pydantic v2, which validator configuration correctly enforces that end_date is after start_date while ensuring both fields are already parsed and coerced?

    Show the answer

    Answer: c · A model_validator with mode='after' that compares self.end_date and self.start_date and raises ValueError on violation

    A model_validator with mode='after' receives the fully constructed instance with coerced datetime objects, making cross-field comparison type-safe and reliable. A model_validator with mode='before' is tempting but forces you to handle raw, unparsed input instead of validated types.

    Read the full bite: Ensure end_date is after start_date in Pydantic

  26. Question 26 of 30

    You define a User model inheriting from BaseModel with name: str and age: int. What missing step lets FastAPI automatically validate an incoming JSON request body against it?

    Show the answer

    Answer: d · Type-hint a path operation parameter with User, e.g., async def create_user(user: User)

    FastAPI treats a parameter type-hinted with a BaseModel subclass as the request body and validates it automatically. Option B is tempting but wrong because parsing the body manually with request.json() skips Pydantic validation and prevents OpenAPI documentation generation.

    Read the full bite: How do you define a Pydantic model and use it in FastAPI?

  27. Question 27 of 30

    What happens to extra fields on an object returned by a FastAPI endpoint when a response_model is declared?

    Show the answer

    Answer: b · FastAPI silently filters out fields not present in the response_model during serialization

    The card explains that FastAPI automatically drops undeclared fields when serializing against the response_model. Option C represents the brittle manual approach the card explicitly warns against, whereas the response_model is designed to handle filtering for you.

    Read the full bite: How would you use a Pydantic response_model to enforce output structure?

  28. Question 28 of 30

    In FastAPI, what primarily determines whether a function parameter is treated as a path parameter instead of a query parameter?

    Show the answer

    Answer: b · If the parameter name appears inside braces in the route path string

    FastAPI inspects the route path template and treats parameters named in braces as path variables, while all others become query parameters. Although Path() can add metadata, it is not required for basic inference, and default values determine optionality rather than parameter location.

    Read the full bite: Define a FastAPI endpoint with path and query parameters

  29. Question 29 of 30

    A FastAPI endpoint with parameters file: UploadFile and user_id: str fails when receiving multipart form-data. What is the most likely reason?

    Show the answer

    Answer: a · FastAPI assumes both parameters come from the JSON body because they lack File() and Form() metadata.

    Without File() or Form() metadata, FastAPI assumes parameters arrive in the JSON body, which breaks multipart form-data parsing. Distractor A reverses the memory behavior: UploadFile spools large files, while bytes loads everything into memory.

    Read the full bite: Implement a FastAPI file upload endpoint with form data

  30. Question 30 of 30

    In FastAPI, which approach best implements a reusable current-user check that preserves OpenAPI docs integration and keeps endpoints testable?

    Show the answer

    Answer: a · Define a get_current_user dependency that uses OAuth2PasswordBearer, validates the token, returns a User model, and inject it into routes with Depends.

    A dedicated get_current_user dependency keeps auth explicit in the signature, auto-documents security in OpenAPI, and enables test overrides via app.dependency_overrides. Middleware hides the dependency from the docs and complicates testing.

    Read the full bite: How do you create a reusable current-user dependency in FastAPI?

Could you explain these out loud?

That is what an interview actually tests. Tezvyn gives you questions like these with what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon