This content originally appeared on DEV Community and was authored by Nelson Adonis Hernandez
¿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'}
Default middlewares in FASTAPI
- CORS https://fastapi.tiangolo.com/tutorial/cors/
- GZIP https://fastapi.tiangolo.com/advanced/middleware/#gzipmiddleware
- HTTPSREDIRECT https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware
- TRUSTEDHOST https://fastapi.tiangolo.com/advanced/middleware/#trustedhostmiddleware
¿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'}
This content originally appeared on DEV Community and was authored by Nelson Adonis Hernandez
Print
Share
Comment
Cite
Upload
Translate

APA
Nelson Adonis Hernandez | Sciencx (2023-10-03T20:50:19+00:00) » How to create Middlewares with FastAPI. Retrieved from https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/.
MLA" » How to create Middlewares with FastAPI." Nelson Adonis Hernandez | Sciencx - Thursday August 19, 2021, https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/
HARVARDNelson Adonis Hernandez | Sciencx Thursday August 19, 2021 » How to create Middlewares with FastAPI., viewed 2023-10-03T20:50:19+00:00,<https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/>
VANCOUVERNelson Adonis Hernandez | Sciencx - » How to create Middlewares with FastAPI. [Internet]. [Accessed 2023-10-03T20:50:19+00:00]. Available from: https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/
CHICAGO" » How to create Middlewares with FastAPI." Nelson Adonis Hernandez | Sciencx - Accessed 2023-10-03T20:50:19+00:00. https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/
IEEE" » How to create Middlewares with FastAPI." Nelson Adonis Hernandez | Sciencx [Online]. Available: https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/. [Accessed: 2023-10-03T20:50:19+00:00]
rf:citation » How to create Middlewares with FastAPI | Nelson Adonis Hernandez | Sciencx | https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/ | 2023-10-03T20:50:19+00:00
https://github.com/addpipe/simple-recorderjs-demo