📝 Fastapi

Middleware and CORS in FastAPI

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
89
🌳
Level
Advanced

Allows browser clients to make requests to an API from a different domain.

CORS (Cross-Origin Resource Sharing)

Allows browser clients to make requests to an API from a different domain.

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "https://myapp.com"],
    allow_credentials=True,
    allow_methods=["*"],      # GET, POST, PUT, DELETE, ...
    allow_headers=["*"],
)

For development (allow everything)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

Custom middleware

import time
from fastapi import Request

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

Request logging

import logging

logger = logging.getLogger(__name__)

@app.middleware("http")
async def log_requests(request: Request, call_next):
    logger.info(f"→ {request.method} {request.url}")
    response = await call_next(request)
    logger.info(f"← {response.status_code}")
    return response

Authentication via middleware

from fastapi.responses import JSONResponse

@app.middleware("http")
async def auth_middleware(request: Request, call_next):
    if request.url.path.startswith("/api/private"):
        token = request.headers.get("Authorization")
        if not token or not verify_token(token):
            return JSONResponse({"detail": "Unauthorized"}, status_code=401)
    return await call_next(request)

BaseHTTPMiddleware (class-based)

from starlette.middleware.base import BaseHTTPMiddleware

class RateLimitMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        if is_rate_limited(request.client.host):
            return JSONResponse({"detail": "Too many requests"}, status_code=429)
        return await call_next(request)

app.add_middleware(RateLimitMiddleware)

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

HTTPException in FastAPI

Охватываемые темы: Basic Usage, Status Codes, Error Details, Custom Headers.

📅 30.06.2026 👁️ 91
📝

Dependency Injection in FastAPI

Depends — FastAPI's dependency injection system for reusing code across endpoints.

📅 30.06.2026 👁️ 85
📝

Testing FastAPI with pytest

Охватываемые темы: Installation, TestClient (synchronous), Test database, Tests with fixtures.

📅 30.06.2026 👁️ 95

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!