Master FastAPI Middleware, Background Tasks, and Deployment in One Guide
This article completes a FastAPI series by detailing middleware usage, request redirection, trusted host and CORS settings, background task handling, custom HTTP status responses, and multiple deployment options—including Uvicorn, Gunicorn, Docker, and Nginx—accompanied by full code examples.
This article is the final part of a FastAPI series, extending the previous introductory and advanced posts with practical code examples.
1. Middleware usage
FastAPI supports middleware similar to Flask hooks. The example measures request processing time and adds a custom header.
# -*- coding: UTF-8 -*-
import time
from fastapi import FastAPI
from starlette.requests import Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
print(response.headers)
return response
@app.get("/")
async def main():
return {"message": "Hello World"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)2. Request redirection middleware
Enforce HTTPS using Starlette's HTTPSRedirectMiddleware.
from fastapi import FastAPI
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
app = FastAPI()
app.add_middleware(HTTPSRedirectMiddleware)
@app.get("/")
async def main():
return {"message": "Hello World"}3. Trusted host middleware
Restrict allowed hosts (supports wildcard patterns) with TrustedHostMiddleware.
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
app.add_middleware(
TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"]
)
@app.get("/")
async def main():
return {"message": "Hello World"}4. CORS middleware
Configure Cross‑Origin Resource Sharing using CORSMiddleware, specifying origins, credentials, methods, and headers.
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"https://gzky.live",
"https://google.com",
"http://localhost:5000",
"http://localhost:8000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)5. BackgroundTasks
Define asynchronous or regular functions that run after a request, such as writing logs.
# -*- coding: UTF-8 -*-
from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: str = None):
if q:
message = f"found query: {q}
"
background_tasks.add_task(write_log, message)
return q
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks, q: str = Depends(get_query)):
message = f"message to {email}
"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}6. Custom response status codes
Define endpoints that return specific HTTP status codes using starlette.status.
from fastapi import FastAPI
from starlette import status
app = FastAPI()
@app.get("/201/", status_code=status.HTTP_201_CREATED)
async def item201():
return {"httpStatus": 201}
@app.get("/302/", status_code=status.HTTP_302_FOUND)
async def items302():
return {"httpStatus": 302}
@app.get("/404/", status_code=status.HTTP_404_NOT_FOUND)
async def items404():
return {"httpStatus": 404}
@app.get("/500/", status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
async def items500():
return {"httpStatus": 500}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)7. Deployment
FastAPI is commonly deployed with Uvicorn (or Hypercorn ) as an ASGI server.
pip install uvicorn uvicorn main:app --reload --host 0.0.0.0 --port 8000Gunicorn can also be used, typically together with Uvicorn workers.
pip install gunicorn gunicorn -w 4 -b 0.0.0.0:5000 manage:app -DDocker deployment simplifies environment setup: build an image with a Dockerfile and run the container, exposing the desired port.
Placing Nginx in front of Uvicorn/Gunicorn provides a production‑ready web server and additional features such as static file handling and TLS termination.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
