[QUESTION] How to use different middleware for different routes/path
See original GitHub issueFirst check
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
Description
Is it possible to use different middleware for different routes/path?
Additional context
In my case my need comes from CORS. But, I am sure there is other cases than CORS requirements that someone would need different middlewares for different paths.
- I want
myapi.com/path1
to allow origins of calls frommyfrontend.com
- I want
myapi.com/path2
to allow origins of calls from anywhere (‘*’) since it is a public facing api.
I checked if it was possible to add a middleware at a router level and did not find any documentation about it.
Code example
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['myfrontend.com'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# I want /path1 to allow only calls from 'myfrontend.com'
@app.get("/path1")
async def path1():
return {"status": "alive"}
# I want /path2 to be a public facing api that can be accessed from anywhere ['*']
@app.get("/path2")
async def path2():
return {"status": "alive"}
Issue Analytics
- State:
- Created 3 years ago
- Reactions:11
- Comments:21 (9 by maintainers)
Top Results From Across the Web
Different middleware for resource route - laravel - Stack Overflow
You need to define each routes individually. Route::resource('/path', Controller::class);. Is similar to : Route::get('/path' ...
Read more >Using middleware - Express.js
Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the /user/:id...
Read more >FAQ: Middleware - Route-Level app.use() - Multiple Paths
This community-built FAQ covers the “Route-Level app.use() - Multiple Paths” exercise from the lesson “Middleware”. Paths and Courses This ...
Read more >Express/Node introduction - Learn web development | MDN
Write handlers for requests with different HTTP verbs at different URL paths (routes). Integrate with "view" rendering engines in order to ...
Read more >Routing in ASP.NET Core - Microsoft Learn
The UseRouting middleware uses the SetEndpoint method to attach the endpoint to the current context. It's possible to replace the UseRouting ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This is a fine approach for some use cases. But having route based middleware is still a requirement for many projects I work on. I understand starlette itself cannot yet do this, so perhaps this is the wrong github page to bring it up. I will see what Tom Cristie thinks about adding route based middleware to starlette. Then perhaps fastapi can impliment it in the route decorators
router.get('/path', middleware=['abc', 'xyz']
etc…+1 for router and/or route level middleware