Skip to content

How to use different middleware for different routes/path #1174

@philippegirard

Description

@philippegirard

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/path1 to allow origins of calls from myfrontend.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"}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions