| marp | true | ||
|---|---|---|---|
| author | Margit ANTAL | ||
| theme | gaia | ||
| class |
|
||
| paginate | true |
- FastAPI project structure
- Creating GET API endpoints
- Path and query parameters
- Pydantic models
- Creating POST API endpoints
- Standard logging
- High performance, built on Starlette and Pydantic
- Automatic data validation and type checking
- Automatic API docs (Swagger & Redoc)
- First-class support for
asyncandawait - FastAPI = Starlette (web) + Pydantic (data)
from pydantic import BaseModel, ValidationError
class User(BaseModel):
name: str
age: int
email: str | None = None
try:
u = User(name="Alice", age="34", email="alice@example.com")
print(u)
except ValidationError as e:
print(e)Loading configuration from JSON file (config.json):
{
"host": "localhost",
"port": 8080,
"debug": true
}
from pydantic import BaseModel
import json
class Config(BaseModel):
host: str
port: int
debug: bool
with open("config.json") as f:
data = json.load(f)
config = Config(**data)
print(config.port)Common structure:
main.py– entry pointrouters/– modular routesmodels/– Pydantic or DB modelsservices/– business logicconfig.py– env variables, settings
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI"}pip install fastapi uvicornuvicorn main:app --reload--reloadenables auto-reload on file changes
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
in_stock: bool = Trueitems: list = list(
Item(
name="Sample Item " + str(i+1),
price=(i+1) * 10.0,
in_stock=True)
for i in range(10))@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}curl http://localhost:8000/items/2
# → {"item_id": 2}
curl http://localhost:8000/items
# → 404 Not Found@app.get("/items/")
def read_item(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}curl http://localhost:8000/items/
# → {"skip": 0, "limit": 10}curl 'http://localhost:8000/items/?skip=5&limit=3'
# → {"skip": 5, "limit": 3}
curl 'http://localhost:8000/items/?skip=5'
# → {"skip": 5, "limit": 10}
curl 'http://localhost:8000/items/?limit=3'
# → {"skip": 0, "limit": 3}| Path Parameters | Query Parameters |
|---|---|
| Part of the URL | Appended after ? |
| Required | Optional (default values) |
| Used to identify resource | Used for filtering, pagination |
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
in_stock: bool = Trueitems = list()
@app.post("/items/")
def create_item(item: Item):
items.append(item)
return {"item_name": item.name, "price": item.price}- Example:
curl -X POST "http://localhost:8000/items/" \
-H "Content-Type: application/json" \
-d '{"name": "Book", "price": 12.99}'import logging
from fastapi import FastAPI
app = FastAPI()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("myapp")
@app.get("/")
def read_root():
logger.info("Root endpoint was called")
return {"Hello": "World"}FastAPI auto-generates API docs:
-
Swagger UI: http://127.0.0.1:8000/docs
-
Redoc: http://127.0.0.1:8000/redoc
Link to homework Section: Practical Exercises: Item Management API
- FastAPI project structure
- GET endpoints
- Path parameters
- Query parameters
- Pydantic request/response models
- POST endpoints
- OpenAPI/Swagger documentation