DEV Community

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

Posted on • Edited on

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

Top comments (0)