new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

FastAPI · Tutorial · all subjects

middleware & headers

14 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Add custom headers to responses

You can add custom headers to responses by passing a headers dictionary parameter when creating a Response object or its subclasses. The headers parameter takes a dict of strings.

Add ASGI middleware using app.add_middleware()

To add ASGI middleware to a FastAPI application, use app.add_middleware() rather than directly wrapping the app. This method takes a middleware class as the first argument, followed by all arguments to pass to that middleware. For example: app.add_middleware(UnicornMiddleware, some_config="rainbow"). This approach ensures internal middlewares for handling server errors and custom exception handlers work correctly.

HTTPSRedirectMiddleware enforces HTTPS/WSS

HTTPSRedirectMiddleware forces all incoming requests to use either https or wss protocols. Incoming requests using http or ws are redirected to the secure schema instead.

TrustedHostMiddleware validates Host header

TrustedHostMiddleware enforces that all incoming requests have a correctly set Host header to protect against HTTP Host header attacks. It supports allowed_hosts (a list of domain names or wildcards like *.example.com), and www_redirect (defaults to True, redirects non-www versions to www versions). When validation fails, a 400 response is sent.

TrustedHostMiddleware allowed_hosts parameter

The allowed_hosts parameter accepts a list of domain names. Wildcard domains like *.example.com are supported for matching subdomains. To allow any hostname, use allowed_hosts=["*"] or omit the middleware entirely.

TrustedHostMiddleware www_redirect parameter

The www_redirect parameter of TrustedHostMiddleware controls whether requests to non-www versions of allowed hosts are redirected to their www equivalents. The default value is True.

GZipMiddleware compresses responses

GZipMiddleware handles GZip compression for all requests that contain "gzip" in the Accept-Encoding header. It processes both standard and streaming responses.

GZipMiddleware minimum_size parameter

The minimum_size parameter of GZipMiddleware specifies the minimum size in bytes below which responses will not be compressed. The default value is 500 bytes.

GZipMiddleware compresslevel parameter

The compresslevel parameter of GZipMiddleware is an integer between 1 and 9, used during GZip compression. The default value is 9. Lower values result in faster compression but larger file sizes, while higher values result in slower compression but smaller file sizes.

ASGI middleware requirement

A middleware does not need to be specifically designed for FastAPI or Starlette to work, as long as it conforms to the ASGI specification. ASGI middleware is typically a class that expects an ASGI application as its first argument.

Use Response parameter to add custom headers

You can declare a parameter of type `Response` in your path operation function to add custom headers. The Response parameter is temporary and used by FastAPI to extract headers, cookies, and status codes, which are then added to the final response containing your returned value. If a `response_model` is declared, it still filters and converts the returned object.

Add headers when returning Response directly

You can add headers when returning a Response directly by passing headers as an additional parameter when creating the Response object.

Custom proprietary headers use X- prefix

Custom proprietary headers are added with the prefix `X-` according to HTTP header standards.

Import Response from FastAPI or Starlette

You can import Response from either `fastapi.responses` or `starlette.responses`. FastAPI provides the same `starlette.responses` via `fastapi.responses` as a convenience, and also provides Response directly under `fastapi.Response`.

Give your agent this brain