new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

FastAPI · Advanced · all subjects

advanced-dependencies/middleware

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

Using ASGI middlewares with FastAPI

FastAPI is based on Starlette and implements the ASGI specification, allowing any ASGI middleware to be used. ASGI middlewares are classes that expect an ASGI app as the first argument. FastAPI provides the `app.add_middleware()` method to add middlewares, which is preferred over direct instantiation because it ensures internal middlewares handle server errors and custom exception handlers work properly. The `app.add_middleware()` method receives a middleware class as the first argument and any additional arguments to pass to the middleware.

HTTPSRedirectMiddleware enforces secure schemes

HTTPSRedirectMiddleware enforces that all incoming requests must be either https or wss. Any incoming request to http or ws will be redirected to the secure scheme instead.

TrustedHostMiddleware validates Host header

TrustedHostMiddleware enforces that all incoming requests have a correctly set Host header to guard against HTTP Host Header attacks. It supports the following arguments: allowed_hosts (a list of domain names that should be allowed as hostnames, with wildcard domains such as *.example.com supported; use allowed_hosts=['*'] or omit the middleware to allow any hostname), and www_redirect (if set to True, requests to non-www versions of allowed hosts will be redirected to their www counterparts; defaults to True). If an incoming request does not validate correctly, a 400 response will be sent.

GZipMiddleware compression settings

GZipMiddleware handles GZip responses for any request that includes 'gzip' in the Accept-Encoding header. The middleware handles both standard and streaming responses. Supported arguments are: minimum_size (do not GZip responses smaller than this minimum size in bytes; defaults to 500), and compresslevel (integer ranging from 1 to 9 used during GZip compression; defaults to 9; lower values result in faster compression but larger file sizes, while higher values result in slower compression but smaller file sizes).

ASGI middleware compatibility

A middleware does not have to be made specifically for FastAPI or Starlette to work, as long as it follows the ASGI specification. This allows use of third-party ASGI middlewares from various sources.

Access Request object directly in path operations

To access the Request object directly in a path operation function, declare a parameter with the type annotation Request. FastAPI will recognize this and pass the Request object to that parameter. This allows you to access low-level request details like the client's IP address or host.

Data from Request object bypasses validation and documentation

When you get data from the Request object directly (for example, reading the body), it will not be validated, converted, or documented by FastAPI in OpenAPI documentation. However, other parameters declared normally will still be validated, converted, and annotated as usual.

Request can coexist with other path parameters

You can declare a Request parameter alongside other path parameters in a path operation function. The path parameters will be extracted, validated, converted to their specified types, and annotated with OpenAPI, while the Request parameter provides direct access to the request object.

Request can be imported from fastapi or starlette

The Request class can be imported from either fastapi or starlette.requests. FastAPI provides it directly as a convenience, but it comes from Starlette underneath.

FastAPI is built on top of Starlette

FastAPI uses Starlette underneath with additional tools and validation layers on top. You can use Starlette's Request object directly when needed in FastAPI path operations.

Give your agent this brain