FastAPI Crash Course
- 25Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
Which Python framework does FastAPI utilize as its foundation for handling basic web functionalities?
Which Python framework does FastAPI utilize as its foundation for handling basic web functionalities?
25 questions
- 1
Which Python framework does FastAPI utilize as its foundation for handling basic web functionalities?
- A
Flask, known for its minimalism and direct ASGI integration support.
- B
Pyramid, offering a highly flexible and extensible framework architecture.
- C
Django, providing extensive ORM capabilities and template rendering.
- D
Starlette, which is an ASGI toolkit responsible for core web components.
Correct answer
DStarlette, 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.
- A
- 2
What is the primary advantage of ASGI over WSGI in the context of web application development?
- A
WSGI is specifically designed for asynchronous operations, while ASGI is synchronous.
- B
ASGI enables concurrent handling of multiple requests, unlike WSGI's synchronous model.
- C
WSGI offers better integration with modern Python frameworks compared to ASGI.
- D
ASGI supports synchronous request handling exclusively for better stability.
Correct answer
BASGI 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.
- A
- 3
Which tool does FastAPI use for automatic data validation and serialization?
- A
Cerberus, a lightweight data validation library with schema definition.
- B
Marshmallow, providing schema-based object serialization and deserialization.
- C
Pydantic, leveraging Python type hints for data validation.
- D
SQLAlchemy, primarily used for object-relational mapping in databases.
Correct answer
CPydantic, 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.
- A
- 4
What interactive documentation tools are bundled with the standard FastAPI package?
- A
Insomnia and cURL, for making HTTP requests to the API.
- B
ReDoc and Sphinx, for generating static API documentation.
- C
Swagger UI and Postman, to test API endpoints directly.
- D
Swagger UI and ReDoc, providing interactive API documentation.
Correct answer
DSwagger 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.
- A
- 5
How does FastAPI manage components and database connections through its dependency injection system?
- A
Dependencies are defined as global variables that FastAPI automatically accesses.
- B
It allows defining dependencies as functions, handling their lifecycle automatically.
- C
Each component must manage its own lifecycle independently without framework support.
- D
It requires explicit manual import and instantiation of all components.
Correct answer
BIt 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.
- A
- 6
What is the recommended tool for deploying a FastAPI application for users who prefer to avoid complex DevOps tasks?
- A
AWS EC2, requiring extensive knowledge of server management and configuration.
- B
Heroku, which has its own specific CLI for application deployment.
- C
Render.com, offering automated deployment from GitHub repositories.
- D
DigitalOcean Droplets, which demand manual setup of infrastructure.
Correct answer
CRender.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.
- A
- 7
What is the purpose of creating a virtual environment in a Python project?
- A
To install dependencies globally across all Python projects on the machine.
- B
To allow the direct execution of Python scripts without needing an interpreter.
- C
To bypass the need for a package manager like pip for dependency installation.
- D
To ensure all project dependencies are isolated and localized to the project folder.
Correct answer
DTo 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.
- A
- 8
How do you activate a virtual environment on a Mac using the command line?
- A
source ./.venv/bin/activate
- B
python ./.venv/activate
- C
run ./.venv/activate
- D
call ./.venv/scripts/activate
Correct answer
Asource ./.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. - A
- 9
Which command is used to install FastAPI with its standard dependencies in a virtual environment?
- A
pip install fastapi[standard]
- B
pip install fastapi-standard
- C
pip install fastapi --with-defaults
- D
pip install fastapi[all]
Correct answer
Apip 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. - A
- 10
What is the primary function of the
main.pyfile in a FastAPI application?- A
It stores all the static files like images and CSS stylesheets.
- B
It serves as the entry point for the application, initializing FastAPI.
- C
It holds helper functions and utility classes for the entire project.
- D
It contains all the database schema definitions and migration scripts.
Correct answer
BIt serves as the entry point for the application, initializing FastAPI.
Explanation
The
main.pyfile serves as the entry point for the FastAPI application, similar toserver.jsorapp.jsin Node.js/Express. It's where the FastAPI instance is initialized and routers are included. - A
- 11
How are HTTP GET routes defined in FastAPI?
- A
Using the
@app.get('/path')decorator above an asynchronous function. - B
By calling
app.route('/path', methods=['GET'])directly. - C
Through a configuration file mapping URLs to specific handler functions.
- D
By defining a function named
get_path()that FastAPI auto-detects.
Correct answer
AUsing 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. - A
- 12
What is the purpose of accessing
/docsendpoint in a running FastAPI application?- A
To download the full source code of the FastAPI application.
- B
To access the interactive Swagger UI documentation for testing routes.
- C
To view the application's performance metrics and server logs.
- D
To configure database connections and environment variables.
Correct answer
BTo access the interactive Swagger UI documentation for testing routes.
Explanation
Accessing the
/docsendpoint 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. - A
- 13
How does FastAPI allow extracting dynamic segments from a URL path, such as an item ID?
- A
By defining path parameters in curly braces, e.g.,
/items/{item_id}. - B
By using query parameters like
/items?id=123in the URL. - C
Through custom HTTP headers containing the dynamic value.
- D
By including the dynamic segment in the request body for POST requests.
Correct answer
ABy 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. - A
- 14
When creating a POST request, what happens if the request body contains fields not defined in the Pydantic schema?
- A
FastAPI raises a validation error and rejects the entire request.
- B
The undefined fields are automatically stripped out and ignored by FastAPI.
- C
The request is processed, but the extra fields are marked as warnings in logs.
- D
FastAPI attempts to infer types for the extra fields and includes them.
Correct answer
BThe 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.
- A
- 15
Why is it recommended to use
APIRouterfor organizing routes in larger FastAPI applications?- A
It prevents the creation of custom middleware for specific route groups.
- B
It automatically generates database migrations for all defined endpoints.
- C
It allows all routes to be defined in a single
main.pyfile without clutter. - D
It enables grouping related routes into separate files and adding prefixes or tags.
Correct answer
DIt enables grouping related routes into separate files and adding prefixes or tags.
Explanation
Using
APIRouteris 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 toexpress.Routerin Node.js. - A
- 16
What is the primary function of the
requirements.txtfile in a Python project for deployment?- A
It defines the database schema and initial data for the application.
- B
It serves as the main entry point for the application on the server.
- C
It lists all the required Python packages and their versions for the project.
- D
It contains environment variables specific to the production server.
Correct answer
CIt lists all the required Python packages and their versions for the project.
Explanation
The
requirements.txtfile lists all the dependencies (Python packages and their specific versions) required for the project. During deployment, a command likepip install -r requirements.txtis used to install these dependencies, ensuring the correct environment. - A
- 17
What is the primary purpose of defining
IssueStatusandIssuePriorityasEnumclasses in FastAPI schemas?- A
To convert these fields into numerical representations for database storage.
- B
To restrict status and priority to a predefined set of specific, valid values.
- C
To allow any string value for status and priority, providing maximum flexibility.
- D
To enable automatic encryption of these fields for security purposes.
Correct answer
BTo restrict status and priority to a predefined set of specific, valid values.
Explanation
Defining
IssueStatusandIssuePriorityasEnumclasses restricts their possible values to a predefined set (e.g., 'open', 'in progress', 'closed' for status). This enforces strict data validation and consistency. - A
- 18
When creating an
IssueCreateschema for a POST request, why is thestatusfield typically omitted?- A
The status is usually hardcoded to 'open' when an issue is first created.
- B
Status is a read-only field and cannot be included in creation requests.
- C
The client is not allowed to set the initial status of an issue.
- D
The status field is automatically inferred from the issue's priority.
Correct answer
AThe status is usually hardcoded to 'open' when an issue is first created.
Explanation
When creating an
IssueCreateschema for a POST request, thestatusfield is typically omitted because the status is hardcoded as 'open' when an issue is first created. The client doesn't provide this initial value. - A
- 19
Why are fields like
titleanddescriptionmadeOptionalin anIssueUpdateschema?- A
To prevent any modification of these fields once an issue is created.
- B
To enforce that all fields must be present in every update request.
- C
To allow the system to automatically generate these fields if they are missing.
- D
To enable partial updates where only specific fields need to be provided.
Correct answer
DTo enable partial updates where only specific fields need to be provided.
Explanation
Fields like
titleanddescriptionare madeOptionalin anIssueUpdateschema 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. - A
- 20
What HTTP status code is typically returned for a successful
POSTrequest that creates a new resource?- A
201 Created, specifically for successful resource creation.
- B
200 OK, indicating a standard successful response.
- C
400 Bad Request, signifying a client-side error in the request.
- D
204 No Content, used when the server fulfills the request but does not return content.
Correct answer
A201 Created, specifically for successful resource creation.
Explanation
For a successful
POSTrequest 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. - A
- 21
What is the purpose of middleware in a backend framework like FastAPI?
- A
To define the data models for database interaction exclusively.
- B
To generate client-side JavaScript for interacting with the API.
- C
To handle asynchronous tasks in the background without affecting requests.
- D
To execute code before or after each request, accessing request and response objects.
Correct answer
DTo 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.
- A
- 22
How can you add a custom header, such as
X-Process-Time, to all responses in FastAPI?- A
By modifying the
responseobject directly within each individual route function. - B
By using a middleware that intercepts responses and adds the header.
- C
Through a global configuration setting in the
settings.pyfile. - D
By defining a
ResponseHeaderclass in the Pydantic schemas.
Correct answer
BBy 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 theresponseobject's headers before the response is sent back to the client. - A
- 23
What is CORS and why is it important for a public API?
- A
CORS defines how a server and client interact over different network protocols.
- B
CORS is a caching mechanism that improves API response times for clients.
- C
CORS is a security feature that encrypts all API traffic for privacy.
- D
CORS specifies how resources from different origins (domains) can be accessed, preventing browser security errors.
Correct answer
DCORS 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.
- A
- 24
How do you allow all domains to access your FastAPI application when implementing CORS middleware?
- A
By omitting the
CORS_Middlewareentirely from the application. - B
By setting
allow_originsto a specific whitelist of trusted domains. - C
By configuring the web server (e.g., Nginx) to handle CORS, not FastAPI.
- D
By setting
allow_origins=["*"]in theCORS_Middlewareconfiguration.
Correct answer
DBy setting
allow_origins=["*"]in theCORS_Middlewareconfiguration.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. - A
- 25
What command is used to generate the
requirements.txtfile, listing project dependencies?- A
python generate-deps.py
- B
pip freeze > requirements.txt
- C
pip list --output requirements.txt
- D
python install --save-dev requirements.txt
Correct answer
Bpip freeze > requirements.txt
Explanation
The command
pip freeze > requirements.txtis used to generate therequirements.txtfile.pip freezeoutputs a list of all installed packages in the current environment with their versions, and redirecting it torequirements.txtsaves this list. - A

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