-
-
Notifications
You must be signed in to change notification settings - Fork 9k
How to use different middleware for different routes/path #1174
Copy link
Copy link
Closed
Labels
Description
First 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/path1to allow origins of calls frommyfrontend.com - I want
myapi.com/path2to 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"}Reactions are currently unavailable