python 41 lines · 9 steps

HTTP ETag caching in a FastAPI route

A FastAPI endpoint fingerprints its response and returns 304 Not Modified when the client's cached copy still matches.

Explained by highlit
1import hashlib
2import json
3from fastapi import APIRouter, Request, Response, Depends, HTTPException, status
4 
5router = APIRouter(prefix="/reports", tags=["reports"])
6 
7 
8def compute_etag(payload: dict) -> str:
9 encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
10 return '"' + hashlib.sha256(encoded).hexdigest()[:32] + '"'
11 
12 
13@router.get("/{report_id}")
14async def get_report(
15 report_id: int,
16 request: Request,
17 response: Response,
18 service: ReportService = Depends(get_report_service),
19):
20 report = await service.get(report_id)
21 if report is None:
22 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Report not found")
23 
24 payload = report.as_dict()
25 etag = compute_etag(payload)
26 
27 response.headers["ETag"] = etag
28 response.headers["Cache-Control"] = "private, max-age=0, must-revalidate"
29 
30 if_none_match = request.headers.get("if-none-match", "")
31 client_tags = {tag.strip() for tag in if_none_match.split(",") if tag.strip()}
32 if etag in client_tags or "*" in client_tags:
33 return Response(
34 status_code=status.HTTP_304_NOT_MODIFIED,
35 headers={
36 "ETag": etag,
37 "Cache-Control": "private, max-age=0, must-revalidate",
38 },
39 )
40 
41 return payload
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1An ETag is a content fingerprint that lets clients and servers agree a cached copy is still fresh without resending the body.
  2. 2Deterministic serialization (sorted keys, fixed separators) is what makes a content hash stable and comparable across requests.
  3. 3Honoring If-None-Match with a 304 response saves bandwidth while keeping the cache validation logic entirely on the server.

Related explainers

Share this explainer

Here's the card — post it anywhere.

HTTP ETag caching in a FastAPI route — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code