From Domain Nouns to Resources and URLs
Turn a domain of teams, tasks and actions into resources and collections, give them URLs that stay predictable, and pick methods and status codes you can justify.
Contentsand lesson path
On this page
- Why it matters
- Finding resources in the domain
- URLs that stay predictable
- Choosing methods and status codes
- Run the demo yourself
- 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
- Model a domain as resources and collections with consistent URLs, methods and status codes, justifying each choice against HTTP semantics.
Prerequisites: HTTP & APIs
01. Why it matters
You already know what a request looks like and what the method and status code of a response mean; that lesson taught the vocabulary. This lesson is about the design decision that comes before any of it: what the things in your API are, and what you call them.
That decision outlives your code. Frameworks, databases and implementations get rewritten; GET /teams/t7/tasks is still GET /teams/t7/tasks. Every client, SDK, dashboard and integration your API will ever have is built against the shape you choose now. A design where URLs name things and methods express actions can be learned in an afternoon, because one pattern covers every new feature. A design where every endpoint is a surprise (/getTasks, /task/listNew, /doTransfer) must be relearned operation by operation, and it pushes semantics out of the protocol where tools can see them and into documentation where nothing enforces them.
The lesson works through one small domain — a team-tasks service — and ends with a running FastAPI app that behaves the way the design says it should.
02. Finding resources in the domain
Start from the nouns the people in the domain use, not from the functions your code performs. A team-tasks service has teams, tasks and comments. People also do things — complete a task, export a report — and the temptation is to turn each verb into an endpoint. Resist it at first pass: most verbs either change a field on a noun (task state), create a new noun (an export), or are a query in disguise.
Each noun that matters enough to have an identity becomes a resource. Resources of the same kind form a collection, named with a plural noun: /teams, /tasks. A collection member is one item, identified within it: /teams/t7/tasks/k101. Three properties make this naming more than taste:
- Plural collections let
POST /teams/t7/tasksread naturally as "add a task to team t7's tasks", andGET /teams/t7/tasksas "list them". - Opaque identifiers. To a client, an id such as
k101is a string with no meaning: it never parses it, sorts by it or guesses the next one, so you stay free to change how ids are made. In production, use random ids such as UUIDs; the demo numbers its ids in order only to keep them readable. - The same resource, one URL. Each task has one canonical URL; in this lesson it is
/teams/{team_id}/tasks/{task_id}, so/teams/t7/tasks/k101is the task. If you also expose a short form such as/tasks/k101, document which one is canonical and redirect or link from the other. Cross-collection filters are queries on a collection, not new nouns.
Actions that create something real deserve to be nouns too. "Export this team's tasks" creates an export you can later ask about — did it finish? where is the file? So it becomes a collection: POST /teams/t7/exports, and the created export is a resource you can GET again. An RPC-style endpoint has nowhere to put that state.
GET /getTasks?team=t7 GET /teams/t7/tasks
POST /createTask POST /teams/t7/tasks
POST /tasks/markDone PATCH /teams/t7/tasks/k101
(state: done in the body)
GET /taskDetails?id=k101 GET /teams/t7/tasks/k101
POST /exportTeamTasks POST /teams/t7/exports
GET /exportStatus?id=e1 GET /teams/t7/exports/e1Notice what moved where. The verbs (get, create, mark, export) disappeared from paths and became methods. What remained is what is acted on. There is one honest case for a verb-shaped path: a state transition so central to the domain that it deserves its own operation instead of a generic field update. POST /teams/t7/tasks/k101/completion is such a custom method (Google's AIP-136 spells it POST /teams/t7/tasks/k101:complete). It does not create a new resource you can fetch later: it applies the transition and answers 200 with the updated task, so there is no Location header. Use it sparingly, and never let a GET have side effects; prefetchers, crawlers and caches act on GETs without asking.
03. URLs that stay predictable
The path names what, the query says how:
- Path segments carry identity and hierarchy.
/teams/t7/tasks/k101/comments/c9reads from left to right: which team, which task, which comment. Nest as deep as ownership runs, and no deeper; two levels of nesting covers most domains, and any deeper is usually a collection asking to be filtered instead. - Query parameters carry selection and presentation. Filtering (
?state=open), sorting, pagination and search terms belong after the?, because they narrow a list without changing which collection you are addressing. - Nest when the child has no life outside the parent. Comments that only ever appear inside one task live at
/teams/t7/tasks/k101/comments. The moment a screen lists comments across tasks, promote them to/comments?task_id=…— a top-level collection with a filter. Both are correct designs; pick per access pattern and stay consistent. - Singletons name the one-of-a-kind. "The settings of team t7" is a single resource:
/teams/t7/settings, updated with PATCH. "The current user" is/me. No id, no collection.
Google's API Improvement Proposals call this discipline resource names and allow narrow exceptions for true custom methods; browsing a few of their AIPs is the fastest way to calibrate your own judgement. Consistency matters more than any single rule: a team that always uses plural collections, snake_case fields and query filters has an API where the third endpoint is predictable from the first two.
04. Choosing methods and status codes
With resources named, methods and status codes follow from questions you can answer about each operation. The classes and the safe and idempotent properties are defined in RFC 9110; what follows is how the choice plays out in design.
Creating a task: the client does not know the id yet, so it POSTs to the collection and the server assigns one. Success is 201 Created with a Location header naming the new resource — the response to a POST on a collection is the contract clients use to fetch what they just made. Reading is GET; the item is found (200) or it is not (404). A partial change — rename a task, set its state — is PATCH with just the fields being changed, answered 200 with the updated representation. Replacing a whole record, when the client owns the full contents, is PUT.
Two codes carry meaning that pure CRUD teaching misses. A request that is well-formed but cannot be applied to this resource — a completion posted for a task that is already done — is 409 Conflict: the body was fine, the state was not. Validation failures (a blank title) are 422 Unprocessable Content, keeping 400 for requests the server could not even parse. Each code is a sentence in a conversation with a client program: "try again as-is" (rarely, except 408/429 after waiting), "fix your data" (422), "look again before you act" (409).
@app.post("/teams/{team_id}/tasks", status_code=201)
def create_task(team_id: str, task_in: TaskIn,
response: Response) -> dict:
if team_id not in TEAMS:
raise HTTPException(404, "unknown team")
task_id = f"k{100 + len(TASKS) + 1}"
task = {"id": task_id, "team_id": team_id,
"title": task_in.title,
"assignee": task_in.assignee, "state": "open"}
TASKS[task_id] = task
response.headers["Location"] = (
f"/teams/{team_id}/tasks/{task_id}")
return task
@app.post("/teams/{team_id}/tasks/{task_id}/completion")
def complete_task(team_id: str, task_id: str) -> dict:
task = TASKS.get(task_id)
if task is None or task["team_id"] != team_id:
raise HTTPException(404, "unknown task")
if task["state"] == "done":
raise HTTPException(409, "already done")
task["state"] = "done"
return taskGET /teams/t7/tasks -> 200 Location: -
GET /teams/t7/tasks?state=done&assignee=ana -> 200 Location: -
GET /teams/t7/tasks/nope -> 404 Location: -
body: {"detail":"unknown task"}
POST /teams/t7/tasks -> 201 Location: /teams/t7/tasks/k104
POST /teams/t7/tasks/k102/completion -> 200 Location: -
POST /teams/t7/tasks/k102/completion -> 409 Location: -
body: {"detail":"already done"}
POST /teams/t7/tasks -> 422 Location: -The transcript is the design, running. Filters live in the query. Creation answers 201 and points at the new task. The second completion is rejected with 409, so a client cannot silently re-complete work, and a blank title fails validation with 422. None of these choices required reading the implementation — the URL, method and status told the whole story. That is the standard to hold your own designs to: a colleague should predict your endpoint for "list a team's open tasks, most recent first" before you show them the docs.
05. Run the demo yourself
The two routes above are the middle of one file. Save part 1, then the routes above, then part 3, in that order, as demo01_resources.py. Part 3 calls the app in process through httpx, so no server or port is needed.
import asyncio
import httpx
from fastapi import FastAPI, HTTPException, Response
from pydantic import BaseModel, Field
app = FastAPI()
class TaskIn(BaseModel):
title: str = Field(min_length=1)
assignee: str | None = None
TEAMS = {"t7": {"id": "t7", "name": "Platform"}}
TASKS = {
"k101": {"id": "k101", "team_id": "t7", "title": "Write API guide",
"assignee": "ana", "state": "open"},
"k102": {"id": "k102", "team_id": "t7", "title": "Review API guide",
"assignee": "bo", "state": "open"},
"k103": {"id": "k103", "team_id": "t7", "title": "Ship release 1.4",
"assignee": "ana", "state": "done"},
}
@app.get("/teams/{team_id}/tasks")
def list_tasks(team_id: str, state: str | None = None,
assignee: str | None = None) -> list[dict]:
if team_id not in TEAMS:
raise HTTPException(404, "unknown team")
rows = [t for t in TASKS.values() if t["team_id"] == team_id]
if state is not None:
rows = [t for t in rows if t["state"] == state]
if assignee is not None:
rows = [t for t in rows if t["assignee"] == assignee]
return rows
@app.get("/teams/{team_id}/tasks/{task_id}")
def get_task(team_id: str, task_id: str) -> dict:
task = TASKS.get(task_id)
if task is None or task["team_id"] != team_id:
raise HTTPException(404, "unknown task")
return taskasync def main() -> None:
transport = httpx.ASGITransport(app=app) # calls the app in process
async with httpx.AsyncClient(transport=transport,
base_url="http://api.test") as client:
calls = [
("GET", "/teams/t7/tasks", None),
("GET", "/teams/t7/tasks?state=done&assignee=ana", None),
("GET", "/teams/t7/tasks/nope", None),
("POST", "/teams/t7/tasks", {"title": "Draft deprecation plan"}),
("POST", "/teams/t7/tasks/k102/completion", None),
("POST", "/teams/t7/tasks/k102/completion", None),
("POST", "/teams/t7/tasks", {"title": ""}),
]
for method, url, body in calls:
r = await client.request(method, url, json=body)
location = r.headers.get("location", "-")
print(f"{method:4} {url} -> {r.status_code} Location: {location}")
if r.status_code in (404, 409): # the two state errors
print(f" body: {r.text}")
asyncio.run(main())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
python demo01_resources.py06. Check your understanding
07. Apply it
Take the team-tasks practice for this skill and draft the resource model before any code. List the nouns people use when they talk about the work, mark each as collection, item or singleton, and draw the URL for five operations: list a team's open tasks, create one, change its assignee, add a comment, start an export. For each, write the method, the success status code and the two most likely error codes, and one sentence justifying the URL shape. Keep the sheet: the next lessons add errors, pagination and retries to exactly this API, and the OpenAPI lab turns it into a contract.
08. Review prompt
Without looking back: write the URL and method for listing a team's open tasks, for adding a task to a team, and for reading one comment on one task. Explain where filter values go and why. Then name the status code for each of these replies to a create request: created successfully, the body failed validation, the parent team does not exist. Finally, give one situation where a verb-shaped sub-resource is defensible, and the one thing a GET handler must never do.
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.