FastAPI is momenteel mijn favoriete framework voor het bouwen van API’s. Snel, modern en met automatische documentatie.
Project opzetten
#1
2
3
4
| mkdir mijn-api && cd mijn-api
python -m venv .venv
source .venv/bin/activate
pip install fastapi uvicorn sqlalchemy
|
Basis applicatie
# 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(title="Mijn API", version="1.0.0")
class Item(BaseModel):
naam: str
prijs: float
voorraad: int = 0
items_db: dict[int, Item] = {}
@app.get("/items")
def lijst_items():
return items_db
@app.post("/items/{item_id}", status_code=201)
def maak_item(item_id: int, item: Item):
if item_id in items_db:
raise HTTPException(status_code=409, detail="Item bestaat al")
items_db[item_id] = item
return item
@app.get("/items/{item_id}")
def haal_item(item_id: int):
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item niet gevonden")
return items_db[item_id]
|
Starten
#1
| uvicorn main:app --reload --host 0.0.0.0 --port 8000
|
Open http://localhost:8000/docs voor de automatische Swagger-documentatie.
Database met SQLAlchemy
# 1
2
3
4
5
6
7
8
9
10
11
12
13
| from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "postgresql://user:pass@localhost:5432/mydb"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
|
Docker deployment
#1
2
3
4
5
6
| FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
FastAPI + Uvicorn + Docker = snel in productie.