Skip to main content

CDN

Even though static files aren’t typically served from FastAPI, if you happen to serve static files, you can take advantage of CDN caching. To add CDN caching, enable the CDN setting to cache your static assets on Cloudflare. To verify your static files are being cached correctly, request a file and inspect the response headers. The cf-cache-status header should be either HIT or MISS. MISS should only occur when the file needs to be set or updated in the CDN. HIT will be the expected value for most requests.

Edge Caching

If your app consists of mostly endpoints that don’t change often, then you can cache the data from your API endpoints with edge caching. This will apply to your entire app and only endpoints with headers disallowing caching will ignored by the edge cache. You can prevent caching by updating the endpoint’s response to have a Cache-Control header with the value no-store.
# main.py
from fastapi import FastAPI, Response
from app.core.config import settings
from datetime import datetime

app = FastAPI()

@app.get("/")
def index(response: Response):
    response.headers["Cache-Control"] = "no-store"
    return {"message": f"The current time is {datetime.now()}"}
To control the longest a page will remain in the cache, you need to set the max-age value in your Cache-Control header.
# main.py
from fastapi import FastAPI, Response
from app.core.config import settings
from datetime import datetime

app = FastAPI()

@app.get("/")
def index(response: Response):
    response.headers["Cache-Control"] = "no-store"
    return {"message": f"The current time is {datetime.now()}"}

@app.get("/page") 
def page(response: Response):
    response.headers["Cache-Control"] = "max-age=120"
    return {"message": f"The current time is {datetime.now()}"}
To verify your endpoints are being cached correctly, request an endpoint and inspect the response headers. The cf-cache-status header should be either HIT or MISS. MISS should only occur when the page needs to be set or updated in the CDN. HIT will be the expected value for most requests.