Learn / Frameworks / FastAPI / Middleware, CORS and Trusted Hosts

FastAPI · Lesson 6 of 15

Middleware, CORS and Trusted Hosts

Add CORS, HTTPS redirects and request-id middleware without blocking the event loop.

  • Intermediate
  • 14 min read
  • 3 objectives

Before this lessonLesson 5: Async, Databases and Deployment

What you will learn

  • Enable CORS
  • Add trusted hosts
  • Write async middleware

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Middleware wraps every request. FastAPI (Starlette) ships CORS, gzip, HTTPS redirect and trusted-host helpers; you can add your own for request ids and timing.

CORS

A browser on https://app.example.com cannot call https://api.example.com unless the API sends the right headers. Be explicit: ["*"] plus cookies is invalid and unsafe.

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)

Trusted hosts and HTTPS

from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app.add_middleware(HTTPSRedirectMiddleware)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.example.com", "*.example.com"])

Custom middleware

import time, uuid
from starlette.middleware.base import BaseHTTPMiddleware

class RequestIdMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        rid = request.headers.get("X-Request-Id", str(uuid.uuid4()))
        start = time.perf_counter()
        response = await call_next(request)
        response.headers["X-Request-Id"] = rid
        response.headers["X-Process-Ms"] = f"{(time.perf_counter() - start) * 1000:.1f}"
        return response

app.add_middleware(RequestIdMiddleware)
Up next · Lesson 7OAuth2 and JWT AuthenticationPassword flow, hashed passwords, JWT access tokens and a get_current_user dependency.