Neden FastAPI?
FastAPI, Python dünyasında hızla yükselen, modern, hızlı (high-performance) web API framework'ü. Starlette ve Pydantic üzerine kurulu, otomatik API dokümantasyonu sunuyor.
FastAPI vs Diğerleri
| Özellik | FastAPI | Flask | Django REST |
|---|---|---|---|
| Performans | Çok Yüksek | Orta | Orta |
| Type Hints | Native | Opsiyonel | Yok |
| Async Support | Native | Extension | Limited |
| Auto Docs | Swagger/ReDoc | Extension | Extension |
Örnek API Endpoint
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class Product(BaseModel):
name: str
price: float
description: Optional[str] = None
tax: Optional[float] = None
@app.post("/products/", response_model=Product)
async def create_product(product: Product):
# Automatic validation with Pydantic
return product
@app.get("/products/{product_id}")
async def read_product(product_id: int, q: Optional[str] = None):
if product_id < 1:
raise HTTPException(status_code=404, detail="Product not found")
return {"product_id": product_id, "q": q}
Authentication & Security
- OAuth2 with JWT tokens
- API key authentication
- CORS middleware
- Rate limiting
- Request validation
Best Practices
- Dependency injection kullanımı
- Background tasks için Celery entegrasyonu
- SQLAlchemy ile async database operations
- Alembic ile database migrations
- pytest ile comprehensive testing