Kurs Python · Moduł 6: Async i FastAPI
FastAPI - nowoczesne asynchroniczne API
W tej lekcji10
Witaj ponownie! Darwin tutaj z FastAPI - najnowocześniejszym frameworkiem do budowania API w Pythonie!
W poprzedniej lekcji nauczyłeś/aś się async/await. Teraz wykorzystamy tę wiedzę z FastAPI - frameworkiem, który jest 3-5× szybszy niż Flask, ma automatyczną walidację, i generu
je dokumentację automatycznie!
Analogia Safari: Flask to tradycyjna wycieczka safari - sprawdzona, niezawodna. FastAPI to safari na dronach - szybkie, nowoczesne, z GPS-em i automatycznym tracking
iem zwierząt!
Czym jest FastAPI?
FastAPI to nowoczesny, szybki framework do budowania API stworzony przez Sebastiána Ramíreza w 2018 roku.
Kluczowe cechy: Szybki - comparable z Node.js/Go (dzięki Starlette) Async native - pełne wsparcie dla async/await Type hints - wykorzystuje type annotations Automatyczna walidacja - Pydantic out-of-the-box Auto docs - Swagger UI + ReDoc automatycznie Modern Python - Python 3.7+ required
Instalacja FastAPI
pip install fastapi[all] # Wszystko (Uvicorn, Pydantic, etc.)
# Lub minimalnie:
pip install fastapi uvicorn[standard]Uvicorn = ASGI server (jak Gunicorn dla WSGI)
Hello World FastAPI
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello Safari!"}
# Uruchom: uvicorn main:app --reloadUruchom:
uvicorn main:app --reloadOutput:
INFO: Uvicorn running on http://127.0.0.1:8000
INFO: Application startup complete.Otwórz:
- http://localhost:8000/ → {"message": "Hello Safari!"}
- http://localhost:8000/docs → Automatyczna dokumentacja Swagger UI!
- http://localhost:8000/redoc → Alternatywna dokumentacja ReDoc
FastAPI vs Flask
| FastAPI | Flask |
|---|---|
| Async native | Sync (async możliwe, ale trudne) |
| Type hints wymagane | Optional |
| Automatyczna walidacja (Pydantic) | Ręczna (Flask-WTF) |
| Auto docs (Swagger/ReDoc) | Brak |
| 3-5× szybszy | Wolniejszy |
| Modern Python (3.7+) | Starsze wersje OK |
| API-first | Web apps + API |
Kiedy FastAPI? REST API, microservices, async I/O Kiedy Flask? Web apps z templates, mniejsze projekty
Podstawowe endpointy
from fastapi import FastAPI
app = FastAPI(title="Safari Database API", version="1.0.0")
# GET - pobierz dane
@app.get("/species")
async def list_species():
return [
{"id": 1, "name": "Lew", "population": 120},
{"id": 2, "name": "Słoń", "population": 450}
]
# GET z parametrem w path
@app.get("/species/{species_id}")
async def get_species(species_id: int):
return {"id": species_id, "name": "Lew", "population": 120}
# POST - dodaj dane
@app.post("/species")
async def create_species(name: str, population: int):
return {"id": 3, "name": name, "population": population, "status": "created"}
# PUT - aktualizuj
@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 - usuń
@app.delete("/species/{species_id}")
async def delete_species(species_id: int):
return {"id": species_id, "status": "deleted"}Testuj:
# GET
curl http://localhost:8000/species
# POST
curl -X POST "http://localhost:8000/species?name=Gepard&population=7100"Query parameters - automatyczna walidacja
FastAPI automatycznie parsuje query params i waliduje typy!
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 automatycznie:
# - parsuje ?skip=10&limit=5&habitat=savanna&endangered=true
# - konwertuje typy (str → int, str → bool)
# - waliduje (skip musi być int!)
return {
"skip": skip,
"limit": limit,
"habitat": habitat,
"endangered": endangered,
"results": ["Lew", "Słoń"]
}Testuj:
/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 automatycznie generuje błędy walidacji:
{
"detail": [
{
"loc": ["query", "skip"],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}Response models - strukturyzowane odpowiedzi
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="Lew",
scientific_name="Panthera leo",
population=120,
endangered=True
)Korzyści response_model:
- Automatyczna serializacja do JSON
- Walidacja output
- Dokumentacja automatycznie pokazuje strukturę
- Type safety
Pełne Safari API - przykład
# 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="Lew", scientific_name="Panthera leo", population=120, habitat="savanna"),
2: Species(id=2, name="Słoń", 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}Uruchom:
uvicorn main:app --reloadTestuj API:
# Lista
curl http://localhost:8000/species
# Konkretny gatunek
curl http://localhost:8000/species/1
# Dodaj
curl -X POST http://localhost:8000/species \
-H "Content-Type: application/json" \
-d '{"name":"Gepard","scientific_name":"Acinonyx jubatus","population":7100,"habitat":"savanna"}'
# Aktualizuj
curl -X PUT http://localhost:8000/species/1 \
-H "Content-Type: application/json" \
-d '{"name":"Lew","scientific_name":"Panthera leo","population":150,"habitat":"savanna"}'
# Usuń
curl -X DELETE http://localhost:8000/species/3Automatyczna dokumentacja
FastAPI automatycznie generuje interaktywną dokumentację!
Swagger UI: http://localhost:8000/docs
- Interaktywne testowanie API
- "Try it out" button dla każdego endpoint
- Automatyczne formularze
ReDoc: http://localhost:8000/redoc
- Czytelna dokumentacja
- Świetna dla developerów
OpenAPI JSON: http://localhost:8000/openapi.json
- Raw OpenAPI 3.0 schema
- Dla narzędzi zewnętrznych
Podsumowanie
W tej lekcji nauczyłeś/aś się:
- Czym jest FastAPI i po co go używać
- Instalacja FastAPI + Uvicorn
- Hello World i podstawowe endpointy
- GET, POST, PUT, DELETE
- Path parameters i query parameters
- Response models z Pydantic
- HTTPException dla błędów
- Automatyczna dokumentacja (Swagger/ReDoc)
- Pełne Safari Database API
Następna lekcja: Darwin pokaże Ci Pydantic v2 - potężny system walidacji danych z FastAPI!
Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Jak najlepiej opisać FastAPI?
2. Jak zainstalować FastAPI wraz z serwerem ASGI?
To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.
Zadania praktyczne w grze
- Układanie w poziomie
Jak utworzyć instancję aplikacji FastAPI?
- Układanie w pionie
Ułóż minimalną aplikację FastAPI:
- Klikanie w kolejności
Ułóż komendę uruchamiającą serwer uvicorn:
- Edytor kodu
Napisz async endpoint GET /species zwracający listę słowników z gatunkami.