🌍 Python · subject

Python FastApi Syllabus

The FastApi syllabus for Python in full: 6 chapters, 16 topics and 45 sub-topics, every one listed below, plus 56 FastApi flashcards with answers.

6Chapters
16Topics
45Sub-topics
56Flashcards

FastApi syllabus: all 6 chapters

Expand any chapter to see its topics and sub-topics.

  1. Introduction to FastAPI

    2 topics
    • Overview
      • What is FastAPI?
      • Key Features
      • Advantages over other frameworks
    • Installation
      • Setting up a Virtual Environment
      • Installing FastAPI using pip
      • Installing an ASGI server (e.g., Uvicorn)
  2. Basic Concepts

    4 topics
    • First Steps
      • Creating a Basic FastAPI Application
      • Running the FastAPI Application
      • Understanding the Auto-Generated Documentation
    • Path Parameters
      • Defining Path Parameters
      • Using Path Parameters in Endpoints
    • Query Parameters
      • Defining Query Parameters
      • Optional and Required Query Parameters
    • Request Body
      • Using Pydantic Models
      • Defining Request Bodies
      • Validating Request Data
  3. Advanced Concepts

    4 topics
    • Dependency Injection
      • Defining Dependencies
      • Using Dependencies in Endpoints
      • Global Dependencies
    • Security
      • OAuth2 with Password (and hashing), Bearer with JWT tokens
      • Handling Security Scopes
      • Using API Keys
    • Background Tasks
      • Defining Background Tasks
      • Using Background Tasks in Endpoints
    • Middleware
      • Creating Middleware
      • Using Middleware in FastAPI
  4. Database Integration

    2 topics
    • SQL (Relational Databases)
      • Using SQLAlchemy
      • Setting up Database Connections
      • Defining Models and Schemas
      • Performing CRUD Operations
    • NoSQL (Non-Relational Databases)
      • Using MongoDB with Motor
      • Setting up Database Connections
      • Defining Models and Schemas
      • Performing CRUD Operations
  5. Testing

    2 topics
    • Writing Tests
      • Using pytest
      • Testing Endpoints
      • Using TestClient
    • Mocking Dependencies
      • Using Dependency Overrides
      • Mocking External Services
  6. Deployment

    2 topics
    • Deployment Options
      • Deploying with Docker
      • Deploying to AWS
      • Deploying to Google Cloud
      • Deploying to Heroku
    • CI/CD
      • Setting up GitHub Actions
      • Automating Tests and Deployments

Python FastApi flashcards — 56 questions with answers

  1. What is FastAPI and what is its primary purpose?

    FastAPI is a modern, high-performance Python web framework for building APIs, based on standard Python type hints. It is designed for speed, automatic data validation, and automatic interactive documentation.

  2. Which two libraries does FastAPI build upon, and what does each provide?

    Starlette provides the web/ASGI toolkit (routing, requests, responses), and Pydantic provides data validation and serialization via Python type hints.

  3. Why is FastAPI considered 'fast'? Name the main performance factors.

    It is built on Starlette and async ASGI, runs on Uvicorn (uvloop), and avoids redundant validation. Its performance is on par with NodeJS and Go for many workloads.

  4. What two documentation UIs does FastAPI generate automatically, and at which default URLs?

    Swagger UI at /docs and ReDoc at /redoc, both generated from the OpenAPI schema.

  5. What open standard schema does FastAPI automatically produce for an application?

    An OpenAPI schema (served as JSON at /openapi.json), which also conforms to JSON Schema for the data models.

  6. What command installs FastAPI together with its standard optional dependencies?

    pip install "fastapi[standard]" — this includes Uvicorn and extras like the standard CLI, validation, and email support.

  7. What type of server is required to run a FastAPI application, and name the most common one?

    An ASGI server is required; Uvicorn is the most common (Hypercorn is an alternative).

  8. What is the recommended development command to run a FastAPI app defined in main.py?

    fastapi dev main.py — it runs the app with auto-reload enabled for development.

  9. What is the difference between `fastapi dev` and `fastapi run`?

    `fastapi dev` runs in development mode with auto-reload on code changes; `fastapi run` runs in production mode without reload.

  10. Write the minimal FastAPI 'first steps' application with a root endpoint.

    from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"}

  11. In FastAPI, what is the object created by `app = FastAPI()` called and what does it do?

    It is the application instance — the main point of interaction that registers all routes and creates the API.

  12. What is a 'path operation' in FastAPI terminology?

    The combination of a URL path and an HTTP operation (method) — e.g., GET on /items — handled by a path operation function via a decorator like @app.get().

  13. How are path parameters declared in a FastAPI route, and how is type conversion handled?

    They are declared in the path string with braces, e.g. @app.get("/items/{item_id}"), and given a type-annotated function parameter. FastAPI parses, validates, and converts the value (e.g., int).

  14. What HTTP status code does FastAPI return when a path/query parameter fails type validation?

    422 Unprocessable Entity, with a JSON body describing the validation error.

  15. Why does the order of path operations matter when one path could match a fixed value and a parameter?

    FastAPI evaluates routes in declaration order, so a fixed path like /users/me must be declared before /users/{user_id}; otherwise 'me' would be captured as the parameter.

  16. How do you restrict a path parameter to a fixed set of allowed values in FastAPI?

    Create an Enum class (typically subclassing str, Enum) and use it as the parameter's type annotation.

  17. How does FastAPI distinguish path parameters from query parameters in a function signature?

    Parameters whose names appear in the path string are path parameters; all other function parameters are interpreted as query parameters.

  18. How do you make a query parameter optional with a default value in FastAPI?

    Give the function parameter a default value, e.g. def read(q: str | None = None): — without a default it becomes required.

  19. How does FastAPI parse a boolean query parameter like ?short=yes or ?short=1?

    It coerces common truthy/falsy forms (true, True, 1, yes, on) to bool True and (false, 0, no, off) to False automatically.

  20. What class is used to add validation and metadata to query parameters in FastAPI?

    Query, from fastapi — e.g. q: str = Query(default=None, min_length=3, max_length=50).

Show the other 36 FastApi flashcards
  1. How do you declare a request body in FastAPI, and what status code is returned on invalid body data?

    Declare a Pydantic BaseModel and use it as a function parameter type. Invalid data yields a 422 response with detailed errors.

  2. How does FastAPI decide whether a parameter comes from the path, query, or request body?

    If the name is in the path it's a path param; if it's a singular type (int, str) it defaults to a query param; if it's a Pydantic model it's read from the request body.

  3. Which Pydantic class do request-body models inherit from in FastAPI?

    pydantic.BaseModel.

  4. How do you force a singular value (like an int) to be read from the request body instead of as a query parameter?

    Annotate it with Body(), e.g. importance: int = Body().

  5. What is Dependency Injection in FastAPI and which function declares a dependency?

    It is a mechanism to declare and reuse shared logic/resources that FastAPI resolves automatically. Dependencies are declared with Depends(), e.g. commons: dict = Depends(get_common_params).

  6. Name three benefits of using FastAPI's dependency injection system.

    Code reuse (shared logic), separation of concerns, and easy testing via dependency overrides; it also handles authentication, DB sessions, and validation.

  7. How can a dependency provide a resource and guarantee cleanup (e.g., closing a DB session)?

    Use a generator dependency with yield: code before yield sets up the resource, the yielded value is injected, and code after yield runs as teardown.

  8. What can be used as a dependency in FastAPI besides functions?

    Any callable, including classes (the class is called to create an instance), and dependencies can themselves have sub-dependencies.

  9. How do you attach a dependency that runs but whose return value you don't need (e.g., a permission check)?

    Add it to the decorator's dependencies list, e.g. @app.get("/items/", dependencies=[Depends(verify_token)]).

  10. Which OpenAPI/standards-based scheme does FastAPI provide for token-based authentication, and from which module?

    OAuth2 with Password flow and Bearer tokens via OAuth2PasswordBearer in fastapi.security.

  11. What does OAuth2PasswordBearer(tokenUrl="token") do in a FastAPI security setup?

    It declares the URL where clients send username/password to obtain a token and creates a dependency that extracts the Bearer token from the Authorization header.

  12. Which HTTP status code and header should a FastAPI endpoint return when authentication fails?

    401 Unauthorized with the header WWW-Authenticate: Bearer.

  13. What is the recommended library and algorithm approach for password hashing in FastAPI security tutorials?

    Use passlib (commonly with bcrypt) to hash and verify passwords; never store plaintext passwords.

  14. In FastAPI's OAuth2 JWT flow, what does the server return after successful login and what does the client send afterward?

    The server returns a JWT access token (with token_type 'bearer'); the client then sends it in the Authorization: Bearer <token> header on subsequent requests.

  15. What is the purpose of BackgroundTasks in FastAPI?

    To run operations after returning the response, so the client isn't kept waiting — e.g. sending email notifications or writing logs.

  16. How do you add a background task in a FastAPI path operation?

    Declare a BackgroundTasks parameter and call background_tasks.add_task(func, *args, **kwargs); the task runs after the response is sent.

  17. When should you use Celery instead of FastAPI's built-in BackgroundTasks?

    For heavy, long-running, or CPU-intensive jobs needing a distributed task queue, retries, scheduling, or a separate worker process. BackgroundTasks suits light operations within the same process.

  18. What is middleware in FastAPI and when does its code run?

    Middleware is a function/class that processes every request before it reaches the path operation and every response before it's returned, enabling cross-cutting concerns like logging, timing, or headers.

  19. Write the signature pattern for a custom HTTP middleware function in FastAPI.

    @app.middleware("http") async def add_process_time(request: Request, call_next): response = await call_next(request) return response # call_next runs the rest of the app

  20. Which middleware do you add in FastAPI to allow requests from other origins (browsers)?

    CORSMiddleware (from fastapi.middleware.cors / starlette), configured with allow_origins, allow_methods, and allow_headers.

  21. Which ORM is traditionally used with FastAPI for relational databases, and which library does FastAPI's creator recommend that combines it with Pydantic?

    SQLAlchemy is traditional; SQLModel (by FastAPI's creator) combines SQLAlchemy and Pydantic in one model.

  22. In a FastAPI + SQLAlchemy setup, how is a database session typically provided to path operations?

    Through a dependency (get_db) that uses yield to create a SessionLocal, inject it, and close it afterward.

  23. What three core objects must you configure for SQLAlchemy in a FastAPI app?

    An engine (create_engine with the DB URL), a session factory (sessionmaker -> SessionLocal), and a declarative Base class for models.

  24. For SQLite specifically with FastAPI, what connect argument is required and why?

    connect_args={"check_same_thread": False}, because SQLite by default allows only the creating thread to use the connection, while FastAPI may use multiple threads.

  25. What is a NoSQL (non-relational) database, and name two types?

    A database that stores data without fixed relational tables/schemas. Types include document stores (MongoDB), key-value stores (Redis), wide-column (Cassandra), and graph databases (Neo4j).

  26. Give one key advantage and one trade-off of NoSQL vs SQL databases.

    Advantage: flexible schema and horizontal scalability for large/unstructured data. Trade-off: weaker ACID guarantees and limited multi-table JOINs/complex relational queries compared to SQL.

  27. Which async driver is commonly used to connect FastAPI to MongoDB?

    Motor (the async MongoDB driver), often paired with Beanie or ODMantic as a Pydantic-based ODM.

  28. Which HTTP client class does FastAPI use for writing tests, and from which library?

    TestClient from fastapi.testing (backed by Starlette/httpx) — instantiated as client = TestClient(app).

  29. Write a minimal FastAPI test using TestClient that checks the root endpoint.

    from fastapi.testclient import TestClient from main import app client = TestClient(app) def test_root(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"Hello": "World"}

  30. How do you replace a real dependency (like a DB) with a fake one during FastAPI tests?

    Use app.dependency_overrides[original_dependency] = fake_dependency; this swaps the dependency only for tests without changing app code.

  31. Why is dependency override preferred over patching/monkeypatching for mocking dependencies in FastAPI?

    Because FastAPI's DI system is designed for it: overrides are explicit, scoped, and reset easily (clear the dict), keeping production code untouched and tests isolated/repeatable.

  32. List three common options for deploying a FastAPI application.

    (1) A container image (Docker) run on Kubernetes/cloud; (2) a managed/PaaS host (e.g., a cloud run service or platform); (3) a VM/server running Uvicorn behind a reverse proxy like Nginx, often managed by Gunicorn with Uvicorn workers.

  33. What is the recommended way to run FastAPI in production for multiple worker processes?

    Run Uvicorn with multiple workers (e.g. fastapi run --workers N or Gunicorn managing uvicorn.workers.UvicornWorker), typically behind a reverse proxy/load balancer.

  34. What is CI/CD and what does each part stand for?

    CI is Continuous Integration (automatically building and testing code on each change/merge); CD is Continuous Delivery/Deployment (automatically releasing/deploying validated code).

  35. What are the typical stages of a CI/CD pipeline for a FastAPI project?

    Lint/format check, install dependencies, run automated tests (pytest), build the artifact/Docker image, and deploy to the target environment.

  36. Why is a reverse proxy (e.g., Nginx) commonly placed in front of a deployed FastAPI/Uvicorn server?

    To handle TLS/HTTPS termination, serve static files, load-balance across workers, and add buffering/security — letting Uvicorn focus on the ASGI app.

Python FastApi FAQ

What is in the Python FastApi syllabus?

Python FastApi is split into 6 chapters: Introduction to FastAPI, Basic Concepts, Advanced Concepts, Database Integration, Testing and Deployment. Together they contain 16 topics and 45 sub-topics.

How many chapters are in Python FastApi?

6 chapters, containing 16 topics and 45 sub-topics. The largest chapter is Basic Concepts, with 4 topics.

Are there flashcards for Python FastApi?

Yes — a 56-card FastApi deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.