Skip to content
tezvyn:

Top 30 Easy Python & FastAPI Interview Questions and Answers for Freshers

30 easy multiple-choice Python & FastAPI interview questions, the ones an interviewer opens with: definitions, everyday syntax, and the quick checks that you have really used it. They come from 30 bites in the Python & FastAPI library, the gentlest slice of the 133 Python & FastAPI interview questions in the 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

    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?

  4. Question 4 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?

  5. Question 5 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?

  6. Question 6 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?

  7. Question 7 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?

  8. Question 8 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?

  9. Question 9 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?

  10. Question 10 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

  11. Question 11 of 30

    What is the main reason to declare a FastAPI dependency in a path operation parameter?

    Show the answer

    Answer: a · To let FastAPI automatically inject reusable logic so routes stay focused on HTTP concerns.

    The correct answer is C because dependency injection allows FastAPI to wire reusable components into routes, keeping handlers clean. A is tempting because it describes calling helpers, but that misses the inversion-of-control pattern where the framework injects the dependency rather than the route calling it manually.

    Read the full bite: How do you declare a function as a dependency, and why?

  12. Question 12 of 30

    In a FastAPI dependency using yield, which statement accurately describes the execution flow?

    Show the answer

    Answer: d · Code before yield runs as setup, and code after yield runs as teardown post-response

    The card explains that yield splits a dependency into setup (before yield) and teardown (after yield), with cleanup running only after the response is fully sent. Option B is a tempting distractor because candidates often assume the dependency resumes immediately after yielding, not realizing teardown waits until after the response completes.

    Read the full bite: What is the purpose of yield in a dependency function?

  13. Question 13 of 30

    Which is the correct way to apply a shared dependency to every route in an APIRouter without adding it to each endpoint signature?

    Show the answer

    Answer: d · Pass a list of Depends() instances to the dependencies parameter when creating the APIRouter

    APIRouter's dependencies parameter automatically injects shared dependencies into every mounted route while keeping endpoint signatures clean and preserving OpenAPI docs. Middleware runs globally on all requests rather than being router-scoped, and custom decorators break FastAPI's automatic schema generation.

    Read the full bite: How do you apply a dependency to an APIRouter without per-endpoint signatures?

  14. Question 14 of 30

    Which scenario best illustrates why APIRouter is considered a first-class modularity primitive in FastAPI?

    Show the answer

    Answer: a · Moving route definitions into separate files so they can be mounted with prefixes, tags, and shared dependencies via include_router.

    APIRouter is a standalone object that lets routes live in dedicated modules and be mounted with app.include_router, inheriting prefixes, tags, and dependencies. Option B is tempting but wrong because merely shortening main.py misses the include_router mechanism and inherited configuration that makes routers a structural primitive.

    Read the full bite: What is APIRouter in FastAPI and why use it?

  15. Question 15 of 30

    In a maintainable multi-file FastAPI project, where should reusable dependencies be placed to avoid tight coupling?

    Show the answer

    Answer: d · In a dedicated dependencies module imported relatively by routers

    The card states reusable dependencies should live in their own module and be imported relatively into router modules, rather than being defined inline everywhere. Option C is tempting but wrong because placing them in the main module encourages routers to import from the main app, creating circular imports and tight coupling.

    Read the full bite: Describe a common FastAPI project structure and key directories

  16. Question 16 of 30

    You have defined routes using APIRouter in a separate file. What is the correct final step in main.py to make those routes available?

    Show the answer

    Answer: a · Import the router object and call app.include_router(router)

    Calling app.include_router(router) is the required step to mount the imported router on the FastAPI instance. Simply importing the module is not enough, as FastAPI does not auto-register routes from imported files.

    Read the full bite: How do you include a router in your main FastAPI app?

  17. Question 17 of 30

    What is the immediate result of calling an async def function without using await?

    Show the answer

    Answer: d · A coroutine object is returned but the body has not yet executed

    Calling an async def function returns a coroutine object immediately without running any of the function body; execution only begins when the object is awaited or wrapped in create_task. The distractor that it runs up to the first await is wrong because the body does not start executing at all upon the bare call.

    Read the full bite: What is the difference between async def and regular functions?

  18. Question 18 of 30

    What occurs when await is used on an awaitable inside an async function?

    Show the answer

    Answer: a · It yields control to the event loop so other tasks may run during the wait

    await suspends the current coroutine and yields control back to the event loop so other tasks can run while this one waits. The blocking thread distractor is wrong because await does not freeze the thread like time.sleep; instead, the event loop schedules a callback to resume the coroutine when the awaitable completes.

    Read the full bite: Explain await's purpose, awaitable types, and event loop signaling

  19. Question 19 of 30

    Which pattern correctly wires SQLAlchemy from configuration to endpoint in FastAPI without risking connection leaks?

    Show the answer

    Answer: d · Define a module-level engine and sessionmaker, then yield request-scoped sessions in a dependency with cleanup in a finally block.

    Option D is correct because a single engine manages the connection pool globally, and yielding sessions with a finally block ensures each request gets its own safely closed session. Option A is tempting but wrong because creating an engine per request is expensive and defeats connection pooling, quickly exhausting database resources.

    Read the full bite: Describe SQLAlchemy setup in FastAPI from database config to endpoint

  20. Question 20 of 30

    In FastAPI, why should a POST endpoint use a dedicated Pydantic model instead of the SQLAlchemy ORM model for the request body?

    Show the answer

    Answer: a · Using the ORM model directly couples the API contract to the database schema and lets clients set server-generated fields like IDs.

    Using the ORM model as a request body leaks database internals and allows clients to forge server-generated fields like primary keys. Option D is tempting because reducing duplication seems desirable, but accidental coupling between the API contract and database schema creates larger maintenance and security risks.

    Read the full bite: Explain SQLAlchemy ORM vs Pydantic models in FastAPI

  21. Question 21 of 30

    What does FastAPI automatically do when you inject an OAuth2PasswordBearer instance into an endpoint using Depends?

    Show the answer

    Answer: c · Expect a Bearer token in the Authorization header, return 401 if absent, and add security metadata to OpenAPI docs

    Injecting OAuth2PasswordBearer via Depends tells FastAPI to require an Authorization: Bearer header, automatically return 401 if it is missing, and document the requirement in OpenAPI. Option D is tempting but wrong because the scheme itself does not query a database or return a user object; that requires a separate custom dependency.

    Read the full bite: How do you protect a FastAPI endpoint using Depends and OAuth2PasswordBearer?

  22. Question 22 of 30

    Which statement accurately describes the structure and security properties of a typical signed JWT's three dot-separated parts?

    Show the answer

    Answer: d · The header specifies the algorithm and token type, the payload carries visible claims such as exp, and the signature provides integrity but not confidentiality.

    The header contains metadata like alg and typ, the payload carries claims such as exp that anyone can read by Base64Url-decoding, and the signature ensures integrity without confidentiality. The most tempting distractor confuses encoding with encryption or swaps the roles of the header and payload, which are exactly the misconceptions the card flags as red flags.

    Read the full bite: What are the three components of a JWT?

  23. Question 23 of 30

    Which storage and verification approach best protects passwords during a total database breach?

    Show the answer

    Answer: b · Hashing with bcrypt using a unique salt per password and constant-time comparison on login

    bcrypt is intentionally slow and one-way, making offline brute force impractical, while unique salts defeat rainbow tables and constant-time comparison prevents timing leaks. SHA-256 with a unique salt is tempting because salting is correct, but the algorithm remains too fast to resist brute-force attacks.

    Read the full bite: How should you store user passwords in a database?

  24. Question 24 of 30

    Why does a browser block a frontend on localhost:3000 from calling a FastAPI backend on localhost:8000, and what is the proper fix?

    Show the answer

    Answer: b · The browser considers them different origins because the ports differ; add CORSMiddleware to FastAPI with the frontend origin in allow_origins.

    The browser treats protocol, host, and port as an origin tuple, so localhost:3000 and localhost:8000 are cross-origin and CORSMiddleware must explicitly allow the frontend. The distractor that claims they are the same origin because they share localhost reflects a fundamental misunderstanding of the same-origin policy.

    Read the full bite: Frontend on localhost:3000 gets errors calling FastAPI on localhost:8000. Name and fix?

  25. Question 25 of 30

    Which pattern should you use in a FastAPI endpoint to send a confirmation email after the HTTP response has already returned to the client?

    Show the answer

    Answer: d · Inject BackgroundTasks into the endpoint, call add_task with the email function, and then return the response

    BackgroundTasks is built into FastAPI to run work after the response is sent without extra infrastructure. asyncio.create_task is a tempting distractor because it schedules a coroutine but does not guarantee execution if the connection drops, whereas Celery adds unnecessary complexity and returning 202 implies an external queue that is not actually being used.

    Read the full bite: How do you send an email without blocking a FastAPI request?

  26. Question 26 of 30

    Where should you place a start-time variable in FastAPI middleware to measure total request latency?

    Show the answer

    Answer: c · Before await next(request), then compute elapsed after the call returns

    You must record the start time before await next(request) and calculate latency afterward, because the endpoint executes during that call. Option B would yield near-zero milliseconds since the timer starts after processing completes, and Option D incorrectly assumes both middleware blocks run before the path operation.

    Read the full bite: Purpose of await next(request) in FastAPI middleware and timing effects

  27. Question 27 of 30

    You need to write a pytest test that verifies a FastAPI GET endpoint returns the expected JSON. Which implementation follows the correct TestClient pattern?

    Show the answer

    Answer: b · Import TestClient from fastapi.testclient and the app from the application module, define test_get_item, create client = TestClient(app), call response = client.get("/items/1"), and assert response.status_code == 200 and response.json() == expected.

    The correct answer imports the real app and TestClient, uses the test_ prefix so pytest discovers it, and asserts on both status_code and json(). Option D is a tempting look-alike but omits the test_ prefix, causing pytest to silently skip the test.

    Read the full bite: How do you test a FastAPI GET endpoint with pytest and TestClient?

  28. Question 28 of 30

    When testing a FastAPI app, what makes TestClient fundamentally different from using the requests library?

    Show the answer

    Answer: a · TestClient couples directly to the app instance and runs without an HTTP server

    TestClient accepts the FastAPI app directly and invokes it internally without starting an HTTP server, making tests faster and simpler. Although its API resembles requests, it is not a wrapper around requests; it is built on HTTPX and purpose-built for framework-level testing.

    Read the full bite: What is FastAPI's TestClient and how does it differ from requests?

  29. Question 29 of 30

    You need to set the API title and version so they render automatically in Swagger UI and ReDoc. Which approach follows FastAPI's convention-over-configuration philosophy?

    Show the answer

    Answer: a · Pass title, description, and version as keyword arguments to the FastAPI() constructor

    FastAPI accepts title, description, and version directly in the FastAPI() constructor, automatically injecting them into the OpenAPI schema and both doc UIs without extra code. Manually editing the schema dictionary is a common misconception that ignores the framework's built-in metadata support.

    Read the full bite: How do you add a title, description, and version to FastAPI auto-docs?

  30. Question 30 of 30

    How do you correctly set the summary and description for a FastAPI endpoint so they appear in Swagger UI?

    Show the answer

    Answer: d · Pass them as keyword arguments to the path operation decorator such as app.get or use the function docstring for description

    FastAPI generates Swagger UI metadata from decorator arguments like summary and description, or automatically from the function docstring. Confusing this with Pydantic Field descriptions is wrong because those only document model fields, not the endpoint itself.

    Read the full bite: Add summary and description to a FastAPI endpoint for Swagger UI

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