Top 30 Easy Python & FastAPI Concepts Quiz for Beginners
30 easy multiple-choice Python & FastAPI concept questions, the vocabulary and first principles, the parts you need before anything else makes sense. They come from 30 bites in the Python & FastAPI library, the gentlest slice of the 109 Python & FastAPI concept 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.
Question 1 of 30
What is the primary mechanism by which Python type hints improve code reliability?
Show the answer
Answer: c · They enable static analysis tools to identify potential type mismatches before execution.
Type hints are ignored by the Python interpreter at runtime. Their primary role is to allow static analysis tools to check for type consistency and potential errors before the code is ever executed, improving reliability. They do not perform runtime validation of external data.
Read the full bite: Python Type Hints: Documentation Your Linter Can Read
Question 2 of 30
For which scenario would a Python dataclass be the most suitable choice?
Show the answer
Answer: d · Creating a simple data structure to represent an API response with predefined fields.
Dataclasses are designed for classes whose primary purpose is to store and group data, making them perfect for structured records like API responses. They are not recommended for classes with complex logic, intricate state, or custom initialization needs, which are better handled by regular classes.
Read the full bite: Python Data Classes: Write Less Boilerplate
Question 3 of 30
What is the primary function of an __init__.py file in a Python directory?
Show the answer
Answer: c · To explicitly designate the directory as a Python package.
The card states that "Its mere presence turns a regular directory into an importable package," indicating its fundamental role is to mark a directory as a package. While it can contain code to import sub-modules (option A), this is an optional setup task, not its primary function of defining the package itself.
Read the full bite: Python Packages: Grouping Modules with __init__.py
Question 4 of 30
What primary problem do Python Enums address in code?
Show the answer
Answer: c · Making code more readable and less prone to errors when using fixed sets of values.
The card states Enums solve the problem of "magic values" by providing a "robust, readable, and type-safe way to define a fixed set of named constants," making code's intent "immediately clear." While Enums contribute to type safety, their primary purpose is to replace obscure "magic numbers" with meaningful names for fixed sets of choices, improving readability and reducing errors from typos or misunderstandings.
Read the full bite: Python Enums: Give Names to Magic Numbers
Question 5 of 30
What is the primary reason for creating a single FastAPI instance (e.g., app = FastAPI()) for your application?
Show the answer
Answer: d · It serves as the central manager for all routing, configuration, and lifecycle events.
The FastAPI instance acts as the central, authoritative object that orchestrates the entire application, managing all routing, configuration, and lifecycle events. While it does contribute to API documentation, that is a feature derived from its central management role, not its primary purpose for being a single instance.
Read the full bite: FastAPI Application Instance: Your API's Central Hub
Question 6 of 30
Which scenario represents an inappropriate use of a FastAPI path operation decorator's arguments?
Show the answer
Answer: c · Dynamically changing the HTTP status code based on specific input conditions.
FastAPI decorator arguments are designed for static configuration, such as setting a default status code or grouping endpoints. Dynamic logic, like returning different status codes based on request input, should be handled within the endpoint function itself, not via decorator arguments.
Read the full bite: FastAPI: Configure Endpoints with Decorators
Question 7 of 30
In FastAPI, what is the primary consequence of defining a path parameter without a type hint (e.g., item_id instead of item_id: int)?
Show the answer
Answer: c · The path parameter will always be treated as a string, regardless of its content.
The card explicitly states that 'without int, 123 is just a string,' meaning FastAPI treats untyped path parameters as strings by default. FastAPI does not infer types for path parameters; it requires explicit type hints for validation and conversion.
Read the full bite: Path Parameters: Turning URL Parts into Variables
Question 8 of 30
For which purpose are FastAPI query parameters most appropriately used?
Show the answer
Answer: b · To provide optional criteria for filtering or paginating a list of items.
The card states query parameters are for optional data like filtering, pagination, or sorting a collection of resources. Options A and D describe the purpose of path parameters, while option A describes when to use a request body, not query parameters.
Read the full bite: FastAPI Query Parameters: Beyond the URL Path
Question 9 of 30
What is the primary benefit of using Uvicorn workers for a FastAPI application in production?
Show the answer
Answer: d · It allows the application to utilize multiple CPU cores for concurrent request processing.
Uvicorn workers are designed to scale your application by running multiple processes, each capable of handling requests, thereby utilizing all available CPU cores to process requests concurrently. Options A and B are incorrect because workers actually complicate debugging and disable auto-reloading; option A is wrong as workers do not fix fundamentally slow or blocking application logic.
Read the full bite: Uvicorn Workers: Scaling Your FastAPI App
Question 10 of 30
To define a Pydantic model field named "notes" that can be entirely absent from input data without causing a validation error, which definition should be used?
Show the answer
Answer: b · notes: str | None = None
The definition "notes: str | None = None" correctly makes the field optional because it provides a default value of None. If the field is missing from the input, Pydantic will use None without raising an error. Option C, "notes: str | None", only indicates that None is an acceptable value if the field is provided, but without a default, the field is still considered required if entirely absent from the input data.
Question 11 of 30
What is a critical prerequisite for FastAPI to correctly parse incoming `Form` data?
Show the answer
Answer: d · Installing the python-multipart library.
The card explicitly states that 'you must pip install python-multipart' and that forgetting it 'will break form parsing.' While Pydantic models are central to FastAPI, for Form data, you declare individual fields with `Form()`, not a top-level Pydantic model for the body. The client must send `application/x-www-form-urlencoded`, not `application/json`.
Read the full bite: FastAPI: Handling Form Data, Not Just JSON
Question 12 of 30
Which scenario is least suitable for declaring individual HTTP headers using Header() in a FastAPI path operation?
Show the answer
Answer: a · Handling a full OAuth2 authentication and authorization flow.
The card explicitly advises against using Header() for complex authentication schemes like OAuth2, as FastAPI provides dedicated security utilities for such cases. It is well-suited for simpler tasks like reading User-Agent, API keys, or tracing IDs.
Question 13 of 30
What is the primary function of declaring a parameter with Cookie() in a FastAPI path operation?
Show the answer
Answer: b · To retrieve the value of a specific cookie sent by the client in the request.
The card states that `Cookie()` is used to signal to FastAPI that a parameter's value should come from a request cookie, allowing it to extract the value. Option D is incorrect because the card explicitly warns against using `Cookie()` to send cookies back to the client.
Question 14 of 30
What is a primary security risk when using FastAPI's HTMLResponse to display user-provided input?
Show the answer
Answer: a · It does not automatically escape user-provided data, opening the door to Cross-Site Scripting (XSS) attacks.
The card explicitly states that HTMLResponse 'does not automatically escape data' and constructing HTML with user-provided input 'open[s] your application to Cross-Site Scripting (XSS) attacks.' Option C is incorrect because the problem is precisely the *lack* of automatic sanitization.
Read the full bite: FastAPI: Returning HTML with HTMLResponse
Question 15 of 30
For what primary purpose should a developer use FastAPI's Depends feature in an API endpoint?
Show the answer
Answer: c · To manage shared setup tasks, such as database connections or user authentication.
The card states that Depends solves "repeated setup and teardown code" and is used for "managing database connections" and "handling security." It delegates prerequisite tasks, not the main business logic, response formatting, or error handling.
Read the full bite: FastAPI's Depends: Let the Framework Handle Setup
Question 16 of 30
What is the primary benefit of using a class as a dependency in FastAPI?
Show the answer
Answer: b · To group logically related request parameters for reuse across multiple endpoints.
The card emphasizes that class dependencies are used to bundle related request parameters, like for pagination, to avoid duplication and improve code structure across multiple endpoints. Options A and C describe the use of Pydantic models for data validation and serialization, which is a different FastAPI feature, while option A refers to authentication, another distinct use case for dependencies.
Question 17 of 30
What is the primary benefit of FastAPI's dependency caching mechanism?
Show the answer
Answer: c · It guarantees a dependency function runs only once per API request, improving performance.
FastAPI's dependency caching ensures that a dependency function is called only once per API request, reusing the result for all subsequent needs within that same request, which significantly improves efficiency. It is not designed for caching across different requests or at application startup.
Read the full bite: FastAPI's Dependency Caching: One Request, One Call
Question 18 of 30
What is the main advantage of using FastAPI's APIRouter for structuring an application?
Show the answer
Answer: d · It allows for better organization and maintainability of routes in larger projects.
APIRouter's core benefit is to modularize and organize routes, making large applications more manageable and maintainable by separating concerns. For small applications, the card states it's "unnecessary overhead," not a code reducer.
Read the full bite: FastAPI's APIRouter: Grouping Routes into Modules
Question 19 of 30
When using app.include_router, what is the primary purpose of the prefix argument?
Show the answer
Answer: a · To define a base URL path for all endpoints within that router.
The 'prefix' argument is crucial for defining the base URL for all endpoints within a router and preventing path conflicts. Option D describes the function of the 'tags' argument, which is used for documentation categorization.
Read the full bite: FastAPI: Splitting Your App with `include_router`
Question 20 of 30
When an async def function executes an await on an I/O operation, what is the immediate action taken by the asyncio event loop?
Show the answer
Answer: b · It pauses the current task and begins executing another task that is ready.
When a task awaits an I/O operation, it yields control to the event loop, which then pauses that task and switches to another ready task, preventing the single thread from blocking. The event loop's purpose is specifically to avoid blocking the application, making option D incorrect.
Read the full bite: The asyncio Event Loop: One Thread, Many Tasks
Question 21 of 30
What is the main advantage of using SQLAlchemy's Engine and Session pattern in a concurrent web application?
Show the answer
Answer: c · It provides a robust way to manage database connections and ensure isolated transactions for each request.
The Engine and Session pattern is designed to efficiently manage a pool of database connections and ensure that each concurrent request operates within its own isolated transaction scope, preventing data conflicts. Other options describe general ORM features, multi-database connectivity, or schema management, which are not the primary benefits of this specific pattern.
Read the full bite: SQLAlchemy Engine vs. Session: The Switchboard and the Call
Question 22 of 30
According to the card, what is the primary role of SQLAlchemy's Declarative mapping in a "code-first" development approach?
Show the answer
Answer: b · To define database table structures directly within Python classes.
The card states Declarative mapping is ideal for "code-first" development where Python code is the source of truth for the database schema, allowing developers to define tables as Python classes. Option D describes reflection, which is the opposite direction (database to Python classes), not the primary role of Declarative mapping for new applications.
Read the full bite: SQLAlchemy Declarative: Python Classes as Database Tables
Question 23 of 30
What is the primary reason to use Passlib's .verify() method for password validation instead of direct string comparison?
Show the answer
Answer: b · It prevents timing attacks that could reveal information about the password.
The .verify() method is designed to prevent timing attacks, which could otherwise allow an attacker to deduce password characters based on the time taken for comparison. Hashing algorithms used by Passlib are intentionally slow to deter brute-force attacks, so speed is not the primary benefit of .verify().
Question 24 of 30
A JWT is signed with a shared secret but not encrypted. Who can read its JSON payload?
Show the answer
Answer: a · Anyone who intercepts the token, though only secret holders can verify its origin
The card describes a JWT as a readable postcard by default; signing proves authenticity but does not provide confidentiality. Option B is tempting because learners often assume the shared secret that verifies the signature also decrypts the payload, but encryption is a separate, optional step.
Question 25 of 30
Which scenario best exemplifies an appropriate use case for the OAuth2 Password Flow?
Show the answer
Answer: b · A company's proprietary mobile app authenticating users against its own API.
The card states the Password Flow is specifically for "trusted first-party apps," such as "a company's official first-party mobile app" communicating with its own backend. Option D describes a third-party scenario, which is explicitly warned against due to security risks.
Read the full bite: OAuth2 Password Flow: Trading Credentials for a Token
Question 26 of 30
When is it most appropriate to implement FastAPI's CORSMiddleware in a web application?
Show the answer
Answer: c · When a browser-based JavaScript application needs to fetch data from an API hosted on a different origin.
CORSMiddleware is specifically designed for scenarios where a browser-based frontend attempts to access an API from a different origin, as browsers enforce the Same-Origin Policy. It is not needed for non-browser clients or when the frontend and backend share the exact same origin.
Read the full bite: CORSMiddleware: Unblocking Your Frontend from Your Backend
Question 27 of 30
Which scenario is the most appropriate use case for a FastAPI background task?
Show the answer
Answer: a · Sending a welcome email to a new user after their account has been successfully created.
Background tasks are ideal for operations like sending emails, where the client doesn't need to wait for completion to receive a response, as highlighted in the card's canonical example. Critical, must-not-fail operations or tasks requiring immediate results for the client are explicitly stated as unsuitable for background tasks due to their fire-and-forget nature and lack of durability.
Read the full bite: FastAPI Background Tasks: Don't Make the Client Wait
Question 28 of 30
What is the fundamental mechanism by which FastAPI's TestClient processes API requests?
Show the answer
Answer: d · It directly passes a simulated request object to the FastAPI application's internal routing and dependency resolution.
TestClient works by constructing a request object and passing it directly into the FastAPI application's internal machinery, bypassing the network stack entirely. It explicitly states it 'doesn't send a network request' and operates 'without a live server', making options involving servers or network requests incorrect.
Read the full bite: FastAPI's TestClient: Test Your API Without a Live Server
Question 29 of 30
What is the primary mechanism by which a pytest test function receives the setup data provided by a fixture?
Show the answer
Answer: c · Pytest automatically executes the fixture function and injects its return value as an argument into the test function.
The card explains that 'Pytest acts as the injector, finding and running the corresponding fixture functions and passing their return values into the test.' This describes automatic execution and injection as arguments. Option B is incorrect because the card explicitly states, 'You never call the fixture function directly.'
Question 30 of 30
What is the primary purpose of configuring API metadata in a FastAPI application?
Show the answer
Answer: a · To enhance the clarity and discoverability of the API through its documentation.
The card explicitly states that metadata "enriches its auto-generated documentation" and makes the API "professional and discoverable." It does not handle logic generation, performance, or security.
Read the full bite: FastAPI: Configure API Metadata for Better Docs
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.