DEV Community

Cover image for How to create Middlewares with FastAPI
Nelson Hernández
Nelson Hernández

Posted on • Edited on

9 3

How to create Middlewares with FastAPI

¿how do i add custom middleware?

from fastapi import FastAPI, Request
from starlette.responses import JSONResponse, Response

app = FastAPI()

@app.middleware("http")
async def verify_user_agent(request: Request, call_next):
    if request.headers['User-Agent'].find("Mobile") == -1:
        response = await call_next(request)
        return response
    else:
        return JSONResponse(content={
            "message": "we do not allow mobiles"
        }, status_code=401)


@app.get('/')
def index(request: Request, response: Response):
    return {'message': 'ok'}
Enter fullscreen mode Exit fullscreen mode

Default middlewares in FastAPI

¿How to add CORS with FastAPI ?

from fastapi import FastAPI, Request
from starlette.responses import Response
from fastapi.middleware.wsgi import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
@app.get('/')
def index(request: Request, response: Response):
    return {'message': 'ok'}
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay