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 django.db import models from django.db.models import Q from django.conf import settings
Enforcing one default address per user in Django
data modeling
database constraints
partial index
Intermediate
7 steps
python
from typing import Any _MISSING = object()
Recursively diffing two JSON structures
recursion
sentinel
tree-traversal
Intermediate
8 steps
python
from contextlib import contextmanager from typing import Iterator import psycopg2
Streaming Postgres rows with a server-side cursor
generators
context-managers
database-streaming
Intermediate
7 steps
rust
use std::time::Duration; use axum::{ http::{header, HeaderValue, Request},
Serving fingerprinted assets in Axum
static-assets
http-caching
middleware
Intermediate
7 steps
python
import wave import os from dataclasses import dataclass
Reading WAV metadata into a dataclass
dataclass
audio
file-io
Beginner
5 steps
ruby
require "net/http" require "json" require "uri" require "base64"
Paginating an HTTP API with a Ruby enumerator
pagination
http
enumerator
Intermediate
7 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.