I am new to FastAPI . I have worked with multiple web frameworks in other languages and found the common pattern of middlewares for various purposes. e.g. If I have an API route that I want to authenticate then I would use a middleware that does the authentication. If I want to augment the incoming request I would use a middleware. FastAPI does have middlewares (A very small section in docs) but also has dependencies. I was looking to authenticate my API routes and started looking for examples and all the examples I find use dependencies. What (dependency or middleware) would be recommended way to authenticate an API route and why?
The way I see it:
Dependency
: you use it to run code for preparing variables, authentication and so on.Middleware
: you need to check some stuff first and reject or forward the request to your logic.The middleware can be seen as a superset of a Dependency
, as the latter is a sort of middleware that returns a value which can be used in the request. Though, in the middleware, you can log your requests or cache the results and access the response of the request (or even forward the request, call some other API and so on).
TL;DR
A Dependency
is a sort of common logic that is required before processing the request (e.g. I need the user id associated to this token), while a Middleware
can do that, it can also access the response to that request. Dependencies are the preferred way to create a middleware for authentication.