Skip to content
tezvyn:

Top 30 Intermediate Python & FastAPI Concepts Quiz

30 intermediate multiple-choice Python & FastAPI concept questions, the mechanics underneath the basics: how the pieces relate and where the usual mental model stops holding. They come from 30 bites in the Python & FastAPI library, the middle 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.

  1. Question 1 of 30

    When a decorator is applied to a function, what is the immediate effect on that function's definition?

    Show the answer

    Answer: d · It replaces the original function in its scope with a new, wrapped function.

    The card states that the decorator returns a wrapper function, which 'replaces the original my_func in the surrounding scope.' This means the original function's name now refers to the new, wrapped function. Option A is incorrect because decorators add behavior without altering the original function's source code.

    Read the full bite: Python Decorators: Functions that Wrap Functions

  2. Question 2 of 30

    What is the primary benefit of using `yield` in a Python function?

    Show the answer

    Answer: a · It enables the function to pause and resume execution, producing values on-demand to conserve memory.

    The card states generators process data lazily, yielding one item at a time to conserve memory by pausing and resuming execution. Option D is incorrect because generators are one-time-use iterators.

    Read the full bite: Python's `yield`: Functions That Pause and Resume

  3. Question 3 of 30

    What is the primary advantage of using a `with` statement in Python for resource management?

    Show the answer

    Answer: d · It ensures that acquired resources are reliably released, regardless of execution flow or errors.

    The `with` statement's core benefit is guaranteeing that resources like file handles or network connections are properly closed or released, even if exceptions interrupt the program flow. While it interacts with errors, it doesn't automatically handle all exceptions; rather, it ensures cleanup *despite* them.

    Read the full bite: The `with` Statement: Python's Automatic Cleanup Crew

  4. Question 4 of 30

    What is the immediate result of calling a function defined with async def, like my_coro(), without awaiting it?

    Show the answer

    Answer: c · A coroutine object is returned, which must be explicitly run by an event loop.

    Calling an async def function directly only creates a coroutine object; it does not execute the function's code. This object must then be awaited or scheduled with an event loop to run. Option B describes synchronous function behavior, and Option A incorrectly implies immediate background execution without the necessary explicit step.

    Read the full bite: Python Coroutines: Functions You Can Pause and Resume

  5. Question 5 of 30

    For which scenario would Python's async/await typically NOT provide a performance benefit?

    Show the answer

    Answer: b · Processing a large dataset with intensive numerical calculations.

    Async/await is designed for I/O-bound tasks where the program spends time waiting, allowing other tasks to run during these waits. CPU-bound tasks, like intensive numerical calculations, will block the single event loop, preventing any other tasks from progressing and thus negating the benefits of concurrency.

    Read the full bite: Python's async/await: Concurrent, Not Parallel

  6. Question 6 of 30

    When developing a FastAPI application, for which purpose is a Pydantic BaseModel most effectively utilized?

    Show the answer

    Answer: d · To define the expected structure and types of data within a POST or PUT request's body.

    The card states that Pydantic models are used for 'the request body of any POST, PUT, or PATCH endpoint where the client sends structured data.' Options A, B, and D describe scenarios where Pydantic models are explicitly advised not to be used for the primary request body model, as those are handled by other FastAPI mechanisms like path parameters, query parameters, or Form().

    Read the full bite: FastAPI: Pydantic for Robust Request Bodies

  7. Question 7 of 30

    When an internal object has fields not defined in a FastAPI response_model, what is the primary action FastAPI takes?

    Show the answer

    Answer: b · It automatically filters out those extra fields before sending the response.

    The `response_model` acts as a stencil, automatically filtering out any fields from the internal object that are not defined in the model before sending the response. It does not raise an error for extra fields, nor does it require manual exclusion for this purpose.

    Read the full bite: FastAPI Response Models: Shape Your API's Output

  8. Question 8 of 30

    What is the fundamental principle behind FastAPI's ability to provide accurate and up-to-date API documentation?

    Show the answer

    Answer: d · It automatically generates documentation by introspecting the application's Python code and type hints.

    The card states, "Think of your code as the single source of truth for your documentation. FastAPI reads your Python functions, their parameters, their type hints..." This means the documentation is generated directly from the code, ensuring it's always current. Other options describe alternative or supplementary methods, but not FastAPI's core mechanism for documentation generation.

    Read the full bite: FastAPI: Automatic Interactive API Docs

  9. Question 9 of 30

    When a parameter validated by FastAPI's Query or Path objects fails its defined constraints, what is the immediate outcome?

    Show the answer

    Answer: b · FastAPI stops request processing and returns a 422 Unprocessable Entity error to the client.

    The card states that if validation fails, FastAPI immediately stops processing and returns a 422 Unprocessable Entity error. This prevents invalid data from reaching your function and provides clear feedback to the client, unlike the other options which describe different error handling or value manipulation.

    Read the full bite: FastAPI: Validate Parameters with Query and Path

  10. Question 10 of 30

    Which is the correct way to set a 201 Created status for a new resource created via a FastAPI POST endpoint?

    Show the answer

    Answer: c · @app.post("/items/", status_code=201)

    The card explicitly states that the success status code should be set in the path operation decorator, as shown in option C, because it's part of the endpoint's contract. Option A is identified as a 'common footgun' for placing it in the function signature, and option D incorrectly uses HTTPException for a success code.

    Read the full bite: FastAPI: Set a Response's HTTP Status Code

  11. Question 11 of 30

    For which scenario are nested Pydantic models most appropriate?

    Show the answer

    Answer: c · To accurately represent and validate hierarchical data, such as JSON with nested objects.

    Nested Pydantic models are specifically designed to handle and validate complex, hierarchical data structures like JSON objects containing other objects. Using them for flat data is explicitly advised against, as it adds unnecessary complexity.

    Read the full bite: Nested Pydantic Models: Composing Complex Data

  12. Question 12 of 30

    When would a developer choose to disable Pydantic's default data coercion for a field?

    Show the answer

    Answer: c · To enforce that the input data's type precisely matches the annotated Python type, preventing automatic conversions.

    The card states that coercion should be disabled "when you need to enforce strict data contracts" and the input data type must match the annotated type exactly. Option B is incorrect because coercion actually enables more flexible handling of diverse input formats by converting them to the target type, so disabling it would reduce flexibility.

    Read the full bite: Pydantic's Data Coercion: From Raw Data to Python Types

  13. Question 13 of 30

    For what primary purpose should model_config be used in Pydantic V2 models?

    Show the answer

    Answer: a · To apply model-wide settings like immutability or global string length constraints.

    model_config is designed for applying consistent, model-wide behaviors such as making a model immutable (frozen=True) or setting global string length limits. Option C describes the use case for Pydantic's Field function, not model_config.

    Read the full bite: Pydantic: Configuring Models with `model_config`

  14. Question 14 of 30

    When handling large file uploads in FastAPI, what is the key benefit of using the UploadFile class compared to reading the entire file into memory?

    Show the answer

    Answer: d · It provides a temporary pointer to the file, allowing streaming to prevent excessive memory usage.

    UploadFile's primary benefit is its streamable nature, which prevents the entire file from being loaded into server memory, thus avoiding memory exhaustion for large uploads. It does not automatically handle compression, persistent storage, or client-side validation.

    Read the full bite: FastAPI: Use UploadFile for Efficient File Uploads

  15. Question 15 of 30

    What is the primary benefit of injecting a Response object into a FastAPI endpoint function?

    Show the answer

    Answer: d · It enables setting cookies or headers while still returning standard data types like dictionaries or Pydantic models.

    Injecting a Response object allows you to modify response metadata like cookies or headers while still returning standard data types for the response body. You do not return the injected Response object itself, nor does it bypass FastAPI's serialization of your returned data; rather, FastAPI merges the metadata from the injected object with the body generated from your return value.

    Read the full bite: FastAPI: Set Cookies Without Returning a Response Object

  16. Question 16 of 30

    When is it inappropriate to use a FastAPI global dependency?

    Show the answer

    Answer: c · When the logic is only relevant for a subset of your API's endpoints, such as an admin section.

    The card explicitly states that global dependencies should be avoided for logic that isn't universal, such as logic only relevant to a subset of endpoints. Raising an HTTPException is a normal and intended way for a global dependency to halt a request, not a reason to avoid using it.

    Read the full bite: FastAPI Global Dependencies: DRY Your API Logic

  17. Question 17 of 30

    What is a primary advantage of using Pydantic BaseSettings for application configuration?

    Show the answer

    Answer: b · It provides a structured, type-safe way to load and validate settings from multiple prioritized sources.

    BaseSettings excels at providing a typed contract for configuration, automatically loading and validating values from sources like environment variables and .env files with a defined priority. Option D is incorrect because BaseSettings loads configuration at initialization time and is not designed for dynamic runtime changes.

    Read the full bite: Pydantic BaseSettings: Typed, Layered Configuration

  18. Question 18 of 30

    Which scenario best illustrates the appropriate use of Pydantic Settings in a FastAPI application?

    Show the answer

    Answer: c · Storing a database connection string that differs between development, staging, and production environments.

    Pydantic Settings is specifically designed to manage configuration values that vary across different deployment environments, such as database URLs or API keys, ensuring they are loaded securely and validated. While Pydantic is used for request body validation, Pydantic Settings focuses on environment-dependent application settings, not static constants or request schemas.

    Read the full bite: FastAPI: Managing Environment-Specific Settings

  19. Question 19 of 30

    Which statement accurately describes a key limitation or misuse of asyncio synchronization primitives?

    Show the answer

    Answer: b · They are not suitable for protecting shared resources accessed by traditional OS threads.

    The card explicitly states that asyncio primitives are not thread-safe and should not be used for synchronizing traditional OS threads, as they will fail unpredictably. Option A is incorrect because the card recommends using 'async with' for safe and automatic management of these primitives.

    Read the full bite: Coordinating Asyncio Tasks with Locks and Events

  20. Question 20 of 30

    Which scenario is NOT an appropriate use case for asyncio.Queue?

    Show the answer

    Answer: a · Exchanging data between an asyncio coroutine and a separate, non-asyncio thread.

    The card explicitly states that asyncio.Queue is not thread-safe and should not be used for communication between different threads or processes. Options A, B, and D all describe valid and recommended use cases for asyncio.Queue, such as distributing work, handling producer-consumer patterns, and throttling.

    Read the full bite: asyncio Queues: Coordinating Asynchronous Tasks

  21. Question 21 of 30

    What is the primary advantage of using asyncio.create_subprocess_exec in an asyncio application?

    Show the answer

    Answer: b · It ensures the application's event loop remains responsive while external commands execute.

    The card explicitly states that asynchronous subprocesses allow the event loop to remain responsive by integrating external process management. While create_subprocess_exec is safer against shell injection because it avoids invoking a shell, its primary advantage in an asyncio context is non-blocking execution, not input sanitization.

    Read the full bite: Python's Asyncio Subprocesses: Non-Blocking Shell Commands

  22. Question 22 of 30

    What is the primary reason to use SQLAlchemy 2.0's async API in an application built with an asyncio framework?

    Show the answer

    Answer: c · To prevent database I/O operations from blocking the application's single event loop.

    The card states that a synchronous database call in an asyncio framework would "block the entire application," making the async API essential for a "non-blocking way to interact with the database." While it improves concurrency, it doesn't inherently make individual queries faster.

    Read the full bite: SQLAlchemy 2.0: Async Without Blocking the Event Loop

  23. Question 23 of 30

    After using alembic revision --autogenerate to create a new migration, what crucial step should a developer take before applying it?

    Show the answer

    Answer: b · Review the generated Python migration script for accuracy and completeness.

    The card explicitly warns about the 'footgun' of autogeneration, stating that one 'must open the generated file and verify' its correctness. Option C is a common mistake that ignores this critical review step, potentially leading to incorrect schema changes.

    Read the full bite: Alembic: Version Control for Your Database Schema

  24. Question 24 of 30

    When is Motor most advantageous for a Python application interacting with MongoDB?

    Show the answer

    Answer: a · When building an I/O-bound application using an asynchronous framework like FastAPI.

    Motor is designed for I/O-bound applications within asynchronous Python frameworks to prevent database operations from blocking the event loop, ensuring responsiveness. While it manages the impact of network latency by allowing other tasks to run, it does not reduce the actual latency itself.

    Read the full bite: Motor: Don't Block Your Python App on MongoDB

  25. Question 25 of 30

    What is the primary advantage of using Beanie for database interactions in an async Python application?

    Show the answer

    Answer: a · It provides type-safe, object-oriented data management by mapping Pydantic models to MongoDB documents.

    Beanie's core purpose is to map Pydantic models to MongoDB documents, offering type-safe and object-oriented interaction. Option B is incorrect because the card states Beanie is not ideal for highly complex, performance-critical operations like intricate aggregation pipelines.

    Read the full bite: Beanie: Python Objects as MongoDB Documents

  26. Question 26 of 30

    What is the primary security concern when using HTTP Basic Auth over an unencrypted HTTP connection?

    Show the answer

    Answer: b · The Base64 encoded credentials can be trivially decoded, exposing them to interception.

    The card states that Base64 encoding is 'trivial to reverse,' meaning anyone intercepting the traffic can easily decode the credentials. It clarifies that Base64 is an encoding, not an encryption, making option A incorrect.

    Read the full bite: HTTP Basic Auth: Simple but Insecure Access Control

  27. Question 27 of 30

    Which scenario is the most appropriate use case for API key authentication?

    Show the answer

    Answer: c · Allowing a third-party monitoring service to access your API's health endpoint.

    API keys are ideal for server-to-server communication or trusted, non-interactive clients, as exemplified by a monitoring service. They are not suitable for authenticating end-users or managing granular, per-user permissions, which are better handled by protocols like OAuth2.

    Read the full bite: API Keys: Simple Server-to-Server Authentication

  28. Question 28 of 30

    What is the primary reason to implement OAuth2 scopes in a FastAPI application?

    Show the answer

    Answer: c · To manage different levels of access for various users or client applications within the API.

    OAuth2 scopes are used for fine-grained authorization, allowing an API to grant different levels of access based on specific permissions attached to a user's token. While scopes are part of securing routes, their core purpose is to differentiate access levels, not just to confirm user identity or ensure basic authentication for all users.

    Read the full bite: FastAPI: Fine-Grained Permissions with OAuth2 Scopes

  29. Question 29 of 30

    For an API requiring distinct read and write access levels for different user types, which FastAPI security pattern is most suitable?

    Show the answer

    Answer: a · Employing Security(get_current_user, scopes=["required_scope"]) to validate token permissions.

    The card explicitly states that OAuth2 scopes with FastAPI's Security dependency are ideal for granting different users varying levels of access, like read and write, by checking specific permissions in their token. Manually checking roles (option D) is a less automated approach that scopes aim to improve upon in token-based systems.

    Read the full bite: FastAPI RBAC: Using OAuth2 Scopes for Permissions

  30. Question 30 of 30

    What is the primary purpose of a refresh token in an authentication system?

    Show the answer

    Answer: d · To allow users to maintain a persistent logged-in session without repeatedly authenticating.

    The card states refresh tokens are used to "keep you logged in for weeks" and "maintain a user's session beyond a few minutes without forcing them to log in again" by obtaining new access tokens. Option A describes an access token, not a refresh token.

    Read the full bite: Refresh Tokens: Persistent Sessions Without Re-Authentication

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