Python course Β· Module 6: Async and FastAPI
FastAPI - modern asynchronous API
In this lesson10
Welcome back! Darwin here with FastAPI - the most modern framework for building APIs in Python!
In the previous lesson you learned async/await. Now we'll use that knowledge with FastAPI - a framework that is 3-5x faster than Flask, has automatic validation, and generates documentation automatically!
Safari Analogy: Flask is a traditional safari tour - tried and true, reliable. FastAPI is a safari with drones - fast, modern, with GPS and automatic animal tracking!
What is FastAPI?
FastAPI is a modern, fast framework for building APIs created by Sebastian Ramirez in 2018.
Key features: Fast - comparable to Node.js/Go (thanks to Starlette) Async native - full support for async/await Type hints - uses type annotations Automatic validation - Pydantic out-of-the-box Auto docs - Swagger UI + ReDoc automatically Modern Python - Python 3.7+ required
Installing FastAPI
pip install fastapi[all] # Everything (Uvicorn, Pydantic, etc.)
# Or minimally:
pip install fastapi uvicorn[standard]Uvicorn = ASGI server (like Gunicorn for WSGI)
Hello World FastAPI
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello Safari!"}
# Run: uvicorn main:app --reloadRun:
uvicorn main:app --reloadOutput:
INFO: Uvicorn running on http://127.0.0.1:8000
INFO: Application startup complete.Open:
- http://localhost:8000/ β {"message": "Hello Safari!"}
- http://localhost:8000/docs β Automatic Swagger UI documentation!
- http://localhost:8000/redoc β Alternative ReDoc documentation
FastAPI vs Flask
| FastAPI | Flask |
|---|---|
| Async native | Sync (async possible, but difficult) |
| Type hints required | Optional |
| Automatic validation (Pydantic) | Manual (Flask-WTF) |
| Auto docs (Swagger/ReDoc) | None |
| 3-5x faster | Slower |
| Modern Python (3.7+) | Older versions OK |
| API-first | Web apps + API |
When FastAPI? REST API, microservices, async I/O When Flask? Web apps with templates, smaller projects
Basic endpoints
from fastapi import FastAPI
app = FastAPI(title="Safari Database API", version="1.0.0")
# GET - fetch data
@app.get("/species")
async def list_species():
return [
{"id": 1, "name": "Lion", "population": 120},
{"id": 2, "name": "Elephant", "population": 450}
]
# GET with path parameter
@app.get("/species/{species_id}")
async def get_species(species_id: int):
return {"id": species_id, "name": "Lion", "population": 120}
# POST - add data
@app.post("/species")
async def create_species(name: str, population: int):
return {"id": 3, "name": name, "population": population, "status": "created"}
# PUT - update
@app.put("/species/{species_id}")
async def update_species(species_id: int, name: str, population: int):
return {"id": species_id, "name": name, "population": population}
# DELETE - remove
@app.delete("/species/{species_id}")
async def delete_species(species_id: int):
return {"id": species_id, "status": "deleted"}Test:
# GET
curl http://localhost:8000/species
# POST
curl -X POST "http://localhost:8000/species?name=Cheetah&population=7100"Query parameters - automatic validation
FastAPI automatically parses query params and validates types!
from fastapi import FastAPI
app = FastAPI()
@app.get("/species")
async def list_species(
skip: int = 0,
limit: int = 10,
habitat: str | None = None,
endangered: bool = False
):
# FastAPI automatically:
# - parses ?skip=10&limit=5&habitat=savanna&endangered=true
# - converts types (str β int, str β bool)
# - validates (skip must be int!)
return {
"skip": skip,
"limit": limit,
"habitat": habitat,
"endangered": endangered,
"results": ["Lion", "Elephant"]
}Test:
/species β skip=0, limit=10, habitat=None, endangered=False
/species?skip=20&limit=5 β skip=20, limit=5
/species?habitat=savanna&endangered=1 β habitat="savanna", endangered=True
/species?skip=abc β ERROR: validation error!FastAPI automatically generates validation errors:
{
"detail": [
{
"loc": ["query", "skip"],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}Response models - structured responses
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Species(BaseModel):
id: int
name: str
scientific_name: str
population: int
endangered: bool = False
@app.get("/species/{species_id}", response_model=Species)
async def get_species(species_id: int):
return Species(
id=species_id,
name="Lion",
scientific_name="Panthera leo",
population=120,
endangered=True
)Benefits of response_model:
- Automatic serialization to JSON
- Output validation
- Documentation automatically shows the structure
- Type safety
Full Safari API - example
# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import List
app = FastAPI(
title="Safari Database API",
description="API for managing African wildlife species",
version="1.0.0"
)
# Models
class SpeciesBase(BaseModel):
name: str = Field(..., min_length=2, max_length=100)
scientific_name: str
population: int = Field(..., ge=0)
habitat: str
class SpeciesCreate(SpeciesBase):
pass
class Species(SpeciesBase):
id: int
class Config:
from_attributes = True
# In-memory database
species_db: dict[int, Species] = {
1: Species(id=1, name="Lion", scientific_name="Panthera leo", population=120, habitat="savanna"),
2: Species(id=2, name="Elephant", scientific_name="Loxodonta africana", population=450, habitat="savanna"),
}
next_id = 3
# Endpoints
@app.get("/")
async def root():
return {"message": "Safari Database API", "version": "1.0.0"}
@app.get("/species", response_model=List[Species])
async def list_species(skip: int = 0, limit: int = 10, habitat: str | None = None):
"""List all species with pagination"""
results = list(species_db.values())
if habitat:
results = [s for s in results if s.habitat == habitat]
return results[skip : skip + limit]
@app.get("/species/{species_id}", response_model=Species)
async def get_species(species_id: int):
"""Get specific species by ID"""
if species_id not in species_db:
raise HTTPException(status_code=404, detail=f"Species {species_id} not found")
return species_db[species_id]
@app.post("/species", response_model=Species, status_code=201)
async def create_species(species: SpeciesCreate):
"""Create new species"""
global next_id
new_species = Species(id=next_id, **species.dict())
species_db[next_id] = new_species
next_id += 1
return new_species
@app.put("/species/{species_id}", response_model=Species)
async def update_species(species_id: int, species: SpeciesCreate):
"""Update existing species"""
if species_id not in species_db:
raise HTTPException(status_code=404, detail="Species not found")
updated = Species(id=species_id, **species.dict())
species_db[species_id] = updated
return updated
@app.delete("/species/{species_id}")
async def delete_species(species_id: int):
"""Delete species"""
if species_id not in species_db:
raise HTTPException(status_code=404, detail="Species not found")
del species_db[species_id]
return {"status": "deleted", "id": species_id}Run:
uvicorn main:app --reloadTest the API:
# List
curl http://localhost:8000/species
# Specific species
curl http://localhost:8000/species/1
# Add
curl -X POST http://localhost:8000/species \
-H "Content-Type: application/json" \
-d '{"name":"Cheetah","scientific_name":"Acinonyx jubatus","population":7100,"habitat":"savanna"}'
# Update
curl -X PUT http://localhost:8000/species/1 \
-H "Content-Type: application/json" \
-d '{"name":"Lion","scientific_name":"Panthera leo","population":150,"habitat":"savanna"}'
# Delete
curl -X DELETE http://localhost:8000/species/3Automatic documentation
FastAPI automatically generates interactive documentation!
Swagger UI: http://localhost:8000/docs
- Interactive API testing
- "Try it out" button for each endpoint
- Automatic forms
ReDoc: http://localhost:8000/redoc
- Readable documentation
- Great for developers
OpenAPI JSON: http://localhost:8000/openapi.json
- Raw OpenAPI 3.0 schema
- For external tools
Summary
In this lesson you learned:
- What FastAPI is and why to use it
- Installing FastAPI + Uvicorn
- Hello World and basic endpoints
- GET, POST, PUT, DELETE
- Path parameters and query parameters
- Response models with Pydantic
- HTTPException for errors
- Automatic documentation (Swagger/ReDoc)
- Full Safari Database API
Next lesson: Darwin will show you Pydantic v2 - a powerful data validation system with FastAPI!
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How would you best describe FastAPI?
2. How do you install FastAPI along with an ASGI server?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
How do you create a FastAPI application instance?
- Vertical ordering
Arrange a minimal FastAPI application:
- Click in order
Arrange the command to start the uvicorn server:
- Code editor
Write an async GET /species endpoint that returns a list of dictionaries with species.