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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1An ETag is a content fingerprint that lets clients and servers agree a cached copy is still fresh without resending the body.
- 2Deterministic serialization (sorted keys, fixed separators) is what makes a content hash stable and comparable across requests.
- 3Honoring If-None-Match with a 304 response saves bandwidth while keeping the cache validation logic entirely on the server.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/http-etag-caching-in-a-fastapi-route-explained-python-39d6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.