Advertisement
⚡ Frameworks

FastAPI Tutorial – Modern Python REST API Framework

FastAPI is the fastest growing Python web framework — high performance (comparable to Node.js and Go), automatic data validation with Pydantic, auto-generated OpenAPI (Swagger) documentation, and async support built-in. It is the top choice for building modern REST APIs in Python.

⏱️ 30 min read🎯 Advanced📅 Updated 2026

Installation and First App

Install FastAPI and uvicorn (ASGI server) and run your first API in minutes.

Python
# pip install fastapi uvicorn

# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def root():
    return {"message": "Hello from FastAPI!"}

@app.get("/items/{item_id}")
def get_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "query": q}

# Run:
# uvicorn main:app --reload
# Visit: http://127.0.0.1:8000/docs  ← Auto Swagger UI!
▶ Output
{"message": "Hello from FastAPI!"} {"item_id": 42, "query": null}

Pydantic Models – Request/Response Validation

Use Pydantic models to define and validate request bodies automatically.

Python
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
from typing import Optional

app = FastAPI()

class User(BaseModel):
    name: str
    email: str
    age: int
    bio: Optional[str] = None

@app.post("/users/", response_model=User)
def create_user(user: User):
    # user is already validated and typed
    return user

# FastAPI auto-validates: wrong type = 422 error
# POST /users/ with {"name":"Alice","email":"a@b.com","age":30}
▶ Output
{"name":"Alice","email":"a@b.com","age":30,"bio":null}

Dependency Injection

FastAPI's dependency injection system handles auth, DB connections, and shared logic.

Python
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBearer

app = FastAPI()
security = HTTPBearer()

def get_current_user(token = Depends(security)):
    if token.credentials != "secret-token":
        raise HTTPException(status_code=401, detail="Invalid")
    return {"user": "alice"}

@app.get("/protected")
def protected_route(user = Depends(get_current_user)):
    return {"message": f"Welcome {user['user']}"}
Advertisement

Async Support

FastAPI supports both sync and async endpoints natively.

Python
import asyncio
from fastapi import FastAPI
import httpx

app = FastAPI()

@app.get("/async-data")
async def get_data():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://api.github.com")
    return response.json()
💡
Tip

Use async functions for I/O-bound operations (database queries, HTTP calls). FastAPI handles the event loop automatically.

FastAPI: Modern APIs With Automatic Validation and Docs

FastAPI is a modern framework built for APIs. Its standout trick: it uses Python type hints to automatically validate requests, serialize responses, and generate interactive API documentation — features you'd hand-code elsewhere.

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class Item(BaseModel):          # the type hints ARE the validation
    name: str
    price: float

@app.post("/items")
async def create(item: Item):   # FastAPI validates the JSON against Item
    return {"total": item.price * 1.1}
From type hints, you get
request validation (bad JSON → automatic 422 error)
response serialization
interactive docs at /docs (Swagger UI)
editor autocomplete on request data

Why it took off: declare a pydantic model with typed fields, and FastAPI enforces it — send malformed data and the client gets a clear 422 error, no manual checking. Those same models generate live, browsable API docs automatically, so your documentation can never drift from the code. Async-native: built on ASGI, it handles async def endpoints for high-concurrency I/O (many simultaneous requests) out of the box. Choose FastAPI for new JSON APIs and microservices where validation, docs, and performance matter; it pairs the speed of Node-style async with Python's ecosystem.

🏋️ Practical Exercise

Build a FastAPI service:

  1. Create an app and a GET / route returning a JSON message.
  2. Add a path parameter route like GET /items/{item_id} with a type hint.
  3. Define a Pydantic model and accept it in a POST route.
  4. Run with uvicorn and open the auto-generated docs at /docs.

🔥 Challenge Exercise

Build a small CRUD API for “tasks” using FastAPI and an in-memory list: routes to create (with a Pydantic model for validation), list, retrieve by id, and delete tasks. Return proper status codes and raise HTTPException for missing ids. Add a dependency that simulates an API-key check on protected routes. Bonus: make one route async and explain when async helps here.

📋 Summary

  • FastAPI is a modern, high-performance Python web framework for building APIs.
  • It uses standard type hints to validate, serialize, and document requests and responses.
  • Pydantic models define request/response schemas and validate data automatically.
  • Dependency injection cleanly shares logic like auth and database sessions across routes.
  • Interactive Swagger/ReDoc docs are generated automatically from your code.
  • It supports async natively, making it well suited to high-concurrency I/O workloads.

Interview Questions on FastAPI

  • What is FastAPI and what is it known for?
  • How does FastAPI use Python type hints?
  • What is Pydantic and how does FastAPI use it?
  • What is dependency injection in FastAPI?
  • How does FastAPI generate interactive API documentation automatically?
  • When should a route be async in FastAPI?
  • How does FastAPI compare to Flask and Django REST Framework?

FAQ

Why is FastAPI considered fast? +

It is built on Starlette and the ASGI standard with full async support, so it handles many concurrent I/O-bound requests efficiently. Combined with Pydantic’s compiled validation, its performance rivals Node.js and Go for typical API workloads.

What role does Pydantic play? +

Pydantic models declare the expected shape of request and response data using type hints. FastAPI uses them to validate incoming JSON, convert types, produce clear errors, and document the schema automatically.

What is dependency injection in FastAPI? +

It is a system for declaring reusable pieces of logic (database sessions, authentication, settings) as functions that FastAPI supplies to your routes automatically via Depends(), keeping routes clean and testable.

When should I make a route async? +

Use async def when the route awaits I/O — async database drivers, external HTTP calls — so the server can handle other requests during the wait. For purely CPU-bound or simple synchronous work, a normal def route is fine.