1. Home
  2. Explore
  3. Computer Science
  4. FastAPI Crash Course

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

FastAPI Crash Course

  • 25Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: FastAPI Fundamentals

Which Python framework does FastAPI utilize as its foundation for handling basic web functionalities?

25 questions

  1. 1

    Which Python framework does FastAPI utilize as its foundation for handling basic web functionalities?

    1. A

      Flask, known for its minimalism and direct ASGI integration support.

    2. B

      Pyramid, offering a highly flexible and extensible framework architecture.

    3. C

      Django, providing extensive ORM capabilities and template rendering.

    4. D

      Starlette, which is an ASGI toolkit responsible for core web components.

    Correct answer
    D

    Starlette, which is an ASGI toolkit responsible for core web components.

    Explanation

    FastAPI is built on top of the Starlette framework, which is an ASGI framework. Starlette handles the basic web parts such as routing, middleware, and request/response processing.

  2. 2

    What is the primary advantage of ASGI over WSGI in the context of web application development?

    1. A

      WSGI is specifically designed for asynchronous operations, while ASGI is synchronous.

    2. B

      ASGI enables concurrent handling of multiple requests, unlike WSGI's synchronous model.

    3. C

      WSGI offers better integration with modern Python frameworks compared to ASGI.

    4. D

      ASGI supports synchronous request handling exclusively for better stability.

    Correct answer
    B

    ASGI enables concurrent handling of multiple requests, unlike WSGI's synchronous model.

    Explanation

    ASGI (Asynchronous Server Gateway Interface) is the successor to WSGI (Web Server Gateway Interface). WSGI is synchronous and handles requests one at a time, whereas ASGI is asynchronous and can handle multiple requests concurrently.

  3. 3

    Which tool does FastAPI use for automatic data validation and serialization?

    1. A

      Cerberus, a lightweight data validation library with schema definition.

    2. B

      Marshmallow, providing schema-based object serialization and deserialization.

    3. C

      Pydantic, leveraging Python type hints for data validation.

    4. D

      SQLAlchemy, primarily used for object-relational mapping in databases.

    Correct answer
    C

    Pydantic, leveraging Python type hints for data validation.

    Explanation

    FastAPI uses Pydantic for automatic data validation and serialization. It validates the API using Python type hints, automatically stripping out unexpected fields in requests.

  4. 4

    What interactive documentation tools are bundled with the standard FastAPI package?

    1. A

      Insomnia and cURL, for making HTTP requests to the API.

    2. B

      ReDoc and Sphinx, for generating static API documentation.

    3. C

      Swagger UI and Postman, to test API endpoints directly.

    4. D

      Swagger UI and ReDoc, providing interactive API documentation.

    Correct answer
    D

    Swagger UI and ReDoc, providing interactive API documentation.

    Explanation

    FastAPI provides automatic interactive documentation bundled with the standard package, specifically Swagger UI and ReDoc. Swagger UI allows you to test HTTP requests directly from the documentation.

  5. 5

    How does FastAPI manage components and database connections through its dependency injection system?

    1. A

      Dependencies are defined as global variables that FastAPI automatically accesses.

    2. B

      It allows defining dependencies as functions, handling their lifecycle automatically.

    3. C

      Each component must manage its own lifecycle independently without framework support.

    4. D

      It requires explicit manual import and instantiation of all components.

    Correct answer
    B

    It allows defining dependencies as functions, handling their lifecycle automatically.

    Explanation

    FastAPI includes a dependency injection system that simplifies the management of components, database connections, and authentication. It allows defining dependencies as functions, and FastAPI handles their lifecycle.

  6. 6

    What is the recommended tool for deploying a FastAPI application for users who prefer to avoid complex DevOps tasks?

    1. A

      AWS EC2, requiring extensive knowledge of server management and configuration.

    2. B

      Heroku, which has its own specific CLI for application deployment.

    3. C

      Render.com, offering automated deployment from GitHub repositories.

    4. D

      DigitalOcean Droplets, which demand manual setup of infrastructure.

    Correct answer
    C

    Render.com, offering automated deployment from GitHub repositories.

    Explanation

    Render.com is suggested as a deployment platform for FastAPI applications, especially for those who are not well-versed in DevOps, Docker, or other cloud platforms. It automates the deployment process from a GitHub repository.

  7. 7

    What is the purpose of creating a virtual environment in a Python project?

    1. A

      To install dependencies globally across all Python projects on the machine.

    2. B

      To allow the direct execution of Python scripts without needing an interpreter.

    3. C

      To bypass the need for a package manager like pip for dependency installation.

    4. D

      To ensure all project dependencies are isolated and localized to the project folder.

    Correct answer
    D

    To ensure all project dependencies are isolated and localized to the project folder.

    Explanation

    A virtual environment ensures that when dependencies are installed, they are localized to the specific project folder rather than being installed globally on the machine. This prevents conflicts between different projects' dependencies.

  8. 8

    How do you activate a virtual environment on a Mac using the command line?

    1. A

      source ./.venv/bin/activate

    2. B

      python ./.venv/activate

    3. C

      run ./.venv/activate

    4. D

      call ./.venv/scripts/activate

    Correct answer
    A

    source ./.venv/bin/activate

    Explanation

    To activate a virtual environment on a Mac, you use the command source ./.venv/bin/activate. This command executes the activation script within the virtual environment's bin directory.

  9. 9

    Which command is used to install FastAPI with its standard dependencies in a virtual environment?

    1. A

      pip install fastapi[standard]

    2. B

      pip install fastapi-standard

    3. C

      pip install fastapi --with-defaults

    4. D

      pip install fastapi[all]

    Correct answer
    A

    pip install fastapi[standard]

    Explanation

    To install FastAPI with its standard dependencies, including Pydantic and Swagger, the command pip install "fastapi[standard]" is used. This installs the core FastAPI along with commonly needed extras.

  10. 10

    What is the primary function of the main.py file in a FastAPI application?

    1. A

      It stores all the static files like images and CSS stylesheets.

    2. B

      It serves as the entry point for the application, initializing FastAPI.

    3. C

      It holds helper functions and utility classes for the entire project.

    4. D

      It contains all the database schema definitions and migration scripts.

    Correct answer
    B

    It serves as the entry point for the application, initializing FastAPI.

    Explanation

    The main.py file serves as the entry point for the FastAPI application, similar to server.js or app.js in Node.js/Express. It's where the FastAPI instance is initialized and routers are included.

  11. 11

    How are HTTP GET routes defined in FastAPI?

    1. A

      Using the @app.get('/path') decorator above an asynchronous function.

    2. B

      By calling app.route('/path', methods=['GET']) directly.

    3. C

      Through a configuration file mapping URLs to specific handler functions.

    4. D

      By defining a function named get_path() that FastAPI auto-detects.

    Correct answer
    A

    Using the @app.get('/path') decorator above an asynchronous function.

    Explanation

    HTTP GET routes in FastAPI are defined using the @app.get('/path') decorator placed directly above a Python function. This decorator registers the function as the handler for GET requests to the specified path.

  12. 12

    What is the purpose of accessing /docs endpoint in a running FastAPI application?

    1. A

      To download the full source code of the FastAPI application.

    2. B

      To access the interactive Swagger UI documentation for testing routes.

    3. C

      To view the application's performance metrics and server logs.

    4. D

      To configure database connections and environment variables.

    Correct answer
    B

    To access the interactive Swagger UI documentation for testing routes.

    Explanation

    Accessing the /docs endpoint in a running FastAPI application displays the interactive Swagger UI documentation. This allows users to view all defined routes, their parameters, and to test requests directly.

  13. 13

    How does FastAPI allow extracting dynamic segments from a URL path, such as an item ID?

    1. A

      By defining path parameters in curly braces, e.g., /items/{item_id}.

    2. B

      By using query parameters like /items?id=123 in the URL.

    3. C

      Through custom HTTP headers containing the dynamic value.

    4. D

      By including the dynamic segment in the request body for POST requests.

    Correct answer
    A

    By defining path parameters in curly braces, e.g., /items/{item_id}.

    Explanation

    FastAPI allows extracting dynamic segments from a URL path, known as path parameters, by enclosing them in curly braces within the route decorator (e.g., /items/{item_id}). These values are then passed as arguments to the route function.

  14. 14

    When creating a POST request, what happens if the request body contains fields not defined in the Pydantic schema?

    1. A

      FastAPI raises a validation error and rejects the entire request.

    2. B

      The undefined fields are automatically stripped out and ignored by FastAPI.

    3. C

      The request is processed, but the extra fields are marked as warnings in logs.

    4. D

      FastAPI attempts to infer types for the extra fields and includes them.

    Correct answer
    B

    The undefined fields are automatically stripped out and ignored by FastAPI.

    Explanation

    When a request body contains fields not defined in the corresponding Pydantic schema, FastAPI automatically strips out and ignores these extra fields. It only processes data that conforms to the defined schema.

  15. 15

    Why is it recommended to use APIRouter for organizing routes in larger FastAPI applications?

    1. A

      It prevents the creation of custom middleware for specific route groups.

    2. B

      It automatically generates database migrations for all defined endpoints.

    3. C

      It allows all routes to be defined in a single main.py file without clutter.

    4. D

      It enables grouping related routes into separate files and adding prefixes or tags.

    Correct answer
    D

    It enables grouping related routes into separate files and adding prefixes or tags.

    Explanation

    Using APIRouter is recommended for organizing routes in larger FastAPI applications because it allows grouping related routes into separate files (e.g., issues.py). It also enables adding prefixes and tags, which helps with documentation and organization, similar to express.Router in Node.js.

  16. 16

    What is the primary function of the requirements.txt file in a Python project for deployment?

    1. A

      It defines the database schema and initial data for the application.

    2. B

      It serves as the main entry point for the application on the server.

    3. C

      It lists all the required Python packages and their versions for the project.

    4. D

      It contains environment variables specific to the production server.

    Correct answer
    C

    It lists all the required Python packages and their versions for the project.

    Explanation

    The requirements.txt file lists all the dependencies (Python packages and their specific versions) required for the project. During deployment, a command like pip install -r requirements.txt is used to install these dependencies, ensuring the correct environment.

  17. 17

    What is the primary purpose of defining IssueStatus and IssuePriority as Enum classes in FastAPI schemas?

    1. A

      To convert these fields into numerical representations for database storage.

    2. B

      To restrict status and priority to a predefined set of specific, valid values.

    3. C

      To allow any string value for status and priority, providing maximum flexibility.

    4. D

      To enable automatic encryption of these fields for security purposes.

    Correct answer
    B

    To restrict status and priority to a predefined set of specific, valid values.

    Explanation

    Defining IssueStatus and IssuePriority as Enum classes restricts their possible values to a predefined set (e.g., 'open', 'in progress', 'closed' for status). This enforces strict data validation and consistency.

  18. 18

    When creating an IssueCreate schema for a POST request, why is the status field typically omitted?

    1. A

      The status is usually hardcoded to 'open' when an issue is first created.

    2. B

      Status is a read-only field and cannot be included in creation requests.

    3. C

      The client is not allowed to set the initial status of an issue.

    4. D

      The status field is automatically inferred from the issue's priority.

    Correct answer
    A

    The status is usually hardcoded to 'open' when an issue is first created.

    Explanation

    When creating an IssueCreate schema for a POST request, the status field is typically omitted because the status is hardcoded as 'open' when an issue is first created. The client doesn't provide this initial value.

  19. 19

    Why are fields like title and description made Optional in an IssueUpdate schema?

    1. A

      To prevent any modification of these fields once an issue is created.

    2. B

      To enforce that all fields must be present in every update request.

    3. C

      To allow the system to automatically generate these fields if they are missing.

    4. D

      To enable partial updates where only specific fields need to be provided.

    Correct answer
    D

    To enable partial updates where only specific fields need to be provided.

    Explanation

    Fields like title and description are made Optional in an IssueUpdate schema to facilitate partial updates. When updating an issue, a client might only want to change one or two fields, and making them optional ensures that other fields are not required in the request body.

  20. 20

    What HTTP status code is typically returned for a successful POST request that creates a new resource?

    1. A

      201 Created, specifically for successful resource creation.

    2. B

      200 OK, indicating a standard successful response.

    3. C

      400 Bad Request, signifying a client-side error in the request.

    4. D

      204 No Content, used when the server fulfills the request but does not return content.

    Correct answer
    A

    201 Created, specifically for successful resource creation.

    Explanation

    For a successful POST request that creates a new resource, the HTTP status code 201 Created is typically returned. This explicitly indicates that a new resource has been successfully created on the server.

  21. 21

    What is the purpose of middleware in a backend framework like FastAPI?

    1. A

      To define the data models for database interaction exclusively.

    2. B

      To generate client-side JavaScript for interacting with the API.

    3. C

      To handle asynchronous tasks in the background without affecting requests.

    4. D

      To execute code before or after each request, accessing request and response objects.

    Correct answer
    D

    To execute code before or after each request, accessing request and response objects.

    Explanation

    Middleware in a backend framework is a function or code that runs before or after each request. It has access to the request and response objects, allowing for tasks like logging, authentication, or modifying headers.

  22. 22

    How can you add a custom header, such as X-Process-Time, to all responses in FastAPI?

    1. A

      By modifying the response object directly within each individual route function.

    2. B

      By using a middleware that intercepts responses and adds the header.

    3. C

      Through a global configuration setting in the settings.py file.

    4. D

      By defining a ResponseHeader class in the Pydantic schemas.

    Correct answer
    B

    By using a middleware that intercepts responses and adds the header.

    Explanation

    A custom header, like X-Process-Time, can be added to all responses in FastAPI by implementing a middleware. The middleware function can modify the response object's headers before the response is sent back to the client.

  23. 23

    What is CORS and why is it important for a public API?

    1. A

      CORS defines how a server and client interact over different network protocols.

    2. B

      CORS is a caching mechanism that improves API response times for clients.

    3. C

      CORS is a security feature that encrypts all API traffic for privacy.

    4. D

      CORS specifies how resources from different origins (domains) can be accessed, preventing browser security errors.

    Correct answer
    D

    CORS specifies how resources from different origins (domains) can be accessed, preventing browser security errors.

    Explanation

    CORS (Cross-Origin Resource Sharing) is a security mechanism that governs how web browsers permit a web page at one domain to make requests to a resource at another domain. For a public API, enabling CORS appropriately allows different front-end applications (from different domains) to access it without being blocked by browser security policies.

  24. 24

    How do you allow all domains to access your FastAPI application when implementing CORS middleware?

    1. A

      By omitting the CORS_Middleware entirely from the application.

    2. B

      By setting allow_origins to a specific whitelist of trusted domains.

    3. C

      By configuring the web server (e.g., Nginx) to handle CORS, not FastAPI.

    4. D

      By setting allow_origins=["*"] in the CORS_Middleware configuration.

    Correct answer
    D

    By setting allow_origins=["*"] in the CORS_Middleware configuration.

    Explanation

    To allow all domains to access a FastAPI application when implementing CORS middleware, you set allow_origins=["*"]. This wildcard value indicates that requests from any origin are permitted, making the API publicly accessible from any domain.

  25. 25

    What command is used to generate the requirements.txt file, listing project dependencies?

    1. A

      python generate-deps.py

    2. B

      pip freeze > requirements.txt

    3. C

      pip list --output requirements.txt

    4. D

      python install --save-dev requirements.txt

    Correct answer
    B

    pip freeze > requirements.txt

    Explanation

    The command pip freeze > requirements.txt is used to generate the requirements.txt file. pip freeze outputs a list of all installed packages in the current environment with their versions, and redirecting it to requirements.txt saves this list.

Question 1 of 25
Question 1 of 25

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent