question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] How to use different middleware for different routes/path

See original GitHub issue

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"}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:11
  • Comments:21 (9 by maintainers)

github_iconTop GitHub Comments

69reactions
mreschkecommented, Feb 3, 2021

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…

60reactions
adriangbcommented, Jul 11, 2021

+1 for router and/or route level middleware

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found