Lab: Contract-First Design with OpenAPI
Write the team-tasks API as an OpenAPI 3.1 document before any server code, validate and lint it, then implement a FastAPI app against it and walk every documented promise with httpx.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: create the environment
- Step 2: write the contract
- Step 3: validate the document structure
- Step 4: lint the design
- Step 5: implement the server against the contract
- Step 6: walk every documented promise
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of API Design
- From Domain Nouns to Resources and URLs Concept · 20 min
- Errors, Pagination and Filtering Clients Can Rely On Worked example · 25 min
- Safe Retries, Long-Running Operations, Concurrent Updates and Versioning Concept · 30 min
- Lab: Contract-First Design with OpenAPI Lab · 30 min
- Beyond REST: Sketching a GraphQL Schema and a gRPC Service Worked example · 25 min
- Check: Review a Flawed API Design Knowledge check · 10 questions
What you will learn
- Write an OpenAPI contract that client and server teams can build against, and state when GraphQL or gRPC would serve the same clients better.
- Model a domain as resources and collections with consistent URLs, methods and status codes, justifying each choice against HTTP semantics.
- Specify a machine-readable error format (Problem Details) and a pagination, filtering and sorting scheme, choosing cursor or offset pagination with stated trade-offs.
Prerequisites: HTTP & APIs
01. Goal and setup
In the lessons so far you designed the team-tasks API on paper and in running code: resources and URLs, Problem Details errors, cursor pagination, an Idempotency-Key on creates, ETag-guarded updates, and an export modelled as 202 Accepted with a status resource. In this lab that design becomes an OpenAPI document — a machine-readable contract — before the server is written, and the server is then checked against it. That order is what contract-first means: client teams can build against a mock of the document while the server team builds the implementation, and both sides test against the same artefact.
You need: Python 3.12, uv, and Node.js for the linter. Versions verified for this lab: Python 3.12.13, fastapi 0.163.1, httpx 0.28.1, openapi-spec-validator 0.9.0, PyYAML 6.0.3, Redocly CLI 2.71.0. Create a scratch folder outside any repo and work there:
team-tasks-api/
├── .venv/ virtual environment (created in step 1)
├── openapi.yaml the contract — written first
├── validate_contract.py structural validation (step 3)
├── lab_server.py FastAPI implementation (step 5)
└── lab_walkthrough.py exercises the contract with httpx (step 6)02. Step 1: create the environment
mkdir team-tasks-api && cd team-tasks-api
uv venv --python 3.12 .venv
source .venv/bin/activate
uv pip install fastapi==0.163.1 pydantic==2.14.3 httpx==0.28.1 \
openapi-spec-validator==0.9.0 pyyaml==6.0.3
python -c "import fastapi, httpx, openapi_spec_validator, pydantic, yaml;
print(fastapi.__version__, pydantic.VERSION, httpx.__version__)"0.163.1 2.14.3 0.28.103. Step 2: write the contract
Write openapi.yaml by hand — not generated from code — starting from the version, the server URL and the first path. Three earlier decisions become visible here: the /v1 path versioning, plural collections under a team, and filters as query parameters with documented ranges. Note the security block: declaring the bearer scheme at the root level applies it to every operation, which matters in the next step.
openapi: 3.1.0
info:
title: Team Tasks API
version: 1.0.0
summary: Tasks and exports for small teams.
license:
name: MIT
url: https://spdx.org/licenses/MIT.html
security:
- bearerAuth: []
servers:
- url: https://api.acme.test/v1 # .test is reserved for examples
paths:
/teams/{teamId}/tasks:
get:
operationId: listTasks
summary: List a team's tasks, newest first
parameters:
- $ref: '#/components/parameters/TeamId'
- name: limit
in: query
schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
- name: cursor
in: query
description: Opaque cursor from a previous response.
schema: { type: string }
- name: state
in: query
schema: { type: string, enum: [open, in-progress, done] }
responses:
'200':
description: One page of tasks.
content:
application/json:
schema: { $ref: '#/components/schemas/TaskPage' }
'404': { $ref: '#/components/responses/TeamNotFound' }
'422': { $ref: '#/components/responses/ValidationError' }
'429': { $ref: '#/components/responses/RateLimited' }
post:
operationId: createTask
summary: Create a task in a team
parameters:
- $ref: '#/components/parameters/TeamId'
- $ref: '#/components/parameters/IdempotencyKey'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/TaskInput' }
responses:
'201':
description: Task created.
headers:
Location: { schema: { type: string },
description: URL of the task }
content:
application/json:
schema: { $ref: '#/components/schemas/Task' }
'404': { $ref: '#/components/responses/TeamNotFound' }
'409': { $ref: '#/components/responses/DuplicateTitle' }
'422': { $ref: '#/components/responses/ValidationError' }
'429': { $ref: '#/components/responses/RateLimited' }Continue with the item, update and export paths. The update documents its If-Match precondition as a required header parameter and the 412 it can produce; the export declares 202 with Location and Retry-After headers plus a link to the status resource — the whole long-running design from the reliability lesson, now in writing that generated clients can see:
/teams/{teamId}/tasks/{taskId}:
get:
operationId: getTask
summary: Read a single task by id
parameters:
- $ref: '#/components/parameters/TeamId'
- $ref: '#/components/parameters/TaskId'
responses:
'200':
description: The requested task.
headers:
ETag: { schema: { type: string } }
content:
application/json:
schema: { $ref: '#/components/schemas/Task' }
'404': { $ref: '#/components/responses/TaskNotFound' }
patch:
operationId: updateTask
summary: Change a task, conditional on its ETag
parameters:
- $ref: '#/components/parameters/TeamId'
- $ref: '#/components/parameters/TaskId'
- name: If-Match
in: header
required: true
description: ETag read from a previous GET.
schema: { type: string }
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/TaskPatch' }
responses:
'200':
description: Updated task with its new ETag.
headers:
ETag: { schema: { type: string } }
content:
application/json:
schema: { $ref: '#/components/schemas/Task' }
'404': { $ref: '#/components/responses/TaskNotFound' }
'412': { $ref: '#/components/responses/VersionConflict' }
'422': { $ref: '#/components/responses/ValidationError' }
'428': { $ref: '#/components/responses/PreconditionRequired' }
/teams/{teamId}/exports:
post:
operationId: startExport
summary: Start a CSV export of the team's tasks
parameters:
- $ref: '#/components/parameters/TeamId'
- $ref: '#/components/parameters/IdempotencyKey'
responses:
'202':
description: Export accepted; poll the status resource.
headers:
Location:
schema: { type: string }
description: URL of the export status resource.
Retry-After: { schema: { type: integer } }
content:
application/json:
schema: { $ref: '#/components/schemas/Export' }
'404': { $ref: '#/components/responses/TeamNotFound' }
'422': { $ref: '#/components/responses/ValidationError' }
/exports/{exportId}:
get:
operationId: getExport
summary: Poll the state of an export
parameters:
- name: exportId
in: path
required: true
schema: { type: string }
responses:
'200':
description: Current export state; result_url when done.
content:
application/json:
schema: { $ref: '#/components/schemas/Export' }
headers:
Retry-After: { schema: { type: integer } }
'404': { $ref: '#/components/responses/ExportNotFound' }Finish with the reusable parts under components: the shared parameters, the error responses, and the schemas, in full. Every error response references one Problem schema — this is the decision a client team can actually build against, because generated clients get a typed problem object for every failure, and each response entry documents its own Retry-After where one applies:
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
parameters:
TeamId:
name: teamId
in: path
required: true
schema: { type: string }
TaskId:
name: taskId
in: path
required: true
schema: { type: string }
IdempotencyKey:
name: Idempotency-Key
in: header
required: true
description: Unique key; retries with it return the first result.
schema: { type: string, format: uuid }
responses:
TeamNotFound:
description: No team with this id.
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
TaskNotFound:
description: No task with this id in this team.
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
ExportNotFound:
description: No export with this id.
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
DuplicateTitle:
description: The title is taken, or a request with this key is in flight.
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
ValidationError:
description: A body, query or header value failed validation, or a key was reused.
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
VersionConflict:
description: If-Match did not match; read the task again.
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
PreconditionRequired:
description: If-Match is missing; read the task and send its ETag.
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
RateLimited:
description: Too many requests; honour Retry-After.
headers:
Retry-After: { schema: { type: integer } }
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
schemas:
Task:
type: object
required: [id, title, state, created_at]
properties:
id: { type: string }
title: { type: string, minLength: 1, maxLength: 200 }
state: { type: string, enum: [open, in-progress, done] }
created_at: { type: string, format: date-time }
TaskInput:
type: object
required: [title]
properties:
title: { type: string, minLength: 1, maxLength: 200 }
TaskPatch:
type: object
properties:
title: { type: string, minLength: 1, maxLength: 200 }
state: { type: string, enum: [open, in-progress, done] }
TaskPage:
type: object
required: [items]
properties:
items:
type: array
items: { $ref: '#/components/schemas/Task' }
next_cursor:
type: [string, 'null']
description: Cursor for the next page; null on the last page.
Export:
type: object
required: [id, state]
properties:
id: { type: string }
state: { type: string, enum: [running, succeeded, failed] }
progress: { type: integer, minimum: 0, maximum: 100 }
retry_after: { type: integer, description: Seconds before polling again. }
result_url: { type: string, description: Set when state is succeeded. }
Problem:
description: RFC 9457 Problem Details.
type: object
required: [type, title, status, detail]
properties:
type: { type: string, format: uri }
title: { type: string }
status: { type: integer }
detail: { type: string }
instance: { type: string }Save the three YAML blocks, in order, as one openapi.yaml: four paths and six operations. Read the components against the operations. Between them, the error responses cover every error status the server in step 5 returns: the list, the create and the export answer 404 for an unknown team; every operation that takes a body, a query parameter or a required header answers 422 when a value fails validation (limit=0, a blank title, an unreadable cursor, a missing Idempotency-Key); the update answers 428 when If-Match is missing and 412 when it is stale; and the create also answers 409 while a request with the same key is still in flight and 422 when a key is reused with a different body. The idempotency draft suggests 400 for a missing key; this contract uses 422 because FastAPI rejects the missing header during validation, and either works if the contract says which. A status the server sends but the contract omits is exactly the drift a contract test reports. Two habits from this step pay off in every later lab: every operation gets an operationId, and every reusable shape is defined once and referenced.
04. Step 3: validate the document structure
Validation checks the document against the OpenAPI 3.1 schema itself — unknown keys, broken $ref targets, wrong types. It is the cheapest possible feedback loop, so run it after every edit:
"""Validate openapi.yaml against the OpenAPI 3.1 schema."""
from openapi_spec_validator import validate
import yaml
with open("openapi.yaml", "rb") as file:
spec = yaml.safe_load(file)
validate(spec)
print(f"{spec['info']['title']} {spec['info']['version']}: "
f"valid OpenAPI {spec['openapi']}")
print(f"{len(spec['paths'])} paths, "
f"{sum(len(m) for m in spec['paths'].values())} operations")Team Tasks API 1.0.0: valid OpenAPI 3.1.0
4 paths, 6 operations05. Step 4: lint the design
Validation proves the document is well-formed; linting judges the design. Redocly CLI applies a recommended ruleset on top: missing descriptions, operations without operationId, undocumented error responses, missing security. It needs Node.js and runs with no setup:
npx --yes @redocly/[email protected] lint openapi.yamlNo configurations were provided -- using built in recommended
configuration by default.
validating openapi.yaml...
openapi.yaml: validated in 72ms
Woohoo! Your API description is valid.The first run of this lab actually failed lint: the security-defined rule reported every operation because the document had a bearer scheme but no security block applying it. One root-level security: entry — added in step 2 — fixed all six reports at once. That is the value of the linter: it holds the whole document to rules a human reviewer would check one path at a time.
06. Step 5: implement the server against the contract
Now write lab_server.py — a FastAPI app mounted under /v1 to match the contract's server URL. Most of the code you already met in lessons 2 and 3: the problem() helper and validation handler, cursor paging over a stable (created_at, id) order, and the export state machine. Two details matter for the walkthrough below. Send ETags as quoted strings (ETag: "16e9e576"), as RFC 9110 requires, and compare If-Match against that exact quoted value; and return result_url as /v1/exports/e1/result.csv, the same /v1 form as Location. The complete file follows; compare it with your own after writing it. Look closely at the create, because it must honour three documented promises at once: require the key, replay on retry (keys are scoped to the team, as in the reliability lesson), and set Location. It also keeps the reliability lesson's in-flight guard: a second request with the same key that arrives while the first is still running gets 409 request-in-flight with Retry-After: 1, rather than racing it. The export honours its Idempotency-Key the same way, so a retried POST /exports returns the first export's Location instead of starting another one. The ETag is the first 8 hex digits of a SHA-256 over the task, so the values in the expected output below are exactly what this file produces. TaskPatch uses None only to mean "not sent"; its validator turns an explicit {"title": null} into a 422, because the contract types title and state as strings, and exclude_unset=True would otherwise store the null:
"""Team Tasks API: a small in-memory implementation of openapi.yaml."""
import asyncio
import base64
import hashlib
from datetime import datetime, timedelta, timezone
from typing import Literal
from fastapi import APIRouter, FastAPI, Header, Query, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, field_validator
app = FastAPI()
api = APIRouter()
T0 = datetime(2026, 10, 24, 9, 0, tzinfo=timezone.utc)
TEAMS = {"t7"}
TASKS: dict[str, dict] = {}
IDEMPOTENT: dict[tuple, dict] = {} # responses stored by (scope, team, key)
IN_FLIGHT: set[tuple] = set() # keys whose first request is still running
EXPORTS: dict[str, dict] = {}
for i in range(5):
TASKS[f"k{101 + i}"] = {
"id": f"k{101 + i}", "title": f"Task {i + 1}", "state": "open",
"created_at": (T0 + timedelta(minutes=i)).isoformat()}
def problem(status_code, type_slug, title, detail, instance, **extra):
return JSONResponse({"type": f"https://api.example.com/problems/{type_slug}",
"title": title, "status": status_code, "detail": detail,
"instance": instance, **extra},
status_code=status_code, media_type="application/problem+json")
@app.exception_handler(RequestValidationError)
async def validation_problem(request: Request, exc):
return problem(422, "validation-error", "The request is invalid",
"One or more values failed validation.", request.url.path)
def etag(task: dict) -> str:
digest = hashlib.sha256(repr(sorted(task.items())).encode()).hexdigest()[:8]
return f'"{digest}"' # RFC 9110: an entity-tag is a quoted string
class TaskInput(BaseModel):
title: str = Field(min_length=1, max_length=200)
class TaskPatch(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=200)
state: Literal["open", "in-progress", "done"] | None = None
@field_validator("title", "state")
@classmethod
def not_null(cls, value): # runs only for fields the client sent
if value is None: # the contract types both as non-null
raise ValueError("send a value or leave the field out")
return value
def cursor_of(t):
raw = f"{t['created_at']}|{t['id']}".encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
@api.get("/teams/{teamId}/tasks")
async def list_tasks(teamId: str, limit: int = Query(20, ge=1, le=100),
cursor: str | None = None,
state: Literal["open", "in-progress", "done"] | None = None):
if teamId not in TEAMS:
return problem(404, "team-not-found", "Team not found", "No such team.",
f"/v1/teams/{teamId}/tasks")
rows = sorted(TASKS.values(), key=lambda t: (t["created_at"], t["id"]),
reverse=True)
if state:
rows = [t for t in rows if t["state"] == state]
if cursor:
try:
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)).decode()
created_at, task_id = raw.split("|") # wrong shape: ValueError
datetime.fromisoformat(created_at) # not a timestamp: ValueError
except ValueError:
return problem(422, "validation-error", "The request is invalid",
"Unknown cursor.", f"/v1/teams/{teamId}/tasks")
marker = (created_at, task_id) # every created_at is UTC, like T0
rows = [t for t in rows if (t["created_at"], t["id"]) < marker]
page = rows[:limit]
more = len(rows) > limit
return {"items": page, "next_cursor": cursor_of(page[-1]) if more else None}
@api.post("/teams/{teamId}/tasks", status_code=201)
async def create_task(teamId: str, task_input: TaskInput,
idempotency_key: str = Header(
alias="Idempotency-Key")):
if teamId not in TEAMS:
return problem(404, "team-not-found", "Team not found", "No such team.",
f"/v1/teams/{teamId}/tasks")
body_hash = hashlib.sha256(
task_input.model_dump_json().encode()).hexdigest()
key = ("task", teamId, idempotency_key)
if key in IDEMPOTENT:
stored = IDEMPOTENT[key]
if stored["body_hash"] != body_hash:
return problem(422, "idempotency-conflict",
"Idempotency key reused with different payload",
"A previous request used this key with different data.",
f"/v1/teams/{teamId}/tasks")
replayed = JSONResponse(stored["body"], status_code=201)
replayed.headers["Location"] = stored["location"]
replayed.headers["Idempotent-Replayed"] = "true"
return replayed
if key in IN_FLIGHT: # a twin with this key is still running
busy = problem(409, "request-in-flight", "Request in progress",
"A request with this key is still being processed.",
f"/v1/teams/{teamId}/tasks")
busy.headers["Retry-After"] = "1"
return busy
IN_FLIGHT.add(key)
try:
await asyncio.sleep(0.05) # slow work, so retries matter
if any(t["title"] == task_input.title
for t in TASKS.values()):
return problem(409, "duplicate-title", "Title already used",
"A task with this title exists.",
f"/v1/teams/{teamId}/tasks")
task_id = f"k{101 + len(TASKS)}"
task = {"id": task_id, "title": task_input.title, "state": "open",
"created_at": (T0 + timedelta(minutes=len(TASKS))).isoformat()}
TASKS[task_id] = task
location = f"/v1/teams/{teamId}/tasks/{task_id}"
IDEMPOTENT[key] = {"body_hash": body_hash, "body": task,
"location": location}
out = JSONResponse(task, status_code=201)
out.headers["Location"] = location
return out
finally:
IN_FLIGHT.discard(key)
def find(teamId, taskId):
return TASKS.get(taskId) if teamId in TEAMS else None
@api.get("/teams/{teamId}/tasks/{taskId}")
async def get_task(teamId: str, taskId: str):
task = find(teamId, taskId)
if task is None:
return problem(404, "task-not-found", "Task not found", "No such task.",
f"/v1/teams/{teamId}/tasks/{taskId}")
return JSONResponse(task, headers={"ETag": etag(task)})
@api.patch("/teams/{teamId}/tasks/{taskId}")
async def update_task(teamId: str, taskId: str, patch: TaskPatch,
if_match: str | None = Header(default=None, alias="If-Match")):
where = f"/v1/teams/{teamId}/tasks/{taskId}"
task = find(teamId, taskId)
if task is None:
return problem(404, "task-not-found", "Task not found", "No such task.", where)
if if_match is None:
return problem(428, "precondition-required", "If-Match required",
"Read the task and send its ETag in If-Match.", where)
if if_match != etag(task):
return problem(412, "version-conflict", "Version conflict",
"The task changed since you read it.", where)
task.update(patch.model_dump(exclude_unset=True))
return JSONResponse(task, headers={"ETag": etag(task)})
@api.post("/teams/{teamId}/exports", status_code=202)
async def start_export(teamId: str,
idempotency_key: str = Header(alias="Idempotency-Key")):
if teamId not in TEAMS:
return problem(404, "team-not-found", "Team not found", "No such team.",
f"/v1/teams/{teamId}/exports")
key = ("export", teamId, idempotency_key)
if key not in IDEMPOTENT: # a retry with the same key reuses the export
export_id = f"e{len(EXPORTS) + 1}"
EXPORTS[export_id] = {"id": export_id, "state": "running", "progress": 0,
"polls": 0}
body = {k: v for k, v in EXPORTS[export_id].items() if k != "polls"}
IDEMPOTENT[key] = {"body": body, "location": f"/v1/exports/{export_id}"}
replayed = False
else:
replayed = True
stored = IDEMPOTENT[key]
headers = {"Location": stored["location"], "Retry-After": "1"}
if replayed:
headers["Idempotent-Replayed"] = "true"
return JSONResponse(stored["body"], status_code=202, headers=headers)
@api.get("/exports/{exportId}")
async def get_export(exportId: str):
ex = EXPORTS.get(exportId)
if ex is None:
return problem(404, "export-not-found", "Export not found", "No such export.",
f"/v1/exports/{exportId}")
ex["progress"] = [0, 60, 100][min(ex["polls"], 2)]
ex["polls"] += 1
body = {"id": ex["id"], "progress": ex["progress"]}
if ex["progress"] == 100:
ex["state"] = "succeeded"
body |= {"state": "succeeded",
"result_url": f"/v1/exports/{exportId}/result.csv"}
return body
body |= {"state": "running", "retry_after": 1}
return JSONResponse(body, headers={"Retry-After": "1"})
app.include_router(api, prefix="/v1")07. Step 6: walk every documented promise
Finally, lab_walkthrough.py drives the app through the contract's headline behaviours with httpx over an in-process ASGI transport. It pages with the cursor, creates with an idempotency key and retries, updates conditionally through an ETag, and polls an export to completion. Every status, content type and problem type below is read from the real response, so each line is a sentence of the contract being kept:
import asyncio
import httpx
from lab_server import app
def kind(response): # the last part of a Problem Details type URI
return response.json()["type"].rsplit("/", 1)[-1]
async def main():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
print("== page through tasks with the cursor ==")
p1 = (await c.get("/v1/teams/t7/tasks?limit=2")).json()
print(f"page 1: {[t['id'] for t in p1['items']]} "
f"next_cursor set: {bool(p1['next_cursor'])}")
cur = p1['next_cursor']
p2 = (await c.get(f"/v1/teams/t7/tasks?limit=2&cursor={cur}")).json()
ids = [t['id'] for t in p2['items']]
print(f"page 2: {ids} next_cursor: {p2['next_cursor']}")
print("== create with an idempotency key, then retry ==")
key = "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"
r1 = await c.post("/v1/teams/t7/tasks", json={"title": "Task 6"},
headers={"Idempotency-Key": key})
print(f"create -> {r1.status_code} {r1.headers.get('Location')}")
r2 = await c.post("/v1/teams/t7/tasks", json={"title": "Task 6"},
headers={"Idempotency-Key": key})
print(f"retry -> {r2.status_code} {r2.headers.get('Location')} "
f"replayed: {r2.headers.get('Idempotent-Replayed')}")
print("== update a task conditionally ==")
read = await c.get("/v1/teams/t7/tasks/k101")
t = read.headers.get("ETag")
print(f"read -> {read.status_code} ETag: {t}")
p_bad = await c.patch("/v1/teams/t7/tasks/k101", json={"state": "done"})
print(f"patch without If-Match -> {p_bad.status_code} "
f"{p_bad.headers['content-type']} {kind(p_bad)}")
p_good = await c.patch("/v1/teams/t7/tasks/k101", json={"state": "done"},
headers={"If-Match": t})
new_etag = p_good.headers.get("ETag")
print(f"patch with If-Match -> {p_good.status_code} new ETag: {new_etag}")
p_stale = await c.patch("/v1/teams/t7/tasks/k101", json={"state": "done"},
headers={"If-Match": t})
print(f"patch with stale If-Match -> {p_stale.status_code} {kind(p_stale)}")
print("== start an export and poll it ==")
export_key = "0c6f2a4e-5d1b-4f7e-9a3c-8b2d1e4f6a70"
ex = await c.post("/v1/teams/t7/exports",
headers={"Idempotency-Key": export_key})
loc = ex.headers["Location"]
print(f"POST exports -> {ex.status_code} Location: {loc}")
for _ in range(3):
resp = await c.get(loc)
poll = resp.json()
ra = poll.get("retry_after", "-")
prog = poll.get("progress", 0)
print(f"poll -> {resp.status_code} {poll['state']} {prog}% "
f"retry-after: {ra}")
if poll.get("result_url"):
print(f" result_url: {poll['result_url']}")
break
asyncio.run(main())== page through tasks with the cursor ==
page 1: ['k105', 'k104'] next_cursor set: True
page 2: ['k103', 'k102'] next_cursor: MjAyNi0xMC0yNFQwOTowMTowMCswMDowMHxrMTAy
== create with an idempotency key, then retry ==
create -> 201 /v1/teams/t7/tasks/k106
retry -> 201 /v1/teams/t7/tasks/k106 replayed: true
== update a task conditionally ==
read -> 200 ETag: "16e9e576"
patch without If-Match -> 428 application/problem+json precondition-required
patch with If-Match -> 200 new ETag: "aee1cdb9"
patch with stale If-Match -> 412 version-conflict
== start an export and poll it ==
POST exports -> 202 Location: /v1/exports/e1
poll -> 200 running 0% retry-after: 1
poll -> 200 running 60% retry-after: 1
poll -> 200 succeeded 100% retry-after: -
result_url: /v1/exports/e1/result.csvThe walkthrough is a sanity check, not a conformance proof: it checks the behaviours you thought of. Property-based contract testing goes further by generating requests from the document itself and validating every response against the declared schemas — Schemathesis is a solid tool for it, and the API integration testing skill covers the practice in depth.
08. Troubleshooting
09. Check your understanding
10. Apply it
Extend the lab. Add a comments sub-resource to the contract: GET and POST on /teams/{teamId}/tasks/{taskId}/comments, with cursor paging on the list and a documented Problem response for posting to a missing task. Re-run validation and lint, implement it, and extend the walkthrough. Then point Schemathesis 4.x (checked with 4.32.4) at the running app: start it with uvicorn lab_server:app --port 8000, then run schemathesis run openapi.yaml --url http://127.0.0.1:8000/v1 --checks all -H "Authorization: Bearer test-token". With a local file, --url is required; otherwise requests would go to the example server api.acme.test, and Schemathesis 4 has no dry-run mode. Expect findings: against a minimal server it reported undocumented 422 and 400 responses (for example, a body that is not valid JSON) and Allow header mismatches on 405 answers. Note what it generated that your walkthrough did not, then fix the server or the contract until it passes. Finish with the skill practice: the full team-tasks contract, linted, plus a peer review against a design checklist.
11. Review prompt
Without looking back: name the two levels of checking a contract gets in this lab and what each covers. Write from memory the contract fragments that document an idempotent create — the parameter, the header of the 201, and one error response. Explain why the walkthrough passing does not prove the server matches the contract, and what kind of test would. Finally, list three things the linter flagged or could flag that the validator would not.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.