Skip to content

Introduction to FastAPI

What is an API?

An API (Application Programming Interface) is a way for two programs to talk to each other.

When you open Swiggy and search for "pizza":

  1. Your phone (the client) sends a request: "Show me pizza near me."
  2. A backend server runs that request: searches the database, finds restaurants.
  3. The server sends back the results.

The thing in the middle that defines the rules for this conversation is an API.

API endpoint = a URL the client can hit to ask for something. Example: https://api.example.com/restaurants?cuisine=pizza

What is FastAPI?

FastAPI is a Python framework for building APIs. It lets you write a Python function and expose it as a web endpoint.

# main.py — a complete FastAPI app
from fastapi import FastAPI

app = FastAPI()

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

Run it (we'll cover this in detail next chapter):

pip install fastapi uvicorn
uvicorn main:app --reload

Open http://127.0.0.1:8000 — you'll see {"message": "Hello, World!"}.

Why FastAPI?

Compared to older frameworks (Flask, Django REST):

Feature FastAPI Flask Django REST
Speed Very fast Medium Slower
Async support Built-in Bolt-on Bolt-on
Auto-generates docs Yes (Swagger + ReDoc) No No
Validates input automatically Yes (via Pydantic) Manual Manual (serializers)
Type-hint driven Yes No No
Learning curve Easy Easy Medium

The big three reasons people pick FastAPI:

  1. Auto-generated interactive docs — go to /docs and try every endpoint live in your browser.
  2. Type hints power everything — write def get_user(user_id: int) and FastAPI validates, parses, and documents that automatically.
  3. Async-native — handles thousands of concurrent requests on a single process.

How FastAPI works — the request lifecycle

When a request comes in, here's what happens:

1. Client sends HTTP request to your server
2. uvicorn (the web server) receives the bytes
3. uvicorn passes the request to FastAPI
4. FastAPI looks at the URL & matches it to a route
5. FastAPI reads type hints — parses query/path/body
6. FastAPI runs validation (via Pydantic)
7. Your function is called with parsed args
8. Whatever you return is converted to JSON
9. FastAPI builds the HTTP response
10. uvicorn sends it back to the client

So you only write step 7 — the function. FastAPI + uvicorn handle 1-6 and 8-10 automatically.

Sync vs async — what's the difference?

Synchronous (Flask-style): one request at a time per worker. Slow request blocks others.

Asynchronous (FastAPI default): one worker can handle many requests concurrently. While one is waiting for the database, the worker handles another.

Sync:
  Request 1 ──[5s DB query]──> Response 1
  Request 2 ──────waiting──────[5s DB query]──> Response 2  (10s total!)

Async:
  Request 1 ──[5s DB query──────]──> Response 1
  Request 2     ──[5s DB query──]──> Response 2  (5s total, mostly!)

That's why FastAPI is dramatically faster for I/O-heavy APIs.

What you'll learn in this tutorial

# Chapter
2 Install + first app + uvicorn
3 Path and query parameters
4 Request body & Pydantic models
5 Response models, status codes
6 Error handling with HTTPException
7 A complete CRUD example — patient records
8 Pydantic deep dive — validators, fields
9 Async/await — when and how
10 Dependency injection
11 Middleware & CORS
12 Authentication — OAuth2 + JWT
13 Deploy an ML model with FastAPI
14 Docker + cloud deployment

Prerequisites

  • Basic Python — variables, functions, classes, dictionaries.
  • Ability to install Python packages with pip.
  • A code editor (VS Code recommended).
  • A terminal.

What's next

Practice

What does this print?

Expected: True

# FastAPI uses Python type hints to validate request data automatically
uses_type_hints = True
print(uses_type_hints)

Use FastAPI (not Flask) when you want auto-generated OpenAPI docs

Expected: True

framework = "Flask"     # bug: Flask has no built-in OpenAPI generation
is_modern_choice = framework == "FastAPI"
print(not is_modern_choice)

Quiz — Quick check

What you remember

Q1. What is FastAPI built on top of?

  • Starlette (ASGI framework) + Pydantic (data validation)
  • Django
  • Flask
  • Express.js

Why: Starlette provides the async web primitives; Pydantic handles type-driven validation. FastAPI combines them with OpenAPI auto-generation.

Q2. What's the killer feature over Flask?

  • Type hints automatically produce request validation AND OpenAPI/Swagger docs
  • Faster execution
  • Built-in ORM
  • No async needed

Why: Annotate args with types → FastAPI validates incoming data against them, returns 422 on mismatch, and generates Swagger UI at /docs. Zero schema definition boilerplate.

Q3. Recommended install for development?

  • pip install "fastapi[standard]" (bundles uvicorn and useful extras)
  • pip install fastapi-server
  • apt install fastapi
  • No install needed

Why: The [standard] extras give you uvicorn, a CLI, and common middlewares. For minimal production deps, install fastapi and uvicorn[standard] separately.

Common doubts

Is FastAPI production-ready?

Yes — used at scale by Microsoft, Uber, Netflix and many startups. Performance is on par with Node.js/Go for I/O-bound APIs. Excellent docs, active maintenance, large community.

FastAPI or Django for a new project?

FastAPI for APIs, microservices, async-heavy work. Django for full-stack apps with HTML rendering, admin panels, ORM-heavy CRUD. Many teams use both: Django for the monolith, FastAPI for ML/microservices.

Can I serve a web frontend with FastAPI?

Possible (FileResponse, Jinja2), but not its strength. Better: deploy SPA frontend separately (Vercel/Netlify), have FastAPI serve only the API. Use CORS middleware to allow the SPA to call your API.

Installation & First App