How to Retire an API Endpoint in FastAPI: Send Deprecation and Sunset Headers, Find the Clients Still Calling It, Schedule Brownouts, and Block an Early Removal With oasdiff
A step-by-step FastAPI lab that retires an endpoint properly: RFC 9745 Deprecation and RFC 8594 Sunset headers, clients that warn, a usage ledger, brownouts that answer 410, and an oasdiff gate...
Adding an endpoint takes an afternoon. Removing one can take a year, because somewhere a script that nobody remembers still calls it. This tutorial retires one endpoint in a FastAPI service the careful way. You will announce the date in the HTTP response itself, make your own clients notice it, count who is still calling, switch the endpoint off for an hour at a time to flush out the callers who ignore every message, and add a check to your pipeline that refuses a removal that comes too early.
Table Of Content
- The terms used in this tutorial
- Prerequisites
- Step 0: Create the project folder and install the tools
- The idea
- The commands
- Check it worked
- Common mistakes
- Step 1: Build the API you want to retire, and see what its callers see
- The idea
- The code
- Run it
- What the output tells you
- Check it worked
- Common mistakes
- Step 2: Describe the retirement once
- The idea
- The code
- What each part does
- Test it
- Check it worked
- Common mistakes
- Step 3: Announce the retirement on the wire and in OpenAPI
- The idea
- The code
- Run it
- Reading the result
- Check it worked
- Common mistakes
- Step 4: Make your own clients notice
- The idea
- The code
- Run it
- Turn the warning into a build gate
- Check it worked
- Common mistakes
- Step 5: Find out who still calls the endpoint
- The idea
- The code
- Why “nobody called for N days” is a dangerous rule
- Reading the model
- Check it worked
- Common mistakes
- Step 6: Run brownouts, then leave a tombstone
- The idea
- Run it
- Reading the result
- Check it worked
- Common mistakes
- Step 7: Refuse an early removal in CI
- The idea
- The code
- Reading the table
- Check it worked
- Common mistakes
- Step 8: Test the tests
- The idea
- Step 9: Put it together
- Run everything once
- A schedule you can adapt
- A checklist for your own API
- What to remember
- Sources and further reading
The starting point is freeCodeCamp’s November 20, 2026 article How to Write an API Migration Guide (With a Real Example). It teaches the document that developers read: classify every change, show before-and-after code, add a checklist. Its publishing step has one sentence about the machine-readable side: “You can also ask the engineering team to add a Sunset header to v1 responses.” This tutorial is that engineering work, and it goes a few steps further. It does not replace the guide. It aims at the people who never read the guide.
You will build a small Orders API with a v1 endpoint that has to go away and a v2 endpoint that replaces it. Then you will retire v1 on a schedule: announced on December 1, 2026 and switched off on June 1, 2027. Along the way you will write about 1,200 lines of Python, and the important parts have a test or a measured result next to them.
By the end you will be able to:
- explain the difference between deprecating, sunsetting and removing an endpoint, and say which part of the web’s standards covers each;
- write the
Deprecationheader (RFC 9745) and theSunsetheader (RFC 8594) correctly, including the two date formats that people get wrong; - describe the retirement once, in a single object, and have the headers, the OpenAPI flag and the
410 Goneanswer all come from it; - make a
requestsorhttpxclient warn about a deprecated endpoint, and make a test suite fail when the sunset is less than 30 days away; - keep a ledger of who still calls the route, and explain why a “no calls for N days” rule can approve a removal too early;
- run brownouts that answer
410for a few hours, and see in a model why their timing matters more than their number; - block an early removal in CI by comparing OpenAPI documents with oasdiff;
- prove that your tests catch 20 planted bugs.
Everything below was run on Windows 11 on November 22, 2026, with Python 3.13.14, FastAPI 0.165.0, Starlette 1.10.0, uvicorn 0.54.0, requests 2.34.2, httpx 0.28.1, pytest 9.2.0 and oasdiff 1.39.0. Every output block is copied from those runs. The callers in Step 5 are a model I invented to show a pattern, not measurements of a real system, and I say so again where it matters.
The terms used in this tutorial
- Deprecation. A statement that an endpoint is no longer recommended. It still works. RFC 9745 puts it this way: “The act of deprecation does not change any behavior of the resource.”
- Sunset. The date after which the endpoint is expected to stop working. RFC 8594 defines the
Sunsetheader for it. - Removal. What actually happens on the sunset date: the endpoint stops answering normally.
- Successor. The endpoint that replaces the old one. Here,
/v2/orders/{order_id}. - Structured Field Date. A date format from RFC 9651 for HTTP headers: an
@sign followed by whole seconds since January 1, 1970 UTC, for example@1796083200. - IMF-fixdate. The one fixed spelling of an HTTP date, for example
Tue, 01 Jun 2027 00:00:00 GMT. The zone is always the three letters GMT. - Brownout. A planned, short period in which the deprecated endpoint is switched off on purpose, so that callers who ignored every warning find out while the endpoint can still come back.
- Tombstone. What you leave behind after the sunset: a route that answers
410 Gonewith a pointer to the replacement, instead of a bare 404. - Problem details. The JSON error format from RFC 9457, sent with the media type
application/problem+json. - Ledger. A table that counts calls to the deprecated route per hour and per client, so you can see who has not migrated.
x-sunset. A custom field (an OpenAPI “extension”) that the oasdiff tool reads to learn when an operation may be removed.- Mutation test. A check of your tests: plant one deliberate bug in the code, run the tests, and see whether any test fails.
Prerequisites
- Python 3.13. I used 3.13.14. Where I write
python, usepython3if that is your command name. - Internet access to install packages from PyPI and to download one program, oasdiff, from GitHub.
- A shell with
curl,tarandsha256sum. I ran every command in Git Bash on Windows 11, so paths use forward slashes (.venv/Scripts/python) and variables are set withexport. On Linux and macOS use.venv/bin/python. In PowerShell use backslashes,$env:LAB_NOW = "..."andGet-FileHashinstead ofsha256sum. I ran the lab only on Windows. - Basic FastAPI and HTTP. You should know what a path operation is and what a response header is. Everything else is explained when it first appears.
- About two hours. The whole lab runs in about a minute.
Step 0: Create the project folder and install the tools
The idea
You need a clean folder with its own Python environment, the web framework and test tools, and one extra program: oasdiff, a command-line tool that compares two OpenAPI documents and reports which changes break clients. You will use it in Step 7.
The commands
mkdir deprecation-lab
cd deprecation-lab
python -m venv .venv
.venv/Scripts/python -m pip install fastapi==0.165.0 uvicorn==0.54.0 requests==2.34.2 httpx==0.28.1 httpx2==2.16.2 pytest==9.2.0
mkdir tools
curl -L -o tools/oasdiff.tar.gz https://github.com/oasdiff/oasdiff/releases/download/v1.39.0/oasdiff_1.39.0_windows_amd64.tar.gz
sha256sum tools/oasdiff.tar.gz
tar -xzf tools/oasdiff.tar.gz -C tools
tools/oasdiff.exe --version
The pip line installs FastAPI, the server, the two HTTP clients we will teach to warn, and pytest. The extra httpx2 is there because the test client that ships with Starlette 1.10.0 is built on it. The release page lists the checksum of the Windows archive, and sha256sum should print the same value:
956a73df88e03efdf3fcc5f327446cc176fefe4adcea1978b0fef464a1ee8901 tools/oasdiff.tar.gz
The last command prints oasdiff version 1.39.0. On other systems download the archive that matches your platform from the same release page. Set an environment variable called OASDIFF to the full path of the program (or put it on your PATH); the script in Step 7 reads it. Finally, create a file named pytest.ini next to your code:
[pytest]
pythonpath = .
norecursedirs = consumer .git
addopts = -p no:cacheprovider
pythonpath = . lets the tests import your modules from the project folder. norecursedirs keeps a plain pytest run out of the consumer folder, which you will meet in Step 4 and which needs an environment variable to run.
Check it worked
tools/oasdiff.exe --versionprints version 1.39.0..venv/Scripts/python -m pytest --versionprints pytest 9.2.0.
Common mistakes
- Running
pytestfrom the wrong folder.pytest.iniand the modules must be in the same folder. - Skipping the checksum. It takes a second and shows that the download matches the checksum on the release page.
Step 1: Build the API you want to retire, and see what its callers see
The idea
First a baseline. The Orders API has two versions of one endpoint. Version 1 returns the order total as a decimal number of dollars. Version 2 returns it as whole cents plus a currency code, which is the safer way to carry money (the money tutorial on this site shows why). Callers have to change code to move from one to the other, so this is a real migration and not a rename.
The code
The data and the two handlers live in one module, so that the plain app and the finished app can share them:
# orders.py
from fastapi import HTTPException
ORDERS = {7: {"id": 7, "total_cents": 1250, "currency": "USD", "status": "paid"}}
def find(order_id: int) -> dict:
order = ORDERS.get(order_id)
if order is None:
raise HTTPException(status_code=404, detail="no such order")
return order
def order_v1(order_id: int) -> dict:
order = find(order_id)
return {"id": order["id"], "total": order["total_cents"] / 100, "status": order["status"]}
def order_v2(order_id: int) -> dict:
return dict(find(order_id))
The plain app registers both handlers and nothing else:
# orders_v0.py
from fastapi import FastAPI
from orders import order_v1, order_v2
app = FastAPI(title="Orders API")
app.get("/v1/orders/{order_id}")(order_v1)
app.get("/v2/orders/{order_id}")(order_v2)
The lab starts and stops real servers, so one small helper does it. It starts uvicorn as a child process, waits until the port accepts connections, and stops the whole process tree afterwards (on Windows it uses taskkill /T, which also covers the launcher that a virtual environment puts in front of the real Python; on other systems it simply terminates the child, a path I did not run). It always uses 127.0.0.1 rather than localhost. On this Windows machine three requests to localhost took 2.03, 2.07 and 2.07 seconds, and three to 127.0.0.1 took 0.01, 0.00 and 0.00.
# serve.py
import os
import socket
import subprocess
import sys
import time
from contextlib import contextmanager
@contextmanager
def server(target="app:app", port=8781, **env):
child_env = {**os.environ, **{key: str(value) for key, value in env.items()}}
command = [sys.executable, "-m", "uvicorn", target, "--host", "127.0.0.1", "--port", str(port), "--log-level", "warning"]
process = subprocess.Popen(command, env=child_env)
try:
for _ in range(100):
with socket.socket() as probe:
probe.settimeout(0.2)
if probe.connect_ex(("127.0.0.1", port)) == 0:
break
time.sleep(0.1)
else:
raise RuntimeError("the server did not start")
yield f"http://127.0.0.1:{port}"
finally:
if os.name == "nt":
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], capture_output=True)
else:
process.terminate()
process.wait()
Now a script that plays the part of a client and writes down everything it receives:
# step01_baseline.py
"""What does a client see today? Start the plain API and look at everything it receives."""
import os
import subprocess
import requests
from fastapi import FastAPI
from fastapi.testclient import TestClient
from orders import order_v1
from serve import server
with server("orders_v0:app", 8781) as base:
for path in ("/v1/orders/7", "/v2/orders/7"):
response = requests.get(base + path, timeout=5)
print(f"GET {path} -> {response.status_code} {response.json()}")
print()
headers = requests.get(base + "/v1/orders/7", timeout=5).headers
print("response headers on /v1/orders/7 (the date line varies):")
for name, value in headers.items():
print(f" {name}: {value}")
print()
wanted = ("deprecation", "sunset", "link")
print("headers that announce a retirement:", [name for name in headers if name.lower() in wanted] or "none")
openapi = requests.get(base + "/openapi.json", timeout=5).json()
print("OpenAPI flag on /v1:", openapi["paths"]["/v1/orders/{order_id}"]["get"].get("deprecated", "not set"))
curl = subprocess.run(["curl", "-s", "-o", os.devnull, "-w", "%{http_code}", base + "/v1/orders/7"], capture_output=True, text=True)
print(f"curl: HTTP {curl.stdout}, text on stderr: {curl.stderr!r}")
flagged = FastAPI()
flagged.get("/v1/orders/{order_id}", deprecated=True)(order_v1)
reply = TestClient(flagged).get("/v1/orders/7")
operation = flagged.openapi()["paths"]["/v1/orders/{order_id}"]["get"]
print()
print("with deprecated=True: OpenAPI deprecated =", operation["deprecated"], "| response headers:", sorted(reply.headers))
Run it
.venv/Scripts/python step01_baseline.py
GET /v1/orders/7 -> 200 {'id': 7, 'total': 12.5, 'status': 'paid'}
GET /v2/orders/7 -> 200 {'id': 7, 'total_cents': 1250, 'currency': 'USD', 'status': 'paid'}
response headers on /v1/orders/7 (the date line varies):
date: Sun, 22 Nov 2026 11:28:50 GMT
server: uvicorn
content-length: 37
content-type: application/json
headers that announce a retirement: none
OpenAPI flag on /v1: not set
curl: HTTP 200, text on stderr: ''
with deprecated=True: OpenAPI deprecated = True | response headers: ['content-length', 'content-type']
What the output tells you
Both versions answer 200 with their own shape. The response headers are the four ordinary ones (date, server, content-length and content-type); nothing mentions a retirement, and the OpenAPI document has no deprecated flag. curl printed nothing to its error output either.
The last two lines are the important ones. FastAPI documents a flag for this: “If you need to mark a path operation as deprecated, but without removing it, pass the parameter deprecated”. The experiment shows what the flag does and does not do. It sets deprecated: true in the OpenAPI document, which documentation pages show with a strike-through, and the response headers stay exactly as they were. A program calling the endpoint cannot see the flag. For a client, the endpoint is as healthy as it was yesterday.
Check it worked
- The headers list has no
deprecation,sunsetorlinkentry. - The OpenAPI flag is
not seton the plain app andTrueon the flagged one, while the flagged app’s response headers are unchanged.
Common mistakes
- Believing that
deprecated=Truewarns callers. It documents the route for people who read the docs, and only them. - Testing with a client that has a browser-like retry or caching layer. Use the bare client first, so that you see the raw answer.
Step 2: Describe the retirement once
The idea
A retirement has a few dates and a few documents, and they must never disagree: the Deprecation header, the Sunset header, the OpenAPI flag, the x-sunset field and the 410 answer all need the same dates. So you describe the retirement in one object and generate everything else from it.
Two web standards define the headers, and they spell dates differently. This table is the part people copy wrongly, so read it once now:
| Where | Defined by | Format | Example |
|---|---|---|---|
Deprecation header |
RFC 9745 (March 2025) | Structured Field Date: @ and Unix seconds |
@1796083200 |
Sunset header |
RFC 8594 and RFC 9110 | HTTP date in IMF-fixdate form, always GMT | Tue, 01 Jun 2027 00:00:00 GMT |
x-sunset in OpenAPI |
oasdiff convention | RFC 3339 date | 2027-06-01 |
RFC 9745 says: “Deprecation is an Item Structured Header Field; its value MUST be a Date”. It also sets one rule that links the two headers: “The timestamp given in the Sunset HTTP header field MUST NOT be earlier than the one given in the Deprecation header field.” RFC 9110, which defines HTTP dates, is just as direct: “When a sender generates a field that contains one or more timestamps defined as HTTP-date, the sender MUST generate those timestamps in the IMF-fixdate format.” The format ends in the letters GMT.
There is a trap here. The example in RFC 9745’s own section 4 prints Sunset: Sun, 30 Jun 2024 23:59:59 UTC, with the zone spelled UTC. That is not an IMF-fixdate. Copy the shape of the RFC example and you send a value that a strict receiver may reject. The code below sends GMT. The reading side, in Step 4, accepts both spellings, because being strict about what you send and generous about what you accept is the safe way round.
The registry of link relations lists three names that the headers can point to. In the registry’s words, deprecation “Refers to documentation (intended for human consumption) about the deprecation of the link’s context”, sunset “Identifies a resource that provides information about the context’s retirement policy”, and successor-version “Points to a resource containing the successor version in the version history”. We will use the first and the last.
The code
# lifecycle.py
"""One source of truth for a retiring endpoint: dates, phases and the headers that announce them."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from email.utils import format_datetime
def utc(year, month, day, hour=0, minute=0, second=0):
return datetime(year, month, day, hour, minute, second, tzinfo=timezone.utc)
class Keep(dict):
def __missing__(self, key):
return "{" + key + "}"
def need_utc(name, moment):
if moment.tzinfo != timezone.utc:
raise ValueError(f"{name} must be a datetime with tzinfo=timezone.utc")
@dataclass(frozen=True)
class Window:
"""A scheduled brownout: the endpoint answers 410 from start (included) until end (excluded)."""
start: datetime
end: datetime
def __post_init__(self):
need_utc("start", self.start)
need_utc("end", self.end)
if self.end <= self.start:
raise ValueError("a brownout window must end after it starts")
def covers(self, now):
return self.start <= now < self.end
@dataclass(frozen=True)
class Lifecycle:
name: str
deprecated_at: datetime
sunset_at: datetime
doc_url: str
successor: str | None = None
brownouts: tuple[Window, ...] = ()
min_notice_days: int = 90
def __post_init__(self):
need_utc("deprecated_at", self.deprecated_at)
need_utc("sunset_at", self.sunset_at)
if self.sunset_at < self.deprecated_at:
raise ValueError("Sunset must not be earlier than Deprecation (RFC 9745, section 4)")
if self.sunset_at - self.deprecated_at < timedelta(days=self.min_notice_days):
raise ValueError(f"our policy: at least {self.min_notice_days} days of notice")
for window in self.brownouts:
if window.start < self.deprecated_at or window.end > self.sunset_at:
raise ValueError("a brownout must fall between deprecation and sunset")
def window_at(self, now):
return next((w for w in self.brownouts if w.covers(now)), None)
def phase(self, now):
if now >= self.sunset_at:
return "gone"
if self.window_at(now) is not None:
return "brownout"
if now >= self.deprecated_at:
return "deprecated"
return "announced"
def days_left(self, now):
return (self.sunset_at - now).total_seconds() / 86400
def successor_for(self, path_params=None):
"""The successor path with the request's path parameters filled in; unknown placeholders stay as written."""
if not self.successor:
return None
return self.successor.format_map(Keep(path_params or {}))
def headers(self, path_params=None):
links = [f'<{self.doc_url}>; rel="deprecation"; type="text/html"']
if self.successor:
links.append(f'<{self.successor_for(path_params)}>; rel="successor-version"')
return {
"Deprecation": "@" + str(int(self.deprecated_at.timestamp())),
"Sunset": format_datetime(self.sunset_at, usegmt=True),
"Link": ", ".join(links),
}
What each part does
utc() builds a timezone-aware datetime, and need_utc() rejects anything that is naive or uses another zone. That strictness is deliberate: a date written in somebody’s local time can retire an endpoint hours early or late. Keep is a small helper for the successor template: when a placeholder has no value, it stays as written instead of raising an error, so that a missing path parameter is not the reason a request fails.
A Window is a brownout: from its start, which is included, to its end, which is not. A Lifecycle holds the two dates, the address of your migration guide, the successor path, the brownout windows and a minimum notice period, which is our own policy and not a standard. Its constructor refuses three mistakes: a sunset earlier than the deprecation date (the RFC’s MUST NOT), too little notice, and a brownout outside the notice period.
phase(now) answers one question: where are we in the schedule?
| Phase | When | The endpoint |
|---|---|---|
announced |
before the deprecation date | works; headers announce the future deprecation date |
deprecated |
from the deprecation date until the sunset | works; headers; OpenAPI flagged |
brownout |
inside a window | answers 410 |
gone |
from the sunset instant on | answers 410; hidden from the docs |
headers() builds the three headers. The Deprecation value is @ plus the Unix seconds. format_datetime(..., usegmt=True) from Python’s standard library produces the IMF-fixdate with GMT. The Link header carries the guide with rel="deprecation" and the replacement with rel="successor-version"; several links in one header are separated by commas.
Test it
Every rule above gets a test. The expected values are written out by hand, not computed by the code under test, so that a wrong format cannot agree with itself:
# test_lifecycle.py
import re
from datetime import datetime, timedelta, timezone
import pytest
from lifecycle import Lifecycle, Window, utc
DOC = "https://api.example.com/docs/orders-v2-migration"
IMF_FIXDATE = re.compile(r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT")
def make(**changes):
values = dict(
name="GET /v1/orders/{order_id}",
deprecated_at=utc(2026, 12, 1),
sunset_at=utc(2027, 6, 1),
doc_url=DOC,
successor="/v2/orders/{order_id}",
)
values.update(changes)
return Lifecycle(**values)
def test_deprecation_header_is_an_sf_date():
assert make().headers()["Deprecation"] == "@1796083200"
def test_sunset_header_is_an_imf_fixdate_in_gmt():
value = make().headers()["Sunset"]
assert value == "Tue, 01 Jun 2027 00:00:00 GMT"
assert IMF_FIXDATE.fullmatch(value)
def test_link_header_carries_the_guide_and_the_successor():
link = make().headers({"order_id": "7"})["Link"]
assert f'<{DOC}>; rel="deprecation"; type="text/html"' in link
assert '</v2/orders/7>; rel="successor-version"' in link
def test_a_placeholder_the_route_does_not_have_stays_as_written():
assert '</v2/orders/{order_id}>; rel="successor-version"' in make().headers()["Link"]
def test_link_header_without_a_successor_has_only_the_guide():
assert make(successor=None).headers()["Link"] == f'<{DOC}>; rel="deprecation"; type="text/html"'
def test_sunset_before_deprecation_is_refused():
with pytest.raises(ValueError, match="RFC 9745"):
make(sunset_at=utc(2026, 11, 30), min_notice_days=0)
def test_too_little_notice_is_refused():
with pytest.raises(ValueError, match="90 days"):
make(sunset_at=utc(2027, 1, 15))
@pytest.mark.parametrize("moment", [datetime(2027, 6, 1), datetime(2027, 6, 1, tzinfo=timezone(timedelta(hours=2)))])
def test_only_utc_datetimes_are_accepted(moment):
with pytest.raises(ValueError, match="timezone.utc"):
make(sunset_at=moment)
def test_a_window_must_end_after_it_starts():
with pytest.raises(ValueError, match="end after"):
Window(utc(2027, 3, 1, 12), utc(2027, 3, 1, 12))
def test_a_brownout_must_fall_inside_the_notice_period():
with pytest.raises(ValueError, match="between"):
make(brownouts=(Window(utc(2027, 5, 31, 12), utc(2027, 6, 1, 12)),))
@pytest.mark.parametrize(
"now, expected",
[
(utc(2026, 11, 30, 23, 59, 59), "announced"),
(utc(2026, 12, 1), "deprecated"),
(utc(2027, 3, 31, 21, 59, 59), "deprecated"),
(utc(2027, 3, 31, 22), "brownout"),
(utc(2027, 3, 31, 22, 59, 59), "brownout"),
(utc(2027, 3, 31, 23), "deprecated"),
(utc(2027, 5, 31, 23, 59, 59), "deprecated"),
(utc(2027, 6, 1), "gone"),
(utc(2030, 1, 1), "gone"),
],
)
def test_phase_boundaries(now, expected):
lifecycle = make(brownouts=(Window(utc(2027, 3, 31, 22), utc(2027, 3, 31, 23)),))
assert lifecycle.phase(now) == expected
def test_days_left():
assert make().days_left(utc(2027, 5, 2)) == 30
.venv/Scripts/python -m pytest -q test_lifecycle.py
..................... [100%]
21 passed in 0.02s
Check it worked
- All tests pass. The boundary tests pin the exact instants: 21:59:59 is still
deprecatedand 22:00:00 is a brownout, and the sunset second itself is alreadygone.
Common mistakes
- Sending
Deprecation: true. That was never a date, and RFC 9745 requires one. Step 4’s reader treats such a value as “deprecated, date unknown” rather than failing. - Building the
Sunsetvalue withstrftimeand the machine’s zone name. On a server set to another zone you would send the wrong instant. Use UTC andusegmt=True. - Choosing a sunset before you have chosen the notice period. Pick the notice period first, because it is a promise to your callers.
Step 3: Announce the retirement on the wire and in OpenAPI
The idea
Now connect the Lifecycle to FastAPI. The obvious way to add a header is a dependency that sets it on the injected Response. Try that first, because it shows a trap:
# naive_headers.py
"""The obvious way to add a header, and what it does to an error response."""
from fastapi import Depends, FastAPI, Response
from fastapi.testclient import TestClient
from orders import order_v1
def announce(response: Response):
response.headers["Deprecation"] = "@1796083200"
app = FastAPI()
app.get("/v1/orders/{order_id}", dependencies=[Depends(announce)])(order_v1)
api = TestClient(app)
for order_id in (7, 999):
reply = api.get(f"/v1/orders/{order_id}")
print(f"order {order_id}: HTTP {reply.status_code}, Deprecation header present: {'deprecation' in reply.headers}")
.venv/Scripts/python naive_headers.py
order 7: HTTP 200, Deprecation header present: True
order 999: HTTP 404, Deprecation header present: False
The header is there on the success and gone on the error. In FastAPI 0.165.0’s routing.py the headers of the injected Response are copied onto the answer only after the route function has returned normally, and a route that raises HTTPException never gets there. A caller that asks for an order that does not exist gets a plain 404 and never learns that the whole endpoint is on its way out. The fix is a middleware. FastAPI’s documentation defines it as “a function that works with every request before it is processed by any specific path operation”, and it sees every response, including error responses, on the way out.
The plan: a small guard dependency decides the phase, records the call in the ledger (Step 5) and stores the headers on request.state. A middleware copies them onto whatever response leaves. For brownouts and after the sunset, the guard raises a Retired exception and a handler turns it into a 410 Gone problem document. RFC 9110 defines that status: it “indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent”. RFC 9457 defines the document format, and a problem document serialized as JSON uses the application/problem+json media type. The problem details tutorial on this site covers that format in depth.
One more detail from the same RFC 9110 section: “A 410 response is heuristically cacheable”. A shared cache could therefore keep a brownout’s 410 and keep serving it after the brownout has ended. The handler sends Cache-Control: no-store to forbid that (the Cache-Control tutorial explains the header). I did not put a cache in front of the lab, so I can show the header and test for it, not a cache obeying it.
The code
# retire.py
"""FastAPI wiring: headers on every answer, a 410 problem document for brownouts and the sunset."""
from fastapi import Depends, Request
from fastapi.responses import JSONResponse
class Retired(Exception):
def __init__(self, lifecycle, phase):
self.lifecycle = lifecycle
self.phase = phase
def stamp(moment):
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
def client_id(request):
declared = request.headers.get("x-client-id")
agent = request.headers.get("user-agent", "").split("/")[0]
return (declared or agent or "anonymous")[:64]
def problem(lifecycle, phase, now, path_params):
sunset = lifecycle.sunset_at.strftime("%Y-%m-%d")
body = {"type": lifecycle.doc_url, "status": 410, "sunset": stamp(lifecycle.sunset_at)}
if phase == "brownout":
body["title"] = "Scheduled brownout of a retiring endpoint"
body["detail"] = f"This endpoint is retired on {sunset}. It is switched off until the brownout ends."
body["brownout_ends"] = stamp(lifecycle.window_at(now).end)
else:
body["title"] = "This endpoint has been retired"
body["detail"] = f"This endpoint was retired on {sunset}."
if lifecycle.successor:
body["successor"] = lifecycle.successor_for(path_params)
return body
def install(app, clock, ledger):
app.state.clock = clock
app.state.ledger = ledger
@app.middleware("http")
async def retirement_headers(request: Request, call_next):
response = await call_next(request)
for name, value in getattr(request.state, "retirement", {}).items():
response.headers[name] = value
return response
@app.exception_handler(Retired)
async def retired_handler(request: Request, exc: Retired):
now = request.app.state.clock()
body = problem(exc.lifecycle, exc.phase, now, request.path_params)
return JSONResponse(
body, status_code=410, media_type="application/problem+json", headers={"Cache-Control": "no-store"}
)
def retire(lifecycle, now):
"""Keyword arguments for @app.get(): OpenAPI flag, x-sunset and the guard dependency."""
def guard(request: Request):
moment = request.app.state.clock()
phase = lifecycle.phase(moment)
request.app.state.ledger.record(moment, lifecycle.name, client_id(request), phase)
request.state.retirement = lifecycle.headers(request.path_params)
if phase in ("brownout", "gone"):
raise Retired(lifecycle, phase)
phase = lifecycle.phase(now)
options = {"dependencies": [Depends(guard)]}
if phase != "announced":
options["deprecated"] = True
options["openapi_extra"] = {"x-sunset": lifecycle.sunset_at.date().isoformat()}
if phase == "gone":
options["include_in_schema"] = False
return options
retire(lifecycle, now) returns the keyword arguments for a route decorator. It always adds the guard. Once the phase is past announced it also sets deprecated=True and an openapi_extra value of {"x-sunset": "2027-06-01"}. FastAPI’s documentation says: “You can extend the OpenAPI schema for a path operation using the parameter openapi_extra.” After the sunset it adds include_in_schema=False, so the tombstone disappears from the docs while it keeps answering. Before the deprecation date the headers announce the future date, but the OpenAPI document stays quiet, because a flag says “is deprecated” and not “will be”.
client_id() names the caller by an X-Client-Id header if there is one, and by the first part of the User-Agent otherwise. It is self-declared, so treat it as a label for finding people, not as proof of who they are.
The app itself is a factory, so that tests and scripts can build it with their own clock:
# app.py
import os
from datetime import datetime, timezone
from fastapi import FastAPI
from ledger import Ledger
from lifecycle import Lifecycle, Window, utc
from orders import order_v1, order_v2
from retire import install, retire
ORDERS_V1 = Lifecycle(
name="GET /v1/orders/{order_id}",
deprecated_at=utc(2026, 12, 1),
sunset_at=utc(2027, 6, 1),
doc_url="https://api.example.com/docs/orders-v2-migration",
successor="/v2/orders/{order_id}",
brownouts=(
Window(utc(2027, 3, 28, 23), utc(2027, 3, 29, 0)),
Window(utc(2027, 3, 31, 21, 30), utc(2027, 3, 31, 22, 30)),
),
)
def real_clock():
return datetime.now(timezone.utc)
def fixed_clock(text):
moment = datetime.fromisoformat(text)
return lambda: moment
def create_app(clock=real_clock, ledger=None, v1=ORDERS_V1):
app = FastAPI(title="Orders API", version="2.0.0")
install(app, clock, ledger or Ledger())
if v1 is not None:
app.get("/v1/orders/{order_id}", **retire(v1, clock()))(order_v1)
app.get("/v2/orders/{order_id}")(order_v2)
return app
app = create_app(
clock=fixed_clock(os.environ["LAB_NOW"]) if "LAB_NOW" in os.environ else real_clock,
ledger=Ledger(os.environ.get("LAB_DB", ":memory:")),
)
create_app(v1=None) builds the app after the endpoint has been deleted, which Step 7 uses. LAB_NOW freezes the server’s clock, so that every run of this tutorial prints the same dates. The two brownout windows are explained in Steps 5 and 6; ignore them for now, because they only matter on March 28 and 31.
Run it
The script freezes the clock at January 10, 2027 and asks the server for both versions with curl -si, which prints the status line, the headers and the body. It removes the date: line, which changes on every run:
# step03_headers.py
"""The API announces the retirement. LAB_NOW freezes the server's clock so every run prints the same dates."""
import subprocess
from clientguard import parse_deprecation, parse_sunset
from serve import server
NOW = "2027-01-10T12:00:00+00:00"
def curl(base, path, *extra):
result = subprocess.run(["curl", "-si", *extra, base + path], capture_output=True, text=True, encoding="utf-8")
return "\n".join(line for line in result.stdout.splitlines() if not line.lower().startswith("date:"))
with server("app:app", 8782, LAB_NOW=NOW) as base:
print("$ curl -si http://127.0.0.1:8782/v1/orders/7 (date line removed)")
print(curl(base, "/v1/orders/7"))
print()
print("$ curl -si http://127.0.0.1:8782/v2/orders/7 (date line removed)")
print(curl(base, "/v2/orders/7"))
print()
from requests import get
headers = get(base + "/v1/orders/7", timeout=5).headers
print("Deprecation decodes to", parse_deprecation(headers["Deprecation"]).isoformat())
print("Sunset decodes to ", parse_sunset(headers["Sunset"]).isoformat())
spec = get(base + "/openapi.json", timeout=5).json()["paths"]["/v1/orders/{order_id}"]["get"]
print("OpenAPI says deprecated =", spec["deprecated"], "and x-sunset =", spec["x-sunset"])
.venv/Scripts/python step03_headers.py
$ curl -si http://127.0.0.1:8782/v1/orders/7 (date line removed)
HTTP/1.1 200 OK
server: uvicorn
content-length: 37
content-type: application/json
deprecation: @1796083200
sunset: Tue, 01 Jun 2027 00:00:00 GMT
link: <https://api.example.com/docs/orders-v2-migration>; rel="deprecation"; type="text/html", </v2/orders/7>; rel="successor-version"
{"id":7,"total":12.5,"status":"paid"}
$ curl -si http://127.0.0.1:8782/v2/orders/7 (date line removed)
HTTP/1.1 200 OK
server: uvicorn
content-length: 60
content-type: application/json
{"id":7,"total_cents":1250,"currency":"USD","status":"paid"}
Deprecation decodes to 2026-12-01T00:00:00+00:00
Sunset decodes to 2027-06-01T00:00:00+00:00
OpenAPI says deprecated = True and x-sunset = 2027-06-01
Reading the result
The /v1 answer carries all three headers. deprecation: @1796083200 decodes to December 1, 2026. sunset is the IMF-fixdate for June 1, 2027. The link header gives the guide and the order-specific successor, /v2/orders/7, because the guard filled in the path parameter. The /v2 answer carries none of them. The OpenAPI document and the headers agree: deprecated is True and x-sunset is the same date as the header.
The tests pin each of those facts, plus the error responses and the phases before and after:
# test_api.py
from datetime import timezone
import pytest
from fastapi.testclient import TestClient
from app import ORDERS_V1, create_app
from clientguard import parse_deprecation, parse_sunset
from ledger import Ledger
from lifecycle import utc
DEPRECATED = utc(2027, 1, 10, 12)
BROWNOUT = utc(2027, 3, 28, 23, 30)
GONE = utc(2027, 6, 2)
def client_at(moment, **kwargs):
return TestClient(create_app(clock=lambda: moment, **kwargs))
def test_v2_never_carries_retirement_headers():
response = client_at(DEPRECATED).get("/v2/orders/7")
assert response.status_code == 200
assert response.json()["total_cents"] == 1250
assert not {"deprecation", "sunset", "link"} & set(response.headers)
def test_v1_still_works_and_announces_its_retirement():
response = client_at(DEPRECATED).get("/v1/orders/7")
assert response.status_code == 200
assert response.json() == {"id": 7, "total": 12.5, "status": "paid"}
assert response.headers["deprecation"] == "@1796083200"
assert response.headers["sunset"] == "Tue, 01 Jun 2027 00:00:00 GMT"
assert '</v2/orders/7>; rel="successor-version"' in response.headers["link"]
def test_headers_also_reach_error_responses():
response = client_at(DEPRECATED).get("/v1/orders/999")
assert response.status_code == 404
assert response.headers["deprecation"] == "@1796083200"
def test_before_the_deprecation_date_the_headers_announce_it_but_openapi_stays_quiet():
app = create_app(clock=lambda: utc(2026, 11, 22))
response = TestClient(app).get("/v1/orders/7")
assert parse_deprecation(response.headers["deprecation"]) > utc(2026, 11, 22)
assert "deprecated" not in app.openapi()["paths"]["/v1/orders/{order_id}"]["get"]
def test_a_brownout_answers_410_with_a_problem_document_that_is_never_cached():
response = client_at(BROWNOUT).get("/v1/orders/7")
assert response.status_code == 410
assert response.headers["content-type"] == "application/problem+json"
assert response.headers["cache-control"] == "no-store"
assert response.headers["sunset"] == "Tue, 01 Jun 2027 00:00:00 GMT"
body = response.json()
assert body["type"] == ORDERS_V1.doc_url
assert body["status"] == 410
assert body["brownout_ends"] == "2027-03-29T00:00:00Z"
assert body["successor"] == "/v2/orders/7"
def test_after_the_sunset_it_is_a_410_tombstone_hidden_from_the_docs():
app = create_app(clock=lambda: GONE)
response = TestClient(app).get("/v1/orders/7")
assert response.status_code == 410
assert response.headers["cache-control"] == "no-store"
assert response.json()["title"] == "This endpoint has been retired"
assert "/v1/orders/{order_id}" not in app.openapi()["paths"]
assert "/v2/orders/{order_id}" in app.openapi()["paths"]
def test_openapi_flag_and_x_sunset_agree_with_the_sunset_header():
app = create_app(clock=lambda: DEPRECATED)
operation = app.openapi()["paths"]["/v1/orders/{order_id}"]["get"]
header = TestClient(app).get("/v1/orders/7").headers["sunset"]
assert operation["deprecated"] is True
assert operation["x-sunset"] == parse_sunset(header).astimezone(timezone.utc).date().isoformat()
assert "deprecated" not in app.openapi()["paths"]["/v2/orders/{order_id}"]["get"]
def test_the_ledger_counts_every_attempt_including_the_410s():
ledger = Ledger()
clock = {"now": DEPRECATED}
api = TestClient(create_app(clock=lambda: clock["now"], ledger=ledger))
api.get("/v1/orders/7", headers={"X-Client-Id": "billing-export"})
api.get("/v1/orders/7", headers={"X-Client-Id": "billing-export"})
clock["now"] = BROWNOUT
api.get("/v1/orders/7", headers={"X-Client-Id": "billing-export"})
clock["now"] = GONE
api.get("/v1/orders/7")
rows = ledger.db.execute("SELECT client, phase, SUM(calls) FROM usage GROUP BY client, phase ORDER BY client, phase").fetchall()
assert rows == [("billing-export", "brownout", 1), ("billing-export", "deprecated", 2), ("testclient", "gone", 1)]
@pytest.mark.parametrize("header, expected", [({"X-Client-Id": "mobile-app"}, "mobile-app"), ({"User-Agent": "partner-sync/3.1"}, "partner-sync")])
def test_the_client_is_named_by_header_or_user_agent(header, expected):
ledger = Ledger()
client_at(DEPRECATED, ledger=ledger).get("/v1/orders/7", headers=header)
assert [row[0] for row in ledger.report("GET /v1/orders/{order_id}")] == [expected]
.venv/Scripts/python -m pytest -q test_api.py
.......... [100%]
10 passed in 0.26s
Check it worked
curl -sion the/v1route showsdeprecation,sunsetandlink; on/v2it shows none of them.- The 404 test passes: an unknown order id still carries the headers.
Common mistakes
- Adding the headers inside the route function or in a dependency only. Errors lose them, as the experiment showed.
- Letting the OpenAPI flag, the header and the 410 text come from three different places. They drift apart. One
Lifecycleprevents that, andtest_openapi_flag_and_x_sunset_agree_with_the_sunset_headerproves it. - Assuming the
Linkparser in Step 4 reads every link that RFC 8288 allows. It is a small regular expression that handles the shapes used here, so keep the URLs in your headers simple.
Step 4: Make your own clients notice
The idea
Headers are only a hint, and RFC 8594 says so: “Clients SHOULD treat Sunset timestamps as hints”. A client that never looks at them will not notice anything, and the plain session in the output below shows it. So give every client you control, and every test suite that calls your API, a few lines that read the headers and warn.
Two design choices matter. The warning category is a subclass of UserWarning, not DeprecationWarning. Python’s documentation describes DeprecationWarning as “ignored by default, unless triggered by code in __main__”, and a hook inside a library is not __main__, so that warning would stay invisible. The second choice is a stronger subclass, ApiSunsetSoonWarning, for the last 30 days. A warning that is only a warning gets ignored; one that can fail a build gets read.
The code
# clientguard.py
"""Make your own HTTP client notice Deprecation and Sunset headers (requests and httpx hook)."""
import re
import warnings
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
SF_DATE = re.compile(r"@(-?\d{1,15})")
LINK = re.compile(r'<([^>]*)>\s*;\s*rel="?([a-z-]+)"?')
class ApiDeprecationWarning(UserWarning):
"""The API says this endpoint is deprecated."""
class ApiSunsetSoonWarning(ApiDeprecationWarning):
"""The endpoint is deprecated and its sunset date is close."""
def parse_deprecation(value):
"""RFC 9745: the value is an sf-date such as @1688169599. Anything else gives None."""
match = SF_DATE.fullmatch(value.strip())
if match is None:
return None
try:
return datetime.fromtimestamp(int(match.group(1)), tz=timezone.utc)
except (OverflowError, OSError, ValueError):
return None
def parse_sunset(value):
"""RFC 8594: an HTTP-date. Python's parser also accepts the 'UTC' spelling used in RFC 9745's example."""
try:
moment = parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
if moment.tzinfo is None:
return moment.replace(tzinfo=timezone.utc)
return moment.astimezone(timezone.utc)
@dataclass(frozen=True)
class Notice:
text: str
soon: bool
def check_headers(headers, method, url, now=None, soon_days=30):
raw_deprecation = headers.get("Deprecation")
raw_sunset = headers.get("Sunset")
if raw_deprecation is None and raw_sunset is None:
return None
now = now or datetime.now(timezone.utc)
since = parse_deprecation(raw_deprecation) if raw_deprecation is not None else None
sunset = parse_sunset(raw_sunset) if raw_sunset is not None else None
links = {rel: target for target, rel in LINK.findall(headers.get("Link", ""))}
parts = [f"{method} {url}"]
if raw_deprecation is not None and since is None:
parts.append(f"is deprecated (the value {raw_deprecation!r} is not an RFC 9745 date)")
elif since is not None and since > now:
parts.append(f"will be deprecated on {since:%Y-%m-%d}")
elif since is not None:
parts.append(f"has been deprecated since {since:%Y-%m-%d}")
else:
parts.append("is scheduled to stop working")
soon = False
if sunset is not None:
days = (sunset - now).total_seconds() / 86400
soon = days <= soon_days
parts.append(f"and stops working on {sunset:%Y-%m-%d} ({days:.0f} days left)")
if "successor-version" in links:
parts.append(f"use {links['successor-version']}")
if "deprecation" in links:
parts.append(f"read {links['deprecation']}")
return Notice(", ".join(parts), soon)
def utc_now():
return datetime.now(timezone.utc)
def make_hook(clock=utc_now, soon_days=30):
"""A response hook for requests (session.hooks['response']) and httpx (event_hooks['response'])."""
def hook(response, *args, **kwargs):
notice = check_headers(response.headers, response.request.method, str(response.url), clock(), soon_days)
if notice is not None:
category = ApiSunsetSoonWarning if notice.soon else ApiDeprecationWarning
warnings.warn(notice.text, category, stacklevel=2)
return hook
warn_on_deprecation = make_hook()
parse_deprecation() accepts only a valid Structured Field Date: an @, an optional minus sign and up to 15 digits (the grammar in RFC 9651). Anything else returns None; a bad header must never break a working call. parse_sunset() uses Python’s e-mail date parser, which accepts the GMT form and the UTC form from RFC 9745’s example. check_headers() builds one sentence that names the endpoint, the dates, the days left, the successor and the guide, and says whether the sunset is within soon_days. make_hook() wraps it as a response hook. It takes a clock, so a test can say what “now” is.
Run it
One hook works for both libraries. requests takes it in session.hooks["response"] and httpx in event_hooks:
# step04_guard.py
"""Make a requests session and an httpx client notice the headers."""
import warnings
from datetime import datetime
import httpx
import requests
from clientguard import make_hook
from serve import server
NOW = "2027-01-10T12:00:00+00:00"
hook = make_hook(clock=lambda: datetime.fromisoformat(NOW))
def show(label, call):
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
status = call().status_code
print(f"{label}: HTTP {status}, {len(caught)} warning(s)")
for item in caught:
print(f" {item.category.__name__}: {item.message}")
with server("app:app", 8783, LAB_NOW=NOW) as base:
plain = requests.Session()
show("plain requests, /v1", lambda: plain.get(base + "/v1/orders/7", timeout=5))
guarded = requests.Session()
guarded.hooks["response"].append(hook)
show("guarded requests, /v1", lambda: guarded.get(base + "/v1/orders/7", timeout=5))
show("guarded requests, /v2", lambda: guarded.get(base + "/v2/orders/7", timeout=5))
with httpx.Client(event_hooks={"response": [hook]}) as client:
show("guarded httpx, /v1", lambda: client.get(base + "/v1/orders/7", timeout=5))
.venv/Scripts/python step04_guard.py
plain requests, /v1: HTTP 200, 0 warning(s)
guarded requests, /v1: HTTP 200, 1 warning(s)
ApiDeprecationWarning: GET http://127.0.0.1:8783/v1/orders/7, has been deprecated since 2026-12-01, and stops working on 2027-06-01 (142 days left), use /v2/orders/7, read https://api.example.com/docs/orders-v2-migration
guarded requests, /v2: HTTP 200, 0 warning(s)
guarded httpx, /v1: HTTP 200, 1 warning(s)
ApiDeprecationWarning: GET http://127.0.0.1:8783/v1/orders/7, has been deprecated since 2026-12-01, and stops working on 2027-06-01 (142 days left), use /v2/orders/7, read https://api.example.com/docs/orders-v2-migration
The plain session prints nothing, which matches Step 1. The guarded session warns on /v1, once per call, and stays silent on /v2. The message names everything a developer needs to act: what is deprecated, since when, how many days are left, where to go instead and what to read. (The count says 142 days because the 141.5 days between January 10 at noon and the sunset round up.)
Turn the warning into a build gate
Now imagine this is the test suite of an application that still calls v1. pytest’s documentation shows how to treat a warning class as an error: “how to treat any UserWarning category class of warning as an error” with -W error::UserWarning. Use the narrower class, so that only the close-to-sunset case fails:
# consumer/test_orders_client.py
"""Pretend this is a client application's own test suite. LAB_NOW sets the API's clock."""
import os
from datetime import datetime
from fastapi.testclient import TestClient
from app import create_app
from clientguard import make_hook
def client():
moment = datetime.fromisoformat(os.environ["LAB_NOW"])
api = TestClient(create_app(clock=lambda: moment))
api.event_hooks["response"].append(make_hook(clock=lambda: moment))
return api
def test_total_with_the_old_endpoint():
assert client().get("/v1/orders/7").json()["total"] == 12.5
def test_total_with_the_new_endpoint():
assert client().get("/v2/orders/7").json()["total_cents"] == 1250
The test builds the client with the clock of the pretend API, so that you can run it on any date. Run it twice, 92 days and 22 days before the sunset:
export LAB_NOW=2027-03-01T12:00:00+00:00
.venv/Scripts/python -m pytest -q --tb=line consumer -W error::clientguard.ApiSunsetSoonWarning
export LAB_NOW=2027-05-10T12:00:00+00:00
.venv/Scripts/python -m pytest -q --tb=line consumer -W error::clientguard.ApiSunsetSoonWarning
The first run, 92 days out:
.. [100%]
=== warnings summary ===
consumer/test_orders_client.py::test_total_with_the_old_endpoint
.venv\Lib\site-packages\httpx2\_client.py:1040: ApiDeprecationWarning: GET http://testserver/v1/orders/7, has been deprecated since 2026-12-01, and stops working on 2027-06-01 (92 days left), use /v2/orders/7, read https://api.example.com/docs/orders-v2-migration
hook(response)
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
2 passed, 1 warning in 0.20s
It passes and shows the warning in pytest’s summary. The second run, 22 days out, with the same command:
F. [100%]
=== FAILURES ===
E clientguard.ApiSunsetSoonWarning: GET http://testserver/v1/orders/7, has been deprecated since 2026-12-01, and stops working on 2027-06-01 (22 days left), use /v2/orders/7, read https://api.example.com/docs/orders-v2-migration
clientguard.py:90: clientguard.ApiSunsetSoonWarning: GET http://testserver/v1/orders/7, has been deprecated since 2026-12-01, and stops working on 2027-06-01 (22 days left), use /v2/orders/7, read https://api.example.com/docs/orders-v2-migration
=== short test summary info ===
FAILED consumer/test_orders_client.py::test_total_with_the_old_endpoint - clientguard.ApiSunsetSoonWarning: GET http://testserver/v1/orders/7, has been deprecated sinc...
1 failed, 1 passed in 0.20s
The test that uses v1 now fails, which is exactly the moment you want a team to hear about it, while 22 days remain. The test that uses v2 still passes. The gate costs you one command-line flag.
The unit tests cover the parsers, the 30-day boundary and the hook:
# test_clientguard.py
from types import SimpleNamespace
import pytest
from clientguard import (
ApiDeprecationWarning,
ApiSunsetSoonWarning,
check_headers,
make_hook,
parse_deprecation,
parse_sunset,
warn_on_deprecation,
)
from lifecycle import utc
NOW = utc(2027, 1, 10, 12)
FULL = {
"Deprecation": "@1796083200",
"Sunset": "Tue, 01 Jun 2027 00:00:00 GMT",
"Link": '<https://api.example.com/docs/orders-v2-migration>; rel="deprecation"; type="text/html", </v2/orders/7>; rel="successor-version"',
}
def test_an_sf_date_is_parsed():
assert parse_deprecation("@1796083200") == utc(2026, 12, 1)
assert parse_deprecation("@-1") == utc(1969, 12, 31, 23, 59, 59)
@pytest.mark.parametrize("value", ["true", "Fri, 30 Jun 2023 23:59:59 GMT", "1796083200", "@12.5", "@", "@9999999999999999"])
def test_values_that_are_not_an_sf_date_are_rejected(value):
assert parse_deprecation(value) is None
def test_the_sunset_parser_accepts_gmt_and_the_utc_spelling_of_the_rfc_example():
assert parse_sunset("Sun, 30 Jun 2024 23:59:59 GMT") == utc(2024, 6, 30, 23, 59, 59)
assert parse_sunset("Sun, 30 Jun 2024 23:59:59 UTC") == utc(2024, 6, 30, 23, 59, 59)
assert parse_sunset("next week") is None
def test_the_notice_names_the_dates_the_successor_and_the_guide():
notice = check_headers(FULL, "GET", "http://x/v1/orders/7", now=NOW)
assert notice.text == (
"GET http://x/v1/orders/7, has been deprecated since 2026-12-01, and stops working on 2027-06-01 (142 days left), "
"use /v2/orders/7, read https://api.example.com/docs/orders-v2-migration"
)
assert notice.soon is False
def test_a_sunset_within_thirty_days_is_soon():
assert check_headers(FULL, "GET", "u", now=utc(2027, 5, 2)).soon is True
assert check_headers(FULL, "GET", "u", now=utc(2027, 5, 1, 23)).soon is False
def test_a_future_deprecation_date_is_an_announcement():
notice = check_headers({"Deprecation": "@1796083200"}, "GET", "u", now=utc(2026, 11, 22))
assert notice.text == "GET u, will be deprecated on 2026-12-01"
def test_a_legacy_true_value_still_warns_but_says_why():
notice = check_headers({"Deprecation": "true"}, "GET", "u", now=NOW)
assert "'true' is not an RFC 9745 date" in notice.text
def test_a_sunset_alone_is_enough_to_warn():
notice = check_headers({"Sunset": FULL["Sunset"]}, "GET", "u", now=NOW)
assert notice.text.startswith("GET u, is scheduled to stop working, and stops working on 2027-06-01")
def test_a_response_without_the_headers_is_silent():
assert check_headers({"Content-Type": "application/json"}, "GET", "u", now=NOW) is None
def fake_response(headers):
return SimpleNamespace(headers=headers, request=SimpleNamespace(method="GET"), url="http://x/v1/orders/7")
def test_the_hook_warns_with_the_plain_category_when_the_sunset_is_far():
with pytest.warns(ApiDeprecationWarning) as caught:
make_hook(clock=lambda: NOW)(fake_response(FULL))
assert caught[0].category is ApiDeprecationWarning
def test_the_hook_escalates_to_the_sunset_soon_category_close_to_the_sunset():
with pytest.warns(ApiSunsetSoonWarning):
make_hook(clock=lambda: utc(2027, 5, 10))(fake_response(FULL))
def test_the_escalation_threshold_can_be_changed():
with pytest.warns(ApiDeprecationWarning) as caught:
make_hook(clock=lambda: utc(2027, 5, 10), soon_days=7)(fake_response(FULL))
assert caught[0].category is ApiDeprecationWarning
def test_the_default_hook_uses_the_real_clock():
with pytest.warns(ApiSunsetSoonWarning):
warn_on_deprecation(fake_response({**FULL, "Sunset": "Mon, 02 Jan 2012 00:00:00 GMT"}))
def test_the_escalated_warning_is_still_a_deprecation_warning():
assert issubclass(ApiSunsetSoonWarning, ApiDeprecationWarning)
.venv/Scripts/python -m pytest -q test_clientguard.py
................... [100%]
19 passed in 0.02s
Check it worked
- The first gate run exits 0 with one warning; the second exits 1 and names the sunset date and the days left.
- A value such as
true, an HTTP date in theDeprecationheader, or@12.5returnsNoneand does not raise.
Common mistakes
- Subclassing
DeprecationWarningfor a message that people must see. - Hooking one
Sessionand forgetting the others. Put the hook in the one place that builds your clients. - Letting the hook raise on a header it cannot parse. A hint must never turn a working request into a failure.
Step 5: Find out who still calls the endpoint
The idea
Warnings reach the clients that run code you control. The rest, partner scripts, old mobile apps and forgotten cron jobs, often do not read your headers. To find them you have to count. The ledger stores one row per hour, route, client and phase, with a call count. It also counts the 410 answers, because a client that keeps calling a dead endpoint is the one you most need to know about.
The code
# ledger.py
"""Who still calls a retiring route: one row per hour, route, client and phase."""
import sqlite3
import threading
def hour_key(moment):
return moment.strftime("%Y-%m-%dT%H")
class Ledger:
def __init__(self, path=":memory:"):
self.db = sqlite3.connect(path, check_same_thread=False)
self.lock = threading.Lock()
with self.lock, self.db:
self.db.execute(
"CREATE TABLE IF NOT EXISTS usage ("
" hour TEXT NOT NULL, route TEXT NOT NULL, client TEXT NOT NULL, phase TEXT NOT NULL,"
" calls INTEGER NOT NULL, PRIMARY KEY (hour, route, client, phase)) WITHOUT ROWID"
)
def record(self, moment, route, client, phase):
with self.lock, self.db:
self.db.execute(
"INSERT INTO usage VALUES (?, ?, ?, ?, 1)"
" ON CONFLICT (hour, route, client, phase) DO UPDATE SET calls = calls + 1",
(hour_key(moment), route, client, phase),
)
def report(self, route, until=None):
"""One row per client: total calls, first hour seen, last hour seen, newest first."""
limit = hour_key(until) if until else "9999"
with self.lock:
return self.db.execute(
"SELECT client, SUM(calls), MIN(hour), MAX(hour) FROM usage"
" WHERE route = ? AND hour <= ? GROUP BY client ORDER BY MAX(hour) DESC, client",
(route, limit),
).fetchall()
def callers_between(self, route, since, until):
with self.lock:
rows = self.db.execute(
"SELECT DISTINCT client FROM usage WHERE route = ? AND hour > ? AND hour <= ? ORDER BY client",
(route, hour_key(since), hour_key(until)),
).fetchall()
return [client for (client,) in rows]
The table’s primary key is the combination of hour, route, client and phase, and INSERT ... ON CONFLICT ... DO UPDATE adds one to the count of an existing row. One lock protects the shared SQLite connection, because FastAPI runs ordinary functions in a pool of threads. report() lists one line per client, newest first. callers_between() answers “who called in this period?”, with an open start and a closed end.
This script plays two weeks of traffic from three clients through the real app, with a clock you can move:
# step05_ledger.py
"""Count who calls the deprecated route. Three clients, a mutable clock, two weeks."""
from datetime import timedelta
from fastapi.testclient import TestClient
from app import create_app
from ledger import Ledger
from lifecycle import utc
ROUTE = "GET /v1/orders/{order_id}"
now = {"value": utc(2027, 1, 10, 12)}
ledger = Ledger()
api = TestClient(create_app(clock=lambda: now["value"], ledger=ledger))
for day in range(14):
now["value"] = utc(2027, 1, 10, 2) + timedelta(days=day)
api.get("/v1/orders/7", headers={"X-Client-Id": "mobile-app"})
if day % 7 == 0:
api.get("/v1/orders/7", headers={"X-Client-Id": "weekly-report"})
if day == 4:
api.get("/v1/orders/7", headers={"User-Agent": "legacy-importer/0.9"})
if day == 9:
api.get("/v2/orders/7", headers={"X-Client-Id": "mobile-app"})
print(f"{'client':<16}{'calls':>6} {'first hour seen':<16} last hour seen")
for client, calls, first, last in ledger.report(ROUTE):
print(f"{client:<16}{calls:>6} {first:<16} {last}")
print()
print("callers in the 7 days up to 2027-01-23 00:00:", ledger.callers_between(ROUTE, utc(2027, 1, 16), utc(2027, 1, 23)))
print("callers in the 3 days up to 2027-01-23 00:00:", ledger.callers_between(ROUTE, utc(2027, 1, 20), utc(2027, 1, 23)))
.venv/Scripts/python step05_ledger.py
client calls first hour seen last hour seen
mobile-app 14 2027-01-10T02 2027-01-23T02
weekly-report 2 2027-01-10T02 2027-01-17T02
legacy-importer 1 2027-01-14T02 2027-01-14T02
callers in the 7 days up to 2027-01-23 00:00: ['mobile-app', 'weekly-report']
callers in the 3 days up to 2027-01-23 00:00: ['mobile-app']
The mobile app calls every day, the weekly report calls once a week, and an importer that identifies itself only by its User-Agent appears once. The call that went to /v2 is not in the table, which is correct: the ledger watches only the route that is being retired.
The ledger gets its own tests. They pin the one-row-per-hour rule, the newest-first order, the open start and closed end of callers_between() (an off-by-one there would change which clients a quiet-days rule sees) and eight threads writing at once:
# test_ledger.py
import threading
from ledger import Ledger
from lifecycle import utc
ROUTE = "GET /v1/orders/{order_id}"
def test_calls_in_the_same_hour_share_a_row():
ledger = Ledger()
for minute in (1, 30, 59):
ledger.record(utc(2027, 1, 10, 12, minute), ROUTE, "mobile-app", "deprecated")
ledger.record(utc(2027, 1, 10, 13), ROUTE, "mobile-app", "deprecated")
assert ledger.report(ROUTE) == [("mobile-app", 4, "2027-01-10T12", "2027-01-10T13")]
def test_the_report_lists_the_newest_caller_first_and_can_stop_at_a_date():
ledger = Ledger()
ledger.record(utc(2027, 1, 5, 2), ROUTE, "old-script", "deprecated")
ledger.record(utc(2027, 2, 5, 2), ROUTE, "new-script", "deprecated")
assert [row[0] for row in ledger.report(ROUTE)] == ["new-script", "old-script"]
assert [row[0] for row in ledger.report(ROUTE, until=utc(2027, 1, 31))] == ["old-script"]
def test_callers_between_uses_an_open_start_and_a_closed_end():
ledger = Ledger()
ledger.record(utc(2027, 1, 5, 2), ROUTE, "a", "deprecated")
ledger.record(utc(2027, 1, 12, 2), ROUTE, "b", "deprecated")
assert ledger.callers_between(ROUTE, utc(2027, 1, 5, 2), utc(2027, 1, 12, 2)) == ["b"]
assert ledger.callers_between(ROUTE, utc(2027, 1, 5, 1), utc(2027, 1, 12, 1)) == ["a"]
def test_other_routes_do_not_mix():
ledger = Ledger()
ledger.record(utc(2027, 1, 5, 2), "GET /v1/other", "a", "deprecated")
assert ledger.report(ROUTE) == []
def test_concurrent_calls_are_all_counted():
ledger = Ledger()
threads = [threading.Thread(target=lambda: [ledger.record(utc(2027, 1, 5, 2), ROUTE, "a", "deprecated") for _ in range(50)]) for _ in range(8)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert ledger.report(ROUTE)[0][1] == 400
.venv/Scripts/python -m pytest -q test_ledger.py
..... [100%]
5 passed in 0.02s
Why “nobody called for N days” is a dangerous rule
It is tempting to remove the endpoint as soon as the ledger shows a quiet spell. The next script tests that rule against a calendar model with five callers. Please read it as an illustration. The callers and their schedules are invented, and the numbers are consequences of those assumptions, not a forecast:
mobile-appcalls every day at 02:00 and moves to v2 on January 15 (its owner reads release notes).partner-synccalls every day at 06:00 and moves on February 20 (its owner got an e-mail).weekly-reportcalls on Mondays at 03:00 and moves on March 2 (its owner reads the warnings).billing-exportcalls on the 28th of each month at 23:30 and is never moved unless it breaks.quarter-auditcalls on the last day of each quarter at 22:00 and is never moved unless it breaks.
When a silent client gets a 410, its owner fixes it three days later. Three retirement plans run against the same callers: no brownouts, three business-hours brownouts, and two windows read off the ledger.
# simulate.py
"""A calendar model of five callers and three retirement plans. The schedules are assumptions, not measurements."""
from datetime import datetime, time, timedelta, timezone
from ledger import Ledger
from lifecycle import Lifecycle, Window, utc
ROUTE = "GET /v1/orders/{order_id}"
DOC = "https://api.example.com/docs/orders-v2-migration"
DEPRECATED, SUNSET, END = utc(2026, 12, 1), utc(2027, 6, 1), utc(2027, 7, 15)
FIX_DAYS = 3
def last_day_of_quarter(day):
return day.month in (3, 6, 9, 12) and (day + timedelta(days=1)).day == 1
# name: (time of day the job calls on a given date or None, when its owner moves it to /v2 or None)
CLIENTS = {
"mobile-app": (lambda d: time(2, 0), utc(2027, 1, 15)),
"partner-sync": (lambda d: time(6, 0), utc(2027, 2, 20)),
"weekly-report": (lambda d: time(3, 0) if d.weekday() == 0 else None, utc(2027, 3, 2)),
"billing-export": (lambda d: time(23, 30) if d.day == 28 else None, None),
"quarter-audit": (lambda d: time(22, 0) if last_day_of_quarter(d) else None, None),
}
PLANS = {
"A no brownouts": [],
"B three 10:00 to 12:00 brownouts": [Window(utc(2027, m, d, 10), utc(2027, m, d, 12)) for m, d in ((4, 6), (5, 4), (5, 18))],
"C windows read off the ledger": [Window(utc(2027, 3, 28, 23), utc(2027, 3, 29, 0)), Window(utc(2027, 3, 31, 21, 30), utc(2027, 3, 31, 22, 30))],
}
def run(brownouts):
lifecycle = Lifecycle(ROUTE, DEPRECATED, SUNSET, DOC, brownouts=tuple(brownouts))
ledger, moves, first_failure = Ledger(), {name: moved for name, (_, moved) in CLIENTS.items()}, {}
day = DEPRECATED.date()
while day <= END.date():
for name, (runs_at, _) in CLIENTS.items():
at = runs_at(day)
when = datetime.combine(day, at, tzinfo=timezone.utc) if at else None
if when is None or (moves[name] is not None and when >= moves[name]):
continue
phase = lifecycle.phase(when)
ledger.record(when, ROUTE, name, phase)
if phase in ("brownout", "gone") and name not in first_failure:
first_failure[name] = (when, phase)
fix = when + timedelta(days=FIX_DAYS)
moves[name] = fix if moves[name] is None else min(moves[name], fix)
day += timedelta(days=1)
return ledger, first_failure
if __name__ == "__main__":
print(f"Model: deprecation {DEPRECATED:%Y-%m-%d}, sunset {SUNSET:%Y-%m-%d}; an owner fixes a client {FIX_DAYS} days after its first 410.")
print("Silent callers: billing-export (28th, 23:30 UTC) and quarter-audit (last day of the quarter, 22:00 UTC).")
print()
ledgers = {}
for plan, windows in PLANS.items():
ledger, failures = run(windows)
ledgers[plan] = ledger
print(f"Plan {plan}")
for name in ("billing-export", "quarter-audit"):
if name in failures:
when, phase = failures[name]
if phase == "brownout":
timing = f"{(SUNSET - when).days} days before the sunset: caught in a brownout"
else:
timing = f"{(when - SUNSET).days} days after the sunset: OUTAGE"
print(f" {name:<15} first 410 on {when:%Y-%m-%d %H:%M}, {timing}")
else:
print(f" {name:<15} never fails")
print()
ledger = ledgers["A no brownouts"]
check = utc(2027, 3, 20)
print(f"Ledger report on {check:%Y-%m-%d} (plan A):")
for client, calls, first, last in ledger.report(ROUTE, until=check):
print(f" {client:<15}{calls:>4} calls, first seen {first}, last seen {last}")
print()
print("When does a quiet-days rule say the route is unused, and who calls after that?")
for quiet in (7, 14, 35, 100):
day, ready = DEPRECATED + timedelta(days=quiet), None
while day <= SUNSET:
if not ledger.callers_between(ROUTE, day - timedelta(days=quiet), day):
ready = day
break
day += timedelta(days=1)
if ready is None:
print(f" quiet for {quiet:>3} days: never before the sunset")
else:
later = ledger.callers_between(ROUTE, ready, END)
print(f" quiet for {quiet:>3} days: first true on {ready:%Y-%m-%d}; still calling afterwards: {', '.join(later)}")
.venv/Scripts/python simulate.py
Model: deprecation 2026-12-01, sunset 2027-06-01; an owner fixes a client 3 days after its first 410.
Silent callers: billing-export (28th, 23:30 UTC) and quarter-audit (last day of the quarter, 22:00 UTC).
Plan A no brownouts
billing-export first 410 on 2027-06-28 23:30, 27 days after the sunset: OUTAGE
quarter-audit first 410 on 2027-06-30 22:00, 29 days after the sunset: OUTAGE
Plan B three 10:00 to 12:00 brownouts
billing-export first 410 on 2027-06-28 23:30, 27 days after the sunset: OUTAGE
quarter-audit first 410 on 2027-06-30 22:00, 29 days after the sunset: OUTAGE
Plan C windows read off the ledger
billing-export first 410 on 2027-03-28 23:30, 64 days before the sunset: caught in a brownout
quarter-audit first 410 on 2027-03-31 22:00, 61 days before the sunset: caught in a brownout
Ledger report on 2027-03-20 (plan A):
weekly-report 13 calls, first seen 2026-12-07T03, last seen 2027-03-01T03
billing-export 3 calls, first seen 2026-12-28T23, last seen 2027-02-28T23
partner-sync 81 calls, first seen 2026-12-01T06, last seen 2027-02-19T06
mobile-app 45 calls, first seen 2026-12-01T02, last seen 2027-01-14T02
quarter-audit 1 calls, first seen 2026-12-31T22, last seen 2026-12-31T22
When does a quiet-days rule say the route is unused, and who calls after that?
quiet for 7 days: first true on 2027-03-09; still calling afterwards: billing-export, quarter-audit
quiet for 14 days: first true on 2027-03-16; still calling afterwards: billing-export, quarter-audit
quiet for 35 days: never before the sunset
quiet for 100 days: never before the sunset
Reading the model
Look at the last block first. A rule that says “no calls for 14 days” becomes true on March 16, after the weekly report has moved, while billing-export and quarter-audit are still on v1. Remove the endpoint then and both jobs break. The cause is the calendar: a monthly job is quiet for most of every month, and a quarterly one for most of a quarter. A 35-day rule never fires before the sunset, because the monthly job always calls inside 35 days, and a 100-day rule never fires either. So a ledger cannot tell you that it is safe to remove an endpoint. What it can do is show the hours at which each client calls, and that is what the report in the middle gives you. On March 20 it cannot say who has moved and who is merely between runs, but it shows that billing-export called three times, first on December 28 and last on February 28, both at hour 23, and that quarter-audit called once, on December 31 at hour 22. Someone with a calendar can recognize a monthly job and a quarterly one.
Plan A, with no brownouts, finds out on June 28 and June 30, 27 and 29 days after the sunset, when the two jobs get their first 410: two production outages. Plan B has three brownouts at 10:00 on Tuesdays, a natural choice for a team that wants to be awake when it happens. Neither job calls at that hour, so the result equals plan A. Plan C schedules a window around each straggler’s hour, read off that report: March 28 from 23:00 to midnight and March 31 from 21:30 to 22:30 (the two windows already in app.py). Both jobs get their first 410 on March 28 and 31, 64 and 61 days before the sunset, while the endpoint can still be turned back on. The lesson is that the timing of a brownout matters more than the number of them.
Check it worked
- The ledger report lists
legacy-importeralthough it never sent anX-Client-Idheader: the User-Agent fallback worked. - The model prints the same three plans and the same quiet-day results on every run, because it has no randomness.
Common mistakes
- Counting only successful calls. After the sunset, the clients that fail are the ones you most need to see.
- Identifying callers by IP address. Shared gateways, mobile networks and proxies hide who is behind an address. Ask clients to send an identifier, and prefer API keys.
- Choosing a quiet-days window shorter than your slowest caller’s cycle. If you have a quarterly job, a rule shorter than a quarter will approve a removal too early.
- Storing more than you need. The ledger has hours, routes, client names and counts, and no addresses or request bodies.
Step 6: Run brownouts, then leave a tombstone
The idea
A brownout is a rehearsal of the sunset. For a few hours the endpoint answers 410 Gone, with a problem document that says what is happening, when it ends and where to go. Callers that never read a header or a guide suddenly have a failing job and a message in their logs. Neither RFC asks for this. RFC 9745 even says that deprecation changes no behavior of the resource, which is why a brownout is an operations technique that you announce yourself, by e-mail and in the guide, a few days ahead.
Why 410 and not 503? A 503 says that the service is temporarily unavailable, so alerting rules and retry policies treat it as a problem on your side. Picture a client that retries 502, 503 and 504, which is a setup urllib3 supports. Its documentation describes the status_forcelist setting as “A set of integer HTTP status codes that we should force a retry on.” That client retries a 503 before it gives up, which can hide a short brownout completely. A 410 is not on that list, so the first attempt already fails, and the status says that the resource is gone, which is the message you are rehearsing. For the time after the sunset, RFC 8594 says it is likely that “interactions with the resource will result in client-side errors (HTTP 4xx status codes), redirect responses (HTTP 3xx status codes), or the client might not be able to interact with the resource at all”, so a 4xx status matches what clients were told to expect.
Run it
You already wrote the brownout and the tombstone in Step 3: retire.py and the windows in app.py. This script freezes the server’s clock inside the March 28 window, then on the day after the sunset, and prints what curl sees. It also checks the retry claim directly on urllib3’s Retry class:
# step06_retire.py
"""A brownout and the day after the sunset, seen from curl."""
import subprocess
from urllib3 import Retry
from serve import server
def curl(base, path, *extra):
result = subprocess.run(["curl", "-si", *extra, base + path], capture_output=True, text=True, encoding="utf-8")
return "\n".join(line for line in result.stdout.splitlines() if not line.lower().startswith("date:"))
for label, now, port in (("inside the March 28 brownout", "2027-03-28T23:30:00+00:00", 8784), ("the day after the sunset", "2027-06-02T09:00:00+00:00", 8785)):
with server("app:app", port, LAB_NOW=now) as base:
print(f"=== {label} (server clock {now}) ===")
print(curl(base, "/v1/orders/7", "-H", "X-Client-Id: billing-export"))
print("-- and /v2 is untouched:", curl(base, "/v2/orders/7").splitlines()[0])
print()
retry = Retry(total=3, status_forcelist=[502, 503, 504])
print("Does a typical urllib3 retry policy (status_forcelist 502, 503, 504) retry it?")
for status in (503, 410):
print(f" {status}: {retry.is_retry('GET', status)}")
.venv/Scripts/python step06_retire.py
=== inside the March 28 brownout (server clock 2027-03-28T23:30:00+00:00) ===
HTTP/1.1 410 Gone
server: uvicorn
cache-control: no-store
content-length: 317
content-type: application/problem+json
deprecation: @1796083200
sunset: Tue, 01 Jun 2027 00:00:00 GMT
link: <https://api.example.com/docs/orders-v2-migration>; rel="deprecation"; type="text/html", </v2/orders/7>; rel="successor-version"
{"type":"https://api.example.com/docs/orders-v2-migration","status":410,"sunset":"2027-06-01T00:00:00Z","title":"Scheduled brownout of a retiring endpoint","detail":"This endpoint is retired on 2027-06-01. It is switched off until the brownout ends.","brownout_ends":"2027-03-29T00:00:00Z","successor":"/v2/orders/7"}
-- and /v2 is untouched: HTTP/1.1 200 OK
=== the day after the sunset (server clock 2027-06-02T09:00:00+00:00) ===
HTTP/1.1 410 Gone
server: uvicorn
cache-control: no-store
content-length: 224
content-type: application/problem+json
deprecation: @1796083200
sunset: Tue, 01 Jun 2027 00:00:00 GMT
link: <https://api.example.com/docs/orders-v2-migration>; rel="deprecation"; type="text/html", </v2/orders/7>; rel="successor-version"
{"type":"https://api.example.com/docs/orders-v2-migration","status":410,"sunset":"2027-06-01T00:00:00Z","title":"This endpoint has been retired","detail":"This endpoint was retired on 2027-06-01.","successor":"/v2/orders/7"}
-- and /v2 is untouched: HTTP/1.1 200 OK
Does a typical urllib3 retry policy (status_forcelist 502, 503, 504) retry it?
503: True
410: False
Reading the result
Both answers are 410 Gone with content-type: application/problem+json and cache-control: no-store. The sunset and link headers are still there, so even a failing call points at the date and the guide, and the body names the successor. The brownout body adds brownout_ends, so that nobody has to guess whether this is the real thing. After the sunset the title changes to “This endpoint has been retired”. /v2 answers normally in both cases. The last two lines show the retry mechanics: a policy that retries 502, 503 and 504 retries a 503 and does not retry a 410. That is a statement about the policy’s code, not about your clients; check the policy that yours use.
How long should the tombstone stay? There is no standard. A sensible rule is at least as long as the slowest caller’s cycle: in the model above, one quarter. After that, delete the route and let the framework answer 404. RFC 9110 leaves it to you: it says it is not necessary to mark every permanently unavailable resource as gone, or “to keep the mark for any length of time”.
Check it worked
- Inside the window and after the sunset the status is 410 and
cache-controlisno-store; outside them it is 200. - The brownout body has
brownout_ends; the tombstone body does not.
Common mistakes
- Starting brownouts a week before the sunset. A brownout that finds a client needs time to be fixed, so start at least a couple of months out.
- Springing a brownout on callers without telling them. The first one should be announced, short and in working hours for your team, then lengthen or move them.
- Using 503 for a brownout. Clients that retry 503 can ride out a short one without noticing it.
Step 7: Refuse an early removal in CI
The idea
Everything so far lives in the running service. One risk is left: a developer deletes the route in a pull request, months before the sunset, because it looks dead. The OpenAPI document that FastAPI generates shows that change, and a comparison tool can block it. oasdiff reads the deprecated flag and the x-sunset field you set in Step 3. Its documentation says what it does with them: “At the sunset date or later, the removal isn’t reported at all.” Before that date, removing the endpoint is an error. It can also enforce a minimum notice, with --deprecation-days-stable, which it describes as “the minimal number of days required between deprecating a resource and removing it.”
The code
The script takes the OpenAPI document of the retiring app and edits copies of it into nine situations a pull request could cause, then asks oasdiff for a verdict on each. The base and the revision are real files, and the dates are relative to the day you run it, so the table below is the same on any day:
# oas_cases.py
"""Gate the API contract with oasdiff: nine edits to the OpenAPI document, one verdict each."""
import copy
import json
import os
import shutil
import subprocess
from datetime import datetime, timedelta, timezone
from pathlib import Path
from app import create_app
from lifecycle import utc
OASDIFF = os.environ.get("OASDIFF") or shutil.which("oasdiff") or "oasdiff"
V1 = "/v1/orders/{order_id}"
LEVELS = {1: "info", 2: "warn", 3: "ERR"}
OUT = Path("oas")
OUT.mkdir(exist_ok=True)
retiring = create_app(clock=lambda: utc(2027, 1, 10)).openapi()
def variant(sunset_in_days=None, deprecated=True, removed=False):
spec = copy.deepcopy(retiring)
if removed:
del spec["paths"][V1]
return spec
operation = spec["paths"][V1]["get"]
operation.pop("x-sunset")
if not deprecated:
operation.pop("deprecated")
if sunset_in_days is not None:
operation["x-sunset"] = (datetime.now(timezone.utc).date() + timedelta(days=sunset_in_days)).isoformat()
return spec
def compare(base, revision, name, *flags):
paths = []
for tag, spec in (("base", base), ("revision", revision)):
path = OUT / f"{name}_{tag}.json"
path.write_text(json.dumps(spec, indent=2), encoding="utf-8")
paths.append(str(path))
command = [OASDIFF, "breaking", *paths, "--fail-on", "ERR", "--deprecation-days-stable", "180", "--format", "json", *flags]
result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8")
findings = json.loads(result.stdout or "[]")
return result.returncode, [f"{LEVELS[item['level']]} {item['id']}" for item in findings]
CASES = [
("announce with 200 days of notice", variant(deprecated=False, sunset_in_days=None), variant(sunset_in_days=200)),
("announce with 170 days of notice", variant(deprecated=False, sunset_in_days=None), variant(sunset_in_days=170)),
("announce with 30 days of notice", variant(deprecated=False, sunset_in_days=None), variant(sunset_in_days=30)),
("deprecate without an x-sunset date", variant(deprecated=False, sunset_in_days=None), variant(sunset_in_days=None)),
("remove without deprecating first", variant(deprecated=False, sunset_in_days=None), variant(removed=True)),
("remove 20 days before the sunset", variant(sunset_in_days=20), variant(removed=True)),
("remove the day after the sunset", variant(sunset_in_days=-1), variant(removed=True)),
("move the sunset 100 days earlier", variant(sunset_in_days=300), variant(sunset_in_days=200)),
("move the sunset 100 days later", variant(sunset_in_days=200), variant(sunset_in_days=300)),
]
if __name__ == "__main__":
for number, (title, base, revision) in enumerate(CASES, 1):
code, findings = compare(base, revision, f"case{number}")
print(f"{number:>2}. {title:<36} exit {code} {'; '.join(findings) or 'no findings'}")
.venv/Scripts/python oas_cases.py
1. announce with 200 days of notice exit 0 no findings
2. announce with 170 days of notice exit 1 ERR api-sunset-date-too-small
3. announce with 30 days of notice exit 1 ERR api-sunset-date-too-small
4. deprecate without an x-sunset date exit 1 ERR api-deprecated-sunset-missing
5. remove without deprecating first exit 1 ERR api-path-removed-without-deprecation
6. remove 20 days before the sunset exit 1 ERR api-path-removed-before-sunset
7. remove the day after the sunset exit 0 no findings
8. move the sunset 100 days earlier exit 1 ERR api-sunset-date-changed-earlier
9. move the sunset 100 days later exit 0 no findings
Reading the table
Each row is a change a pull request could make. Announcing with 200 days of notice passes the 180-day rule. Announcing with 170 or 30 days fails with api-sunset-date-too-small, and deprecating without an x-sunset date fails with api-deprecated-sunset-missing, because the rule makes the date mandatory. Removing the endpoint without ever deprecating it, or 20 days before its sunset, fails. Removing it the day after the sunset passes. Moving the sunset earlier fails with api-sunset-date-changed-earlier, and moving it later passes. I did not test a notice of exactly 180 days: the boundary day depends on how the tool counts days, so keep a margin. My routes had no x-stability-level, and oasdiff still held them to the rule, which its option name calls “stable”.
In your pipeline the comparison is one command. oasdiff can read the base document straight from a git revision (its help says a base can be “a git ref (e.g. main:openapi.yaml)”). Export the current document with the same clock your service uses, then compare:
.venv/Scripts/python -c "import json; from app import app; print(json.dumps(app.openapi(), indent=2))" > openapi.json
tools/oasdiff.exe breaking origin/main:openapi.json openapi.json --fail-on ERR --deprecation-days-stable 180
I ran the same shape of command in a throwaway git repository, with HEAD:openapi.json as the base and the edited file as the revision. It printed error [api-path-removed-without-deprecation] and exited with status 1, which fails a CI job. --fail-on ERR is what turns an error into that exit status.
Check it worked
- Three rows exit 0 and six exit 1, and each failing row names a check id.
- Your own pipeline fails when you delete a deprecated route before its
x-sunsetdate, and passes after it.
Common mistakes
- Exporting the OpenAPI document with a different clock than production. Before the deprecation date the route is not flagged, so the comparison sees a different document.
- Setting
x-sunsetin a format other than an RFC 3339 date. oasdiff reports a date it cannot parse. - Leaving out
--deprecation-days-stable. Without it the notice period is not enforced.
Step 8: Test the tests
The idea
Fifty-five tests pass. Do they protect anything? A mutation test answers that. It copies the lab, plants one deliberate bug, runs the tests and checks that at least one fails. A bug that no test notices is a hole in the suite. The script below plants 20 bugs, each a realistic mistake from the steps above: Deprecation: true instead of a date, +0000 instead of GMT, a 404 instead of a 410, a 410 without no-store, headers that vanish on errors, a ledger that skips the 410s, a brownout that includes its end instant.
# mutants.py
"""Plant one bug at a time in a copy of the lab and check that the tests notice."""
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
MUTANTS = [
("lifecycle.py", '"Deprecation": "@" + str(int(self.deprecated_at.timestamp())),', '"Deprecation": "true",', "Deprecation sent as the old boolean true"),
("lifecycle.py", "format_datetime(self.sunset_at, usegmt=True)", "format_datetime(self.sunset_at)", "Sunset sent with +0000 instead of GMT"),
("lifecycle.py", 'rel="successor-version"', 'rel="next"', "wrong link relation for the successor"),
("lifecycle.py", " if self.sunset_at < self.deprecated_at:", " if False:", "sunset may be earlier than deprecation"),
("lifecycle.py", " if self.sunset_at - self.deprecated_at < timedelta(days=self.min_notice_days):", " if False:", "no minimum notice period"),
("lifecycle.py", " if window.start < self.deprecated_at or window.end > self.sunset_at:", " if False:", "brownout outside the notice period"),
("lifecycle.py", " if moment.tzinfo != timezone.utc:", " if False:", "naive or local datetimes accepted"),
("lifecycle.py", " if now >= self.sunset_at:", " if now > self.sunset_at:", "sunset instant still served"),
("lifecycle.py", " return self.start <= now < self.end", " return self.start <= now <= self.end", "brownout end instant still blocked"),
("retire.py", 'headers={"Cache-Control": "no-store"}', "headers={}", "410 without Cache-Control: no-store"),
("retire.py", "status_code=410,", "status_code=404,", "404 instead of 410"),
("retire.py", 'options["openapi_extra"] = {"x-sunset": lifecycle.sunset_at.date().isoformat()}', 'options["openapi_extra"] = {"x-sunset": lifecycle.deprecated_at.date().isoformat()}', "x-sunset disagrees with the Sunset header"),
("retire.py", 'options["deprecated"] = True', 'options["deprecated"] = False', "OpenAPI deprecated flag lost"),
("retire.py", " request.app.state.ledger.record(moment, lifecycle.name, client_id(request), phase)", ' if phase in ("announced", "deprecated"):\n request.app.state.ledger.record(moment, lifecycle.name, client_id(request), phase)', "ledger skips the 410 attempts"),
("retire.py", 'for name, value in getattr(request.state, "retirement", {}).items():', 'for name, value in getattr(request.state, "retirement", {}).items() if response.status_code < 400 else []:', "headers missing on error responses"),
("retire.py", 'return (declared or agent or "anonymous")[:64]', 'return (declared or "anonymous")[:64]', "client named only by header"),
("clientguard.py", "soon = days <= soon_days", "soon = days < soon_days", "escalation boundary off by one"),
("clientguard.py", 'SF_DATE = re.compile(r"@(-?\\d{1,15})")', 'SF_DATE = re.compile(r"@?(-?\\d{1,15})")', "parser accepts a date without the @"),
("clientguard.py", " if raw_deprecation is None and raw_sunset is None:", " if raw_deprecation is None:", "a lone Sunset header ignored"),
("ledger.py", "AND hour > ? AND hour <= ?", "AND hour >= ? AND hour <= ?", "quiet-window start included"),
]
def pytest_in(folder):
env = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "COLUMNS": "170"}
result = subprocess.run([sys.executable, "-m", "pytest", "-q", "-x", "--no-header"], cwd=folder, capture_output=True, text=True, env=env)
failed = re.findall(r"^FAILED (\S+)", result.stdout, re.M)
return result.returncode, failed[0] if failed else ""
def fresh_copy(root):
target = Path(root) / "lab"
shutil.copytree(HERE, target, ignore=shutil.ignore_patterns("__pycache__", "oas", "out", "consumer", ".pytest_cache", "mutants.py"))
return target
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as root:
code, _ = pytest_in(fresh_copy(root))
print("control (no bug planted):", "tests pass" if code == 0 else "TESTS FAIL")
caught = 0
for number, (name, old, new, label) in enumerate(MUTANTS, 1):
with tempfile.TemporaryDirectory() as root:
folder = fresh_copy(root)
source = (folder / name).read_text(encoding="utf-8")
assert source.count(old) == 1, (name, old, source.count(old))
(folder / name).write_text(source.replace(old, new), encoding="utf-8")
code, test = pytest_in(folder)
caught += code != 0
print(f"{number:>2}. {'caught' if code else 'MISSED'} {label:<44} {test}")
print(f"{caught} of {len(MUTANTS)} planted bugs caught")
.venv/Scripts/python mutants.py
control (no bug planted): tests pass
1. caught Deprecation sent as the old boolean true test_api.py::test_v1_still_works_and_announces_its_retirement
2. caught Sunset sent with +0000 instead of GMT test_api.py::test_v1_still_works_and_announces_its_retirement
3. caught wrong link relation for the successor test_api.py::test_v1_still_works_and_announces_its_retirement
4. caught sunset may be earlier than deprecation test_lifecycle.py::test_sunset_before_deprecation_is_refused
5. caught no minimum notice period test_lifecycle.py::test_too_little_notice_is_refused
6. caught brownout outside the notice period test_lifecycle.py::test_a_brownout_must_fall_inside_the_notice_period
7. caught naive or local datetimes accepted test_lifecycle.py::test_only_utc_datetimes_are_accepted[moment0]
8. caught sunset instant still served test_lifecycle.py::test_phase_boundaries[now7-gone]
9. caught brownout end instant still blocked test_lifecycle.py::test_phase_boundaries[now5-deprecated]
10. caught 410 without Cache-Control: no-store test_api.py::test_a_brownout_answers_410_with_a_problem_document_that_is_never_cached
11. caught 404 instead of 410 test_api.py::test_a_brownout_answers_410_with_a_problem_document_that_is_never_cached
12. caught x-sunset disagrees with the Sunset header test_api.py::test_openapi_flag_and_x_sunset_agree_with_the_sunset_header
13. caught OpenAPI deprecated flag lost test_api.py::test_openapi_flag_and_x_sunset_agree_with_the_sunset_header
14. caught ledger skips the 410 attempts test_api.py::test_the_ledger_counts_every_attempt_including_the_410s
15. caught headers missing on error responses test_api.py::test_headers_also_reach_error_responses
16. caught client named only by header test_api.py::test_the_ledger_counts_every_attempt_including_the_410s
17. caught escalation boundary off by one test_clientguard.py::test_a_sunset_within_thirty_days_is_soon
18. caught parser accepts a date without the @ test_clientguard.py::test_values_that_are_not_an_sf_date_are_rejected[1796083200]
19. caught a lone Sunset header ignored test_clientguard.py::test_a_sunset_alone_is_enough_to_warn
20. caught quiet-window start included test_ledger.py::test_callers_between_uses_an_open_start_and_a_closed_end
20 of 20 planted bugs caught
The control run, with no bug planted, passes, so a failure is caused by the planted bug. Every one of the 20 bugs is caught, and the output names the first test that failed for each (the script stops a run at its first failure). If a mutant survives in your copy, the output prints MISSED and the name of the bug, and you know which test to write.
Step 9: Put it together
Run everything once
.venv/Scripts/python -m pytest -q
....................................................... [100%]
55 passed in 0.29s
All 55 tests pass. The two gate runs, the nine oasdiff verdicts and the 20 mutants were already shown in their steps. Together they cover each stage of the retirement.
A schedule you can adapt
These dates are the lab’s example, not a standard. The notice period and the number of brownouts are decisions for your own callers:
| Date | What happens | Where it is enforced |
|---|---|---|
| December 1, 2026 | Deprecation: headers, OpenAPI flag with x-sunset, guide published, e-mail sent |
Lifecycle, retire(), oasdiff |
| December to March | Teams migrate; clients warn; the ledger is read every week | clientguard.py, ledger.py |
| Late March | Brownouts around the hours the ledger shows | Window in the lifecycle |
| June 1, 2027 | Sunset: 410 tombstone, hidden from the docs | phase() is gone |
| After a full cycle of the slowest caller | Delete the tombstone; the route answers 404 | pull request, oasdiff already passes |
A checklist for your own API
- Write the migration guide first. The headers point at it. freeCodeCamp’s article is a good template for that document.
- Describe the retirement in one object with UTC dates and a notice period you are willing to promise.
- Send
Deprecation,SunsetandLinkon every response from the route, errors included, and flag the operation in OpenAPI withx-sunset. - Put the warning hook in every client you control and gate your own tests on the sunset-soon warning.
- Count callers by a client id, including the 410s, and read the report weekly.
- Announce and run brownouts around the hours of the stragglers, starting months before the sunset.
- Gate the removal in CI with oasdiff and a notice period.
- Leave a tombstone for a full cycle of your slowest caller.
What to remember
- FastAPI’s
deprecated=Truechanges the documentation and nothing a client can see at runtime. Deprecationcarries an@and Unix seconds;Sunsetcarries an HTTP date that ends in GMT; the sunset must not be earlier than the deprecation. RFC 9745’s own example spells theSunsetzone UTC, so do not copy it.- Headers set in a dependency vanish on error responses. A middleware keeps them on every answer.
- A hint nobody reads is not a warning. Make clients warn, and let a close sunset fail a build.
- A quiet ledger does not prove that an endpoint is unused, because monthly and quarterly callers are quiet most of the time. Use the ledger to find stragglers and brownouts to wake them.
- Answer brownouts with 410 and
Cache-Control: no-store, announce them, and aim them at the hours your callers actually use. - oasdiff can refuse a removal before the sunset and a notice that is too short, and it is one command in CI.
Sources and further reading
- IETF, RFC 9745: The Deprecation HTTP Response Header Field (March 2025), and RFC 8594: The Sunset HTTP Header Field.
- IETF, RFC 9110: HTTP Semantics, sections on HTTP dates and 410 Gone; RFC 9651: Structured Field Values for HTTP; RFC 9457: Problem Details for HTTP APIs.
- IANA, Link Relations registry (the
deprecation,sunsetandsuccessor-versionentries). - FastAPI, Path Operation Configuration, Path Operation Advanced Configuration and Middleware.
- oasdiff, Deprecating APIs, Parameters and Properties, and the v1.39.0 release.
- pytest, How to capture warnings; Python, the warnings module; urllib3, the Retry class.
- freeCodeCamp, How to Write an API Migration Guide (With a Real Example), the article that prompted this tutorial.
- More from this site: RFC 9457 problem details in FastAPI, Cache-Control headers in FastAPI and nginx, evolving a Protobuf schema without breaking old clients, fuzz-testing a FastAPI API from its OpenAPI schema and hardening a rate limiter, including Retry-After.








No Comment! Be the first one.