🌍 Worldwide · Programming

FastApi Syllabus

Python FastApi Framework. The full FastApi syllabus: 6 chapters, 16 topics and 45 sub-topics, with 69 flashcards written against it.

6Chapters
16Topics
45Sub-topics
69Flashcards

FastApi syllabus — full chapter and topic list

Expand any chapter to see its topics and sub-topics. This is the whole examinable outline for FastApi, not a summary of it.

  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

FastApi flashcards

The complete FastApi deck: 69 questions with worked answers.

  1. What is FastAPI?

    A modern, high-performance Python web framework for building APIs, built on Starlette (web/ASGI) and Pydantic (data validation), using standard Python type hints.

  2. Which two libraries is FastAPI built on top of, and what does each provide?

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

  3. Name three key advantages FastAPI is known for.

    Very high performance (on par with NodeJS/Go), fast development with fewer bugs due to type hints, and automatic interactive API documentation.

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

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

  5. At what URL is the raw OpenAPI JSON schema served by default in FastAPI?

    At /openapi.json.

  6. What programming feature does FastAPI rely on for validation, serialization, and documentation?

    Standard Python type hints (type annotations), which Pydantic and FastAPI use to validate, convert, and document data.

  7. What command installs FastAPI with its standard optional dependencies?

    pip install "fastapi[standard]", which includes extras like uvicorn, starlette utilities, and email/JSON helpers.

  8. What is Uvicorn and why is it needed to run FastAPI?

    Uvicorn is an ASGI server; FastAPI apps are ASGI applications, so an ASGI server like Uvicorn (or Hypercorn) is required to serve them.

  9. What command starts a FastAPI app in development mode using the FastAPI CLI?

    fastapi dev main.py, which runs the app with auto-reload enabled.

  10. How do you run a FastAPI app named 'app' in file main.py directly with Uvicorn?

    uvicorn main:app --reload (the --reload flag enables auto-reload during development).

  11. Write the minimal FastAPI 'Hello World' application.

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

  12. In FastAPI, what is the object created by 'app = FastAPI()' used for?

    It is the main application instance (an ASGI callable) on which you register path operations (routes) and configuration.

  13. What is a 'path operation' in FastAPI?

    The combination of a URL path and an HTTP operation (decorator like @app.get, @app.post) mapped to a handler function.

  14. List the common HTTP method decorators FastAPI provides for path operations.

    @app.get, @app.post, @app.put, @app.delete, @app.patch, @app.options, @app.head, and @app.trace.

  15. What are path parameters in FastAPI and how are they declared?

    Parts of the URL path captured as function arguments, declared with braces in the path (e.g. "/items/{item_id}") and matched to a function parameter of the same name.

  16. How does FastAPI use a type hint like 'item_id: int' on a path parameter?

    It validates and converts the incoming string to an int; a non-integer value returns an automatic HTTP 422 validation error.

  17. Why must the fixed path '/users/me' be declared before '/users/{user_id}' in FastAPI?

    Path operations are evaluated in order; if the parameterized route came first, '/users/me' would be captured as user_id='me' instead of matching the fixed route.

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

    Use a Python Enum class (subclassing str, Enum) as the parameter's type annotation; only the enum members are allowed and documented.

  19. What is a query parameter and how is it distinguished from a path parameter?

    A query parameter is a key-value pair in the URL after '?' (e.g. ?skip=0&limit=10); it is any function parameter NOT part of the path, whereas path parameters appear inside the path braces.

  20. How do you give a query parameter a default value versus making it required?

    Assign a default value (e.g. skip: int = 0) to make it optional; declare it without a default (e.g. q: str) to make it required.

Show the other 49 FastApi flashcards
  1. How do you declare an optional query parameter that may be omitted entirely in FastAPI?

    Give it a default of None with an optional type, e.g. q: str | None = None.

  2. How are boolean query parameters parsed in FastAPI?

    FastAPI converts strings like 'true', 'True', '1', 'on', 'yes' to True and their negatives to False, coercing the value to bool.

  3. What is the Query utility used for in FastAPI?

    Query adds extra validation and metadata to query parameters, such as min_length, max_length, pattern (regex), default values, and description.

  4. What is a request body in FastAPI and how do you declare one?

    Data sent by the client in the body (typically JSON); you declare it by adding a parameter whose type is a Pydantic BaseModel.

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

    If the name matches a path parameter it's a path param; if it's a singular type (int, str, etc.) it's a query param; if it's a Pydantic model it's read from the request body.

  6. What is a Pydantic BaseModel and its role in FastAPI request bodies?

    A class defining data schema via typed attributes; FastAPI uses it to validate, parse, and document the JSON request body, returning 422 on invalid data.

  7. How can you send multiple Pydantic models plus scalars in a single FastAPI request body?

    Declare multiple body parameters (each becomes a JSON key), and use Body() for singular values to embed them as keys rather than treating them as query params.

  8. What is dependency injection in FastAPI?

    A system where a path operation declares dependencies (via Depends) that FastAPI resolves and injects automatically, sharing logic like DB sessions, auth, and common parameters.

  9. How do you declare a dependency in a FastAPI path operation?

    Add a parameter with Depends, e.g. commons: dict = Depends(common_parameters), where the dependency is a callable (function or class).

  10. What kinds of callables can be used as FastAPI dependencies?

    Any callable: plain functions, async functions, or classes (using the class itself as the dependency, which injects an instance).

  11. How can a dependency in FastAPI perform setup and teardown (e.g. open/close a DB session)?

    Use a generator dependency with 'yield'; code before yield runs as setup, the yielded value is injected, and code after yield runs as teardown after the response.

  12. How do you apply a dependency that runs but whose return value you don't need (e.g. auth check)?

    Use the dependencies=[Depends(...)] argument on the path operation decorator or router, so it executes without injecting a value.

  13. What does 'sub-dependencies' mean in FastAPI's dependency system?

    Dependencies can themselves declare dependencies via Depends, forming a tree that FastAPI resolves recursively (and caches shared ones within a request).

  14. By default, if the same dependency is used multiple times in one request, how often is it called?

    Once; FastAPI caches the dependency's result per request. Set use_cache=False in Depends to force re-evaluation.

  15. Which security schemes does FastAPI provide utilities for out of the box?

    OAuth2 (including password flow with Bearer tokens), API keys (header/query/cookie), HTTP Basic, and OpenID Connect via fastapi.security classes.

  16. What class is commonly used to implement OAuth2 password flow with bearer tokens in FastAPI?

    OAuth2PasswordBearer, instantiated with a tokenUrl, used as a dependency to extract and require the Bearer token.

  17. What is the recommended algorithm/standard for tokens in FastAPI's OAuth2 tutorial, and how is the password stored?

    JWT (JSON Web Tokens) signed with a secret; passwords are stored hashed (e.g. bcrypt via passlib), never in plaintext.

  18. How do you enforce that a user is authenticated for an endpoint in FastAPI?

    Declare a dependency (e.g. current_user = Depends(get_current_user)) that validates the token and raises HTTPException 401 with WWW-Authenticate header if invalid.

  19. What are OAuth2 scopes used for in FastAPI security?

    Scopes define fine-grained permissions attached to a token; dependencies can require specific scopes and reject tokens lacking them with a 403/401.

  20. What are background tasks in FastAPI and when are they useful?

    Operations run after returning the response (e.g. sending email, logging), letting the client get a fast response without waiting for the work to finish.

  21. How do you add a background task to a FastAPI endpoint?

    Add a BackgroundTasks parameter to the path function, then call background_tasks.add_task(func, *args, **kwargs).

  22. For heavy or CPU-intensive work, why might FastAPI BackgroundTasks be insufficient, and what is the alternative?

    BackgroundTasks run in the same process and are lost on restart with no retries; for heavy/distributed work use a task queue like Celery, RQ, or ARQ with a message broker.

  23. What is middleware in FastAPI?

    A function/class that processes every request before it reaches the path operation and every response before it is returned, wrapping the whole request-response cycle.

  24. How do you write a custom HTTP middleware function in FastAPI?

    Use the @app.middleware("http") decorator on an async function that takes (request, call_next), calls response = await call_next(request), and returns the response.

  25. How do you add CORS support in FastAPI?

    Add CORSMiddleware via app.add_middleware(CORSMiddleware, allow_origins=[...], allow_methods=[...], allow_headers=[...]).

  26. What ORM is most commonly used with FastAPI for relational (SQL) databases, and what modern library combines it with Pydantic?

    SQLAlchemy is the common ORM; SQLModel (by FastAPI's author) combines SQLAlchemy and Pydantic into unified models.

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

    Through a dependency with 'yield' (e.g. get_db) that creates a Session, yields it, and closes it in a finally/teardown block.

  28. Why should Pydantic response models be used when returning SQLAlchemy ORM objects in FastAPI?

    They control/validate the output schema, hide sensitive fields (like hashed passwords), and serialize ORM objects; enabling from_attributes/orm_mode lets Pydantic read attributes.

  29. What are NoSQL (non-relational) databases and a common example used with FastAPI?

    Databases that store data without fixed relational schemas (document, key-value, graph, wide-column). MongoDB (a document store) is common with FastAPI, often via Motor (async) or Beanie.

  30. Compare SQL and NoSQL databases on schema and scaling.

    SQL: fixed/rigid schema, strong ACID transactions, typically scales vertically, uses JOINs. NoSQL: flexible/dynamic schema, often eventual consistency (BASE), scales horizontally, denormalized data.

  31. Which async MongoDB drivers/ODMs are commonly paired with FastAPI?

    Motor (async MongoDB driver) and Beanie (an async ODM built on Motor and Pydantic).

  32. What tools are used to write tests for FastAPI applications?

    pytest as the test runner and Starlette/FastAPI's TestClient (based on httpx/requests) or httpx AsyncClient to make requests against the app.

  33. Write a minimal FastAPI test using TestClient.

    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() == {"message": "Hello World"}

  34. How do you test asynchronous FastAPI endpoints that require an async client?

    Use httpx.AsyncClient with an ASGITransport pointing to the app, inside async test functions, typically with the anyio/pytest-asyncio plugin.

  35. What is dependency overriding in FastAPI testing, and how is it done?

    Replacing a real dependency with a test double by setting app.dependency_overrides[original_dependency] = test_dependency, letting you inject test DBs/auth without changing app code.

  36. Why is FastAPI's dependency_overrides mechanism preferred over monkeypatching for tests?

    It's built into FastAPI, integrates cleanly with the DI system, is scoped to the app, and lets you swap dependencies (DB sessions, auth, configs) declaratively and reversibly.

  37. What is mocking, and why mock dependencies in tests?

    Replacing real objects/services with controllable fakes; it isolates the unit under test, avoids slow/external calls (DBs, APIs), and lets you assert interactions and simulate edge cases.

  38. Which standard Python library is used for mocking, and what class simulates objects?

    unittest.mock, providing Mock/MagicMock objects and the patch() function/decorator to replace targets during a test.

  39. What is the difference between a stub and a mock in testing?

    A stub returns canned responses to make the test run; a mock also records calls and lets you assert that expected interactions occurred (behavior verification).

  40. Name common deployment options for a FastAPI application.

    Containers (Docker) on Kubernetes/ECS, PaaS (Render, Railway, Fly.io, Heroku), serverless (AWS Lambda via Mangum), or a VM running Uvicorn behind a reverse proxy like Nginx.

  41. How is a FastAPI app typically deployed with Docker in production?

    Build an image installing dependencies and copying the app, then run it with an ASGI server, e.g. CMD ["fastapi", "run", "main.py", "--port", "80"] or via uvicorn/gunicorn.

  42. What is the difference between 'fastapi dev' and 'fastapi run' commands?

    'fastapi dev' runs with auto-reload for development; 'fastapi run' runs in production mode (no reload, optimized defaults).

  43. Why run Uvicorn workers behind Gunicorn (or use multiple workers) in production FastAPI deployments?

    To utilize multiple CPU cores and handle more concurrency; Gunicorn manages multiple Uvicorn worker processes (via the uvicorn.workers.UvicornWorker class) for parallelism and resilience.

  44. Why is a reverse proxy like Nginx or Traefik commonly placed in front of a FastAPI/Uvicorn app?

    To terminate TLS/HTTPS, serve static files, load balance, handle timeouts/buffering, and provide a hardened public-facing entry point.

  45. What is CI/CD?

    Continuous Integration (automatically building and testing code on each commit/merge) and Continuous Delivery/Deployment (automatically releasing or deploying validated changes to environments).

  46. What is the difference between Continuous Delivery and Continuous Deployment?

    Continuous Delivery automatically prepares/validates releases but requires a manual approval to deploy to production; Continuous Deployment deploys every passing change to production automatically with no manual gate.

  47. What typically runs in the CI stage of a FastAPI project's pipeline?

    Installing dependencies, linting/formatting checks (e.g. ruff), type checking (mypy), and running the pytest test suite on each push or pull request.

  48. Name a common CI/CD platform used to automate FastAPI pipelines.

    GitHub Actions (also GitLab CI, CircleCI, Jenkins); workflows are defined in YAML, e.g. .github/workflows/*.yml, triggered on push/PR.

  49. In a typical FastAPI CI/CD flow, what are the ordered stages from commit to production?

    Commit/PR triggers CI (lint, type-check, tests) then build (Docker image) then push to a registry then deploy to staging/production, often with automated smoke tests.

FastApi syllabus FAQ

What is in the FastApi syllabus?

The FastApi syllabus 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 and topics are in the FastApi syllabus?

6 chapters and 16 topics, broken down further into 45 sub-topics. The largest chapter is Basic Concepts, with 4 topics.

Are there FastApi flashcards?

Yes — 69 question-and-answer flashcards, printed in full on 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.