1.5 Hours

1. Introduction to FastAPI

Foundations

What is FastAPI?

FastAPI is a modern, high-performance web framework for building APIs with Python. It was created by Sebastián Ramírez (tiangolo) and released in 2018. FastAPI is built on top of Starlette for web routing and Pydantic for data validation, making it one of the fastest Python frameworks available today.

Unlike older frameworks like Flask or Django, FastAPI was designed from the ground up to leverage Python's type hints and async/await syntax, resulting in automatic API documentation, request validation, and excellent IDE support.

Why FastAPI?

FastAPI has exploded in popularity because it solves real problems that other Python frameworks struggle with:

  • Speed: FastAPI is as fast as Node.js and Go, making it one of the fastest Python frameworks available. In benchmark tests, it consistently outperforms Flask and Django.
  • Automatic Documentation: When you write a FastAPI endpoint, it automatically generates interactive API documentation using Swagger UI and ReDoc with zero extra code.
  • Type Safety: By using Python type hints, FastAPI validates request data, serializes responses, and gives you IDE autocompletion.
  • Async Support: FastAPI natively supports Python's async/await syntax, allowing you to handle thousands of concurrent connections efficiently.

Performance Comparison

In independent benchmarks (TechEmpower), FastAPI ranks among the fastest Python frameworks. It is approximately 3x faster than Flask and 2x faster than Django for typical API workloads because of its ASGI architecture.

Installing FastAPI

To use FastAPI, you need to install both FastAPI itself and an ASGI server to run it. The most popular ASGI server is Uvicorn, which is lightning fast due to being built on uvloop and httptools.

Bash
pip install fastapi uvicorn
Local Setup Instructions: After installing, create a file called main.py. Write your FastAPI code, then run uvicorn main:app --reload in your terminal. Open http://localhost:8000/docs to see the interactive API documentation.

Your First FastAPI Application

Let's create a minimal FastAPI application. Save this as main.py.

Python 3
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "query": q}
To run this code: Save as main.py, then run uvicorn main:app --reload in your terminal. Visit http://localhost:8000 to see your API running. The --reload flag auto-restarts the server when you make changes.

Understanding the Code

Let's break down what's happening in this simple application:

  • from fastapi import FastAPI — Imports the FastAPI class into your file.
  • app = FastAPI() — Creates the FastAPI application instance. This is your main entry point.
  • @app.get(<strong><code>/) — A decorator that tells FastAPI this function handles HTTP GET requests to the root path.
  • def read_root(): — The function that executes when the endpoint is called.
  • return {<strong><code>message: Hello World} — FastAPI automatically converts this Python dictionary to a JSON response.

ASGI vs WSGI

Flask uses WSGI (Web Server Gateway Interface), which is synchronous and handles one request at a time. FastAPI uses ASGI (Asynchronous Server Gateway Interface), which supports async/await and can handle many concurrent connections efficiently.

Automatic API Documentation

One of FastAPI's killer features is automatic API documentation. Start your server and visit these URLs:

  • http://localhost:8000/docs — Swagger UI (interactive, you can test endpoints directly from your browser)
  • http://localhost:8000/redoc — ReDoc (alternative documentation layout with a different visual style)

Both are generated automatically from your code's type hints and docstrings. You do not need to write a single line of documentation code.

Python 3
@app.get("/users/{user_id}")
def get_user(user_id: int):
    """
    Get a user by their ID.

    - **user_id**: The ID of the user to retrieve
    """
    return {"user_id": user_id, "name": "John Doe"}
Try it locally: Add a docstring to your endpoint function. It will appear in the documentation page automatically at /docs.

Running with Uvicorn

FastAPI Architecture: ASGI Runtime & Framework Stack Uvicorn handles raw network sockets • Starlette manages HTTP routing • Pydantic handles validation CLIENT HTTP / WS Requests / Sockets UVICORN (ASGI) asyncio event loop uvloop C-speed Protocol Translation STARLETTE HTTP routing Middleware & CORS WebSockets base FASTAPI Pydantic V2 Auto OpenAPI Docs / Swagger

The command uvicorn main:app --reload deserves explanation:

  • main — The name of your Python file (main.py, without the .py extension).
  • app — The variable name of your FastAPI instance inside main.py.
  • --reload — Auto-restarts the server when you change code (use only in development, never in production).
Bash
# Basic run (no auto-reload)
uvicorn main:app

# Run with custom host and port
uvicorn main:app --host 0.0.0.0 --port 8080

# Run with reload for development
uvicorn main:app --reload
Never use --reload in production! The reload flag is a development tool that consumes extra resources and can cause security issues. It also does not scale well under load.

Environment Setup with Virtual Environments

It is best practice to create a virtual environment for each project to isolate dependencies and prevent version conflicts.

Bash
# Create virtual environment
python -m venv venv

# Activate on Windows
venv\Scripts\activate

# Activate on Mac/Linux
source venv/bin/activate

# Install packages inside the virtual environment
pip install fastapi uvicorn

# Save dependencies for later
pip freeze > requirements.txt

# Install from requirements file on another machine
pip install -r requirements.txt
Pro Tip: Always add venv/ to your .gitignore file. You never want to commit your virtual environment to version control.

Knowledge Check

Ready to test your understanding of 1. Introduction to FastAPI?

Back