
Welcome to FastAPI Masterclass! In this lesson, we introduce the FastAPI framework built on top of the Python programming language. We:
explain what an API is
learn the history of FastAPI
compare FastAPI with its competitors Flask and Django
introduce technical prerequisites
discuss technical setup and our next steps
This lesson offers answers to common questions you might have around installing Python and uv, downloading course materials, editor setup, technical support and more.
In this lesson, we setup the uv command-line tool for managing Python versions/projects. This lesson is exclusively for macOS users.
In this lesson, we setup the uv command-line tool for managing Python versions/projects. This lesson is exclusively for Windows users.
In this lesson, we download the FastAPI Masterclass course repository from GitHub. We also utilize the uv sync command within the rent-a-room project to install Python and all project libraries/dependencies (including FastAPI). As you progress through the course, make sure to run uv sync in every project directory before you start that project.
In this lesson, we introduce and install the JSONVue Chrome extension to format JSON. JSON (JavaScript Object Notation) is the data transfer language of the web. We also show the process for installing the course's recommended VSCode editor extensions which are attached to each project.
In this lesson, we show how the Ruff formatter can style and format our Python code. Ruff is made by the same team as the uv Python manager. I've setup the course projects to run Ruff automatically when you save within VSCode.
Introduce the Airbnb application that serves as inspiration for our first project, rent-a-room. We describe the value of the website and click around a few pages.
Learn how clients and servers communicate via routes and endpoints in FastAPI, mapping requests to route handler functions to build backend APIs.
Create a FastAPI server by importing FastAPI from fastapi, creating an app instance, and defining routes so the server can listen for client requests and respond with data.
Learn how get and post requests work over http, how endpoints and payloads form requests, and how status codes like 200, 201, 400, 401, 404, and 500 reflect outcomes.
Define a route in a FastAPI app using a get method decorator to map a function to an endpoint, with the root route returning json.
Discover how curl at the command line makes http requests to a running FastAPI server. Use -X for the http verb and -H for headers like accept application/json.
Review FastAPI basics by building a server and routes, returning JSON from endpoints, with uvicorn, on localhost:8000, and using Swagger docs.
Learn to raise an HTTPException with a 404 not found status in FastAPI, returning a descriptive detail like room not found for a missing room id.
Learn how the official VS Code FastAPI extension helps you navigate and view all routes in your application, showing HTTP verbs, routes like /, /rooms, and their Python handler functions.
Update the getRooms function to accept a search query parameter and maxPrice with defaults (empty string, 10000), then filter rooms by a lowercase name match and price.
Explore the annotated type from Python's typing module, attach metadata to a core type, and leverage FastAPI runtime validation for constraints like min and max lengths.
Learn to use FastAPI with Pydantic data validation, implement an after validator for custom logic on inputs like query parameters, and raise errors for invalid input.
Learn to extract reusable validation logic in FastAPI using Pydantic, applying shared query parameters across rooms and mansions endpoints.
Discover how to use Pydantic string constraints for validation and transformation to auto-lowercase search query parameters in FastAPI, reducing code in get rooms and get mansions.
Explore how the examples parameter enhances field definitions in a pedantic model by supplying sample values such as max price and search terms, clarifying query parameters for developers.
Explore route decorator options to customize Swagger docs by adding summary, description, response_description, and deprecated flags for FastAPI endpoints, improving endpoint readability for end users.
Review query parameters and validation in FastAPI, including path vs query parameters, type coercion, defaults, and annotated types with after validators. Learn how Pydantic models enable reusable, validated parameter schemas.
Learn how headers and cookies work in FastAPI, as key value pairs attach to requests and responses. Discover how cookies persist across requests on the same domain to enable state.
Create a FastAPI endpoint to set cookies using a response object, assigning theme and language, then verify the browser stores them for all subsequent requests to localhost.
Learn how the browser sends language and theme cookies in the cookie header and how FastAPI reads them with annotated cookies to customize greetings.
Explore cookies and headers in FastAPI, including how cookies are automated headers, how to set cookies with the response, and how to declare data sources with type annotations.
Discover how an ORM translates Python into SQL to persist data in relational databases such as SQLite, and why SQL Model, built on SQLAlchemy and Pydantic, fits FastAPI.
Define a database model by creating a room class that inherits from SQLModel, maps to a rooms table, and enables create, query, and delete operations.
Create a database engine to connect your FastAPI app to SQLite. Configure the SQLite URL, enable connect_args for multi-threading, and turn on echo for development debugging.
Import models to register all SQLModel schemas, then define a function that calls metadata.create_all(engine) to build the database and its tables on FastAPI startup.
Restart the server, run uvicorn, and review the orm-generated sql for the rooms table. Open database.db in vscode with SQLite3Editor to view rooms schema, including id and price per night.
Explore injecting a session for each route handler into FastAPI using depends. Learn how the engine remains permanent while the session is a temporary, testable conversation with the database.
Retrieve a session via getSession, execute a simple SQL select using that session, and verify the database interaction with server logs.
Master FastAPI ORM concepts with SQLModel atop Pydantic and SQLAlchemy, mapping Python models to database tables in a SQLite engine using dependency injection for sessions.
Create a post endpoint for /rooms to add room data using the SQL model ORM, validating with a Pydantic room model, committing, refreshing, and returning the created room with 201.
Test the rooms creation endpoint with swagger, sending json payloads via post to create rooms, and verify ids are assigned and data persists in the database.
Replace inline dictionaries with a database query in get_rooms using SQLModel's SELECT and a session to fetch room records. Convert results to Pydantic models and JSON.
Build and optimize dynamic sql queries by moving filtering into the database using where, lower, contains, and ilike, boosting getRooms efficiency with a single query.
Learn how to scale a get rooms endpoint by applying limit and offset to cap results and enable pagination, with an explicit order by on room.id to ensure deterministic sorting.
This lecture demonstrates why using a single pedantic room model for create, update, and database mapping breaks the patch endpoint, and advocates splitting payload models for create, update, and responses.
Add a delete room route that uses the room id path parameter to remove the room from the database and return the deleted room as json with a 200 ok.
Update the delete route to return a room public model, using pydantic for response shaping, and confirm the room exists, delete it, and handle 404 not found.
Learn to extract repeated room-fetching logic into a reusable FastAPI dependency, get room or 404, and compose dependencies with Depends to simplify get, patch, and delete route handlers.
Master database operations in FastAPI using SQLModel and Pydantic: perform create, read, update, delete with session management, advanced querying, dependencies, and flexible response models.
Organize the APIRouter class by moving routes from main.py into general.py and rooms.py, then register these routers in main.py to keep the app lightweight.
Configure the API router to apply a /rooms prefix and rooms tag across all routes, avoiding duplication and enabling swagger docs grouping; reuse the router with different prefixes via include_router.
Configure app-wide or router-level dependencies with FastAPI's dependencies parameter and depends, so global logging, authentication checks, rate limiting, and metrics run before every route.
Register route-level dependencies to guard mutational endpoints with maintenance mode, using checkMaintenanceMode and depends to run before handlers and return 503 when needed.
Learn how to organize a FastAPI app by technical layers and domain features, using routers, services, dependencies, and database clients for clean separation.
Explore how to organize a FastAPI project with Python packages, dunderinit, and a top-level app directory, and how routers, includeRouter, prefixes, tags, and dependencies shape scalable code.
Explore asynchronous code in Python to let FastAPI handle IO-bound tasks with async and await, using the event loop to reduce blocking and boost concurrency.
Update the lifespan function in main.py to async with await for create db and tables, aligning with route handlers and fully async FastAPI before launching the server.
Update route handlers to async await, convert IO-bound database calls to asynchronous operations, manage lazy loading with explicit refresh, and test both async and sync routes in FastAPI.
Create a booking base and a Booking SQL model mapped to the bookings table, with a room_id foreign key to rooms.id, DateTime check-in and check-out fields, and a BookingPublic response.
Expand the booking model by introducing a users table and a user model, linking bookings to users and rooms via foreign keys to form a join-table with check-in and check-out.
Create a FastAPI users router with post /users to create a user, get /users/{id} to fetch, and /users/{id}/bookings to list bookings, wired with a session and dependencies, registered in main.
Validate room and user IDs, create bookings that link a room to a user, and test these endpoints via Swagger docs to ensure correct error handling and data integrity.
This lesson compares select in load and joined load for fetching related data, shows when two queries beat a join for one-to-many relations, and explains data expansion from excessive joins.
Learn to use joined load for eager loading in FastAPI with SQLAlchemy to pull booking, room, and user data in a single query and shape the response with Pydantic schemas.
Refactor FastAPI error handling by centralizing HTTP exception instances in errors.py. Use constants like room not found, user not found, and booking not found for consistent messaging across routes.
Set null on delete preserves bookings by nulling the room reference when a room is deleted, enabling SQLite foreign keys and updating models to allow optional room references.
Use the tilde symbol to negate an exists query and fetch rooms with no bookings, demonstrating how to create an unbooked endpoint in FastAPI Masterclass.
Fetch a distinct list of rooms a user has stayed in by joining bookings to rooms and filtering by the user, ensuring a single query.
Explore outer joins in SQL within a FastAPI endpoint to return each room with a booking count, including rooms with zero bookings, using groupby and count.
Welcome to FastAPI Masterclass, a comprehensive introduction to backend development in Python with FastAPI.
FastAPI is a Python framework for building fast, modern server-side applications and APIs. It has exploded in popularity in the last few years. Today, it has more than 100,000 stars on GitHub and more daily downloads than Django and Flask on PyPi. It powers applications in companies like Netflix, Microsoft, Uber, OpenAI, and Amazon.
One of FastAPI’s greatest strengths is its flexibility. Unlike larger frameworks that impose a specific structure, FastAPI gives developers the freedom to choose how their applications are organized. You can customize the folder structure, database, ORM, authentication system, validation rules, testing strategy, and architecture.
No previous backend development experience is required. This course follows a linear progression, beginning with the fundamentals and gradually advancing to topics such as authorization, authentication, testing, architecture, and more.
Topics covered:
Clients and servers
Routes and HTTP methods
Path parameters
Query parameters
Debugging with Visual Studio Code
Cookies and Headers
FastAPI Validator Functions (Path, Query, Cookie, Header, and More)
Dependencies (Functions, Classes, and Other Callables) and Dependency Injection (DI)
Object-Relational Mappers (ORM)
Database Queries
Database Migrations
Codebase Structure
Password hashing
JSON Web Tokens (JWTs)
Authentication
Authorization
and more!
In addition to FastAPI, the course covers many helpful libraries and tools from the modern Python ecosystem including:
uv
Pydantic
SQLModel
SQLAlchemy
SQLite 3
Alembic
The first part of the course offers a step-by-step walkthrough of a rent-a-room project inspired by home-stay platforms such as Airbnb. We begin from scratch and gradually incorporate all the critical components of a modern FastAPI application.
After the main project, the course explores common backend topics in dedicated sections. These include database migrations, password hashing, JWT-based authentication, authorization, application architecture, and automated testing.
By the end of FastAPI Masterclass, you will not only understand the syntax and features of FastAPI but also understand the fundamental backend principles that apply across programming languages, libraries, or frameworks.
I'm excited to teach you everything I know about this powerful framework, and I look forward to seeing you in the course!