APIs · Beginner · 20 min
Design REST endpoints: resources, methods and status codes
By Padding · Updated 18 Nov 2026
Node.js 26.13 · Express 5.3
You will design the endpoints of an event ticketing API on one page, build an Express 5 stub that follows it, and prove every status code in the design with curl.
On this page
Most API trouble starts before the first line of code: a URL with a verb in it, a POST that charges a card twice when the client retries, a 200 that hides an error. Fixing those after clients depend on them means a new version of the API. Fixing them in a design document costs a few minutes.
In this tutorial you design the API for a small event ticketing service. You decide its resources and URLs, what each HTTP method promises, which status code each outcome gets, and how to handle an action that is not create, read, update or delete. You write those decisions into API-DESIGN.md, a one-page document you can take to a review. Then you build a stub in Express 5 that follows the document, with data in memory, and run a curl script that checks every status code the design promises.
The stub keeps validation short on purpose. For a fuller treatment of input checking, error handlers and tests, see build a REST API with Express 5.
Step 1 · Name the resources
A resource is a thing your clients care about, named with a noun. Verbs belong to the HTTP methods, so a well-named resource never needs create or get in its name. For ticketing, read the job out loud: people buy tickets of a certain kind for an event. That gives three nouns: event, ticket type and order.
Make a throwaway folder and start the design document with those nouns and their fields. You can type the file in an editor instead; the content is what matters:
mkdir -p ~/tickets-api-demo
cd ~/tickets-api-demo
cat > API-DESIGN.md <<'MD'
# Tickets API design
Sells tickets for events. JSON in and out. The server makes every ID
(evt_1, tt_1, ord_1); clients never choose them.
## Resources
- Event: a dated show at a venue. Fields: name, venue, startsAt.
- Ticket type: one kind of ticket for one event. Fields: name, capacity, sold.
- Order: one purchase of tickets of one type. Fields: ticketTypeId, quantity, status.
MDThe ID prefixes (evt_, tt_, ord_) cost nothing and make logs and support messages easier to read: a buyer who sends ord_19 by SMS has told you what it is. If you add prices later, store them as whole numbers in the currency's smallest unit with a currency code, such as 250000 and NGN for 2,500 naira, so no rounding creeps in.
Run the remaining commands in this tutorial from ~/tickets-api-demo.
Check it worked
grep -c '^- ' API-DESIGN.mdThe output is 3, one line per resource. Each name is a noun a ticket buyer or box-office worker would use without explanation.
Step 2 · Write the URLs and decide what to nest
Each resource gets two kinds of URL. The collection URL is the plural noun, such as /events. The item URL adds the ID, such as /events/{eventId}. Nesting puts one resource under another, as in /events/{eventId}/ticket-types. Nest when the child cannot exist without the parent and clients always reach it through the parent. Do not nest when clients look the child up on its own, and never go deeper than one level, because every extra level is one more ID each client must carry.
Append the URLs and the reasoning:
cat >> API-DESIGN.md <<'MD'
## URLs
| Collection | Item |
| ------------------------------ | --------------------------------------------- |
| /events | /events/{eventId} |
| /events/{eventId}/ticket-types | /events/{eventId}/ticket-types/{ticketTypeId} |
| /orders | /orders/{orderId} |
Ticket types are nested: one never exists without its event, and clients
reach them from the event page. Orders are not nested: a buyer looks up an
order by the ID on their receipt without knowing the event, and a URL such as
/events/{eventId}/ticket-types/{ticketTypeId}/orders/{orderId} would make
every client carry three IDs to read one order. Nest at most one level.
MDCheck it worked
Look for verbs in the URLs:
grep -Ei '/(get|create|update|delete|add|remove)' API-DESIGN.md || echo "No verbs in URLs"The output is No verbs in URLs. If grep prints a line instead, rename that path to a noun and let the method carry the verb.
Step 3 · Match each method to what it promises
HTTP gives each method a meaning that clients, proxies and caches rely on. Two properties matter most:
- Safe means the request changes nothing on the server.
GETis safe, so a browser may prefetch it and a crawler may follow it. - Idempotent means sending the same request twice leaves the server in the same state as sending it once.
PUTandDELETEare idempotent, so a client can retry them after a timeout without harm.POSTis not: a retriedPOST /ordersbuys the tickets twice.
PUT replaces the whole resource with the body you send, so a body missing a field is an error, not a partial update. PATCH changes only the fields you send. Because this API makes its own IDs, PUT to an ID that does not exist answers 404 rather than creating the resource. Append the endpoint table:
cat >> API-DESIGN.md <<'MD'
## Endpoints
Safe: changes nothing. Idempotent: repeating it leaves the same state,
so a client may retry it after a timeout.
| Method and path | Does | Safe | Idempotent |
| -------------------------------------------------- | ---------------------- | ---- | ---------- |
| GET /events | List events | yes | yes |
| POST /events | Create an event | no | no |
| GET /events/{eventId} | Read one event | yes | yes |
| PUT /events/{eventId} | Replace all its fields | no | yes |
| PATCH /events/{eventId} | Change some fields | no | no (1) |
| DELETE /events/{eventId} | Delete it | no | yes (2) |
| GET /events/{eventId}/ticket-types | List its ticket types | yes | yes |
| POST /events/{eventId}/ticket-types | Add a ticket type | no | no |
| GET /events/{eventId}/ticket-types/{ticketTypeId} | Read one ticket type | yes | yes |
| POST /orders | Buy tickets | no | no |
| GET /orders/{orderId} | Read one order | yes | yes |
(1) PATCH is not guaranteed to be idempotent. Ours only sets fields to the
values sent, so repeats are harmless, but clients must not rely on that.
(2) A second DELETE answers 404, yet the state is the same: still gone.
MDIdempotency matters more than it looks. On a slow mobile connection, or when prepaid data runs out mid-request, the client often cannot tell whether a request reached the server. It can safely retry a PUT. It cannot safely retry POST /orders, which is why payment APIs commonly accept an idempotency key that lets the server spot a repeat.
Check it worked
grep -cE '^\| (GET|POST|PUT|PATCH|DELETE) ' API-DESIGN.mdThe output is 11. Read down the Safe column: only GET rows say yes. Every POST row says no in both columns.
Step 4 · Pick a status code for every outcome
A status code tells the client what happened before it reads the body, so it must be exact. Write down the codes this API uses and when, and use no others without updating the document. The line that teams argue over most is between 400, 422 and 409:
400 Bad Request: the request cannot be read at all, such as a body that is not valid JSON.422 Unprocessable Content: the JSON is fine but breaks a rule, such as a missing name or a capacity of 0.409 Conflict: the request is valid but clashes with the current state, such as buying tickets that have sold out.
Some teams use 400 for rule failures too. Either choice works if you write it down and apply it everywhere. Append the table:
cat >> API-DESIGN.md <<'MD'
## Status codes
| Code | When |
| ---- | -------------------------------------------------------------------- |
| 200 | A GET, PUT, PATCH or action succeeded; the body is the resource |
| 201 | A POST created a resource; the Location header holds its URL |
| 204 | A DELETE succeeded; there is no body |
| 400 | The body is not valid JSON |
| 404 | Nothing exists at this URL |
| 409 | Valid, but clashes with current state: sold out, already cancelled, |
| | or deleting an event that still has confirmed orders |
| 413 | The body is larger than the 10 KB limit |
| 422 | Valid JSON that breaks a rule, including an ID in the body that |
| | matches nothing |
| 500 | An unexpected server error; details go to the log, not the client |
Error bodies: {"error": "message"}, or for 422
{"errors": [{"field": "name", "message": "..."}]} listing every problem.
MDNote the last 422 rule. POST /orders with an unknown ticketTypeId is not a 404, because the URL /orders exists. The problem is a value inside the body.
Check it worked
grep -oE '^\| [0-9]{3} ' API-DESIGN.md | tr -d '| ' | tr '\n' ' '; echoThe output is 200 201 204 400 404 409 413 422 500. For each row of the endpoint table, you can now name every code it may return: POST /orders, for example, returns 201, 400, 409 or 422.
Step 5 · Design an action that does not fit CRUD
Buyers need to cancel orders. Cancelling releases the tickets back to sale and, in a real service, starts a refund. There are three common ways to model it:
PATCH /orders/{orderId}with{"status": "cancelled"}. It looks tidy, but a field edit now triggers a refund, and you must police which status changes are allowed.POST /cancelOrder. A verb in the URL. It works, but it drops the resource model and every action becomes its own endpoint shape.POST /orders/{orderId}/cancellation. The action is named as a noun under the order, it is clearly not safe, and it has its own status codes.
This design takes the third. Some style guides, such as Google's API Improvement Proposals, use a custom method form like /orders/{orderId}:cancel instead. Pick one form and use it for every action. Append the decision and the scope:
cat >> API-DESIGN.md <<'MD'
## Actions
| Method and path | Does | Safe | Idempotent |
| ------------------------------------ | ------------------------------------- | ---- | ---------- |
| POST /orders/{orderId}/cancellation | Cancel the order, release its tickets | no | no |
Cancelling has side effects (tickets go back on sale, a refund starts), so
it is an action, not a PATCH of status. It answers 200 with the cancelled
order, 404 for an unknown order and 409 if it is already cancelled.
## Not in this version
Authentication, pagination, payments and refunds.
MDCheck it worked
wc -l < API-DESIGN.md | tr -d ' 'The output is 80, or close to it if you typed the file yourself: the whole design fits on one printed page. Read it top to bottom and check that every decision has its reason next to it. Those reasons are your answers in review.
Step 6 · Build a stub that follows the design
Now turn the document into running code. Create the project and install Express 5.3. The range ~5.3.0 accepts patch releases of 5.3 only:
npm init -y
npm pkg set type=module
npm install express@~5.3.0Create server.js. Every route below matches a row of the endpoint and action tables, and every status code comes from the status table:
cat > server.js <<'JS'
import express from 'express'
const app = express()
app.disable('x-powered-by')
app.use(express.json({ limit: '10kb' }))
const events = new Map()
const ticketTypes = new Map()
const orders = new Map()
const counters = {}
const newId = (prefix) => `${prefix}_${(counters[prefix] = (counters[prefix] ?? 0) + 1)}`
const notFound = (res, what) => res.status(404).json({ error: `${what} not found` })
const invalid = (res, errors) => res.status(422).json({ errors })
const conflict = (res, message) => res.status(409).json({ error: message })
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value)
const isText = (value) => typeof value === 'string' && value.trim() !== ''
function checkEvent(body) {
if (!isObject(body)) return [{ field: 'body', message: 'must be a JSON object' }]
const errors = []
for (const field of ['name', 'venue']) {
if (!isText(body[field])) errors.push({ field, message: 'must be a non-empty string' })
}
if (typeof body.startsAt !== 'string' || Number.isNaN(Date.parse(body.startsAt))) {
errors.push({ field: 'startsAt', message: 'must be a date-time such as 2027-03-14T18:00:00Z' })
}
return errors
}
const eventFrom = (id, body) => ({
id,
name: body.name.trim(),
venue: body.venue.trim(),
startsAt: body.startsAt,
})
// Events
app.get('/events', (req, res) => res.json([...events.values()]))
app.post('/events', (req, res) => {
const errors = checkEvent(req.body)
if (errors.length > 0) return invalid(res, errors)
const event = eventFrom(newId('evt'), req.body)
events.set(event.id, event)
res.status(201).location(`/events/${event.id}`).json(event)
})
app.get('/events/:eventId', (req, res) => {
const event = events.get(req.params.eventId)
if (!event) return notFound(res, 'Event')
res.json(event)
})
app.put('/events/:eventId', (req, res) => {
const { eventId } = req.params
if (!events.has(eventId)) return notFound(res, 'Event')
const errors = checkEvent(req.body)
if (errors.length > 0) return invalid(res, errors)
const event = eventFrom(eventId, req.body)
events.set(eventId, event)
res.json(event)
})
app.patch('/events/:eventId', (req, res) => {
const current = events.get(req.params.eventId)
if (!current) return notFound(res, 'Event')
if (!isObject(req.body)) return invalid(res, [{ field: 'body', message: 'must be a JSON object' }])
const merged = { ...current, ...req.body }
const errors = checkEvent(merged)
if (errors.length > 0) return invalid(res, errors)
const event = eventFrom(current.id, merged)
events.set(current.id, event)
res.json(event)
})
app.delete('/events/:eventId', (req, res) => {
const { eventId } = req.params
if (!events.has(eventId)) return notFound(res, 'Event')
const busy = [...orders.values()].some((o) => o.eventId === eventId && o.status === 'confirmed')
if (busy) return conflict(res, 'Event has confirmed orders; cancel them first')
for (const [id, type] of ticketTypes) if (type.eventId === eventId) ticketTypes.delete(id)
events.delete(eventId)
res.status(204).end()
})
// Ticket types, nested one level under events
app.get('/events/:eventId/ticket-types', (req, res) => {
const { eventId } = req.params
if (!events.has(eventId)) return notFound(res, 'Event')
res.json([...ticketTypes.values()].filter((type) => type.eventId === eventId))
})
app.post('/events/:eventId/ticket-types', (req, res) => {
const { eventId } = req.params
if (!events.has(eventId)) return notFound(res, 'Event')
const body = req.body
const errors = []
if (!isText(body?.name)) errors.push({ field: 'name', message: 'must be a non-empty string' })
if (!Number.isInteger(body?.capacity) || body.capacity < 1) {
errors.push({ field: 'capacity', message: 'must be a whole number of 1 or more' })
}
if (errors.length > 0) return invalid(res, errors)
const type = { id: newId('tt'), eventId, name: body.name.trim(), capacity: body.capacity, sold: 0 }
ticketTypes.set(type.id, type)
res.status(201).location(`/events/${eventId}/ticket-types/${type.id}`).json(type)
})
app.get('/events/:eventId/ticket-types/:ticketTypeId', (req, res) => {
const type = ticketTypes.get(req.params.ticketTypeId)
if (!type || type.eventId !== req.params.eventId) return notFound(res, 'Ticket type')
res.json(type)
})
// Orders, not nested
app.post('/orders', (req, res) => {
const body = req.body
const errors = []
if (!isText(body?.ticketTypeId)) errors.push({ field: 'ticketTypeId', message: 'is required' })
if (!Number.isInteger(body?.quantity) || body.quantity < 1 || body.quantity > 10) {
errors.push({ field: 'quantity', message: 'must be a whole number from 1 to 10' })
}
if (errors.length > 0) return invalid(res, errors)
const type = ticketTypes.get(body.ticketTypeId)
if (!type) return invalid(res, [{ field: 'ticketTypeId', message: 'matches no ticket type' }])
const left = type.capacity - type.sold
if (body.quantity > left) return conflict(res, `Only ${left} tickets left`)
type.sold += body.quantity
const order = {
id: newId('ord'),
eventId: type.eventId,
ticketTypeId: type.id,
quantity: body.quantity,
status: 'confirmed',
}
orders.set(order.id, order)
res.status(201).location(`/orders/${order.id}`).json(order)
})
app.get('/orders/:orderId', (req, res) => {
const order = orders.get(req.params.orderId)
if (!order) return notFound(res, 'Order')
res.json(order)
})
// An action that does not fit CRUD
app.post('/orders/:orderId/cancellation', (req, res) => {
const order = orders.get(req.params.orderId)
if (!order) return notFound(res, 'Order')
if (order.status === 'cancelled') return conflict(res, 'Order is already cancelled')
order.status = 'cancelled'
ticketTypes.get(order.ticketTypeId).sold -= order.quantity
res.json(order)
})
app.use((req, res) => res.status(404).json({ error: 'Not found' }))
app.use((err, req, res, next) => {
if (res.headersSent) return next(err)
if (err.type === 'entity.parse.failed') return res.status(400).json({ error: 'Body is not valid JSON' })
if (err.type === 'entity.too.large') return res.status(413).json({ error: 'Body is too large' })
console.error(err)
res.status(500).json({ error: 'Internal server error' })
})
const port = Number(process.env.PORT ?? 8080)
app.listen(port, '127.0.0.1', (error) => {
if (error) throw error
console.log(`Tickets API stub on http://127.0.0.1:${port}`)
})
JSA few lines carry design decisions:
- The
DELETEhandler refuses with409while confirmed orders exist. Deleting the event would leave buyers holding orders for nothing. - An unknown
ticketTypeIdin an order body is a422, as the status table says, not a404. - The cancellation handler checks the state first, so a second cancel gets
409and the tickets are released only once. - The last handler maps a body that is not JSON to
400, a body over the 10 KB limit to413, and hides any other error behind a plain500.
Start the server in a second terminal:
cd ~/tickets-api-demo
node server.jsIt prints Tickets API stub on http://127.0.0.1:8080.
Check it worked
Back in the first terminal:
curl -s -w '\n' http://127.0.0.1:8080/eventsThe output is [], an empty list of events.
Step 7 · Check every status code with curl
Rather than trying requests one at a time, write each promise from the design as one line of a script: the status you expect, the method, the path and an optional body. The script sends each request with curl and compares the code it gets. Run it against a freshly started server, because the IDs in it assume an empty store:
cat > check-status.sh <<'SH'
#!/usr/bin/env bash
# One line per promise in API-DESIGN.md: expected status, method, path, body.
base=${BASE:-http://127.0.0.1:8080}
failures=0
expect() {
local want=$1 method=$2 path=$3 body=${4:-}
local args=(-s -o /dev/null -w '%{http_code}' -X "$method")
if [ -n "$body" ]; then
args+=(-H 'Content-Type: application/json' --data "$body")
fi
local got
got=$(curl "${args[@]}" "$base$path")
if [ "$got" = "$want" ]; then
echo "ok $want $method $path"
else
echo "FAIL $method $path: wanted $want, got $got"
failures=$((failures + 1))
fi
}
event='{"name":"Harbour Jazz Night","venue":"Pier Hall","startsAt":"2027-03-14T18:00:00Z"}'
expect 200 GET /events
expect 201 POST /events "$event"
expect 400 POST /events '{"name":'
expect 422 POST /events '{"name":""}'
expect 200 GET /events/evt_1
expect 404 GET /events/evt_999
expect 200 PUT /events/evt_1 "$event"
expect 422 PUT /events/evt_1 '{"name":"Only a name"}'
expect 404 PUT /events/evt_999 "$event"
expect 200 PATCH /events/evt_1 '{"venue":"Pier Hall, upper floor"}'
expect 201 POST /events/evt_1/ticket-types '{"name":"Standard","capacity":2}'
expect 422 POST /events/evt_1/ticket-types '{"name":"VIP","capacity":0}'
expect 404 POST /events/evt_999/ticket-types '{"name":"Standard","capacity":2}'
expect 200 GET /events/evt_1/ticket-types
expect 200 GET /events/evt_1/ticket-types/tt_1
expect 201 POST /orders '{"ticketTypeId":"tt_1","quantity":2}'
expect 409 POST /orders '{"ticketTypeId":"tt_1","quantity":1}'
expect 422 POST /orders '{"ticketTypeId":"tt_999","quantity":1}'
expect 200 GET /orders/ord_1
expect 409 DELETE /events/evt_1
expect 200 POST /orders/ord_1/cancellation
expect 409 POST /orders/ord_1/cancellation
expect 404 POST /orders/ord_999/cancellation
expect 204 DELETE /events/evt_1
expect 404 GET /events/evt_1
expect 404 DELETE /events/evt_1
echo "$failures failures"
[ "$failures" -eq 0 ]
SH
bash check-status.shEach line prints ok with the code, and the last line is 0 failures. Read the middle of the run as a story: the event is created, two tickets go on sale, an order takes both, a third ticket is refused with 409, the event cannot be deleted while the order stands, and after the cancellation the delete succeeds with 204. If a line prints FAIL, either the stub or the design is wrong; decide which, and fix that one.
Check it worked
The script checks codes only. Look at a full 201 response to see the Location header the design promises:
curl -si -w '\n' --json '{"name":"Harbour Jazz Night","venue":"Pier Hall","startsAt":"2027-03-14T18:00:00Z"}' http://127.0.0.1:8080/eventsThe response starts with HTTP/1.1 201 Created and includes Location: /events/evt_2. The ID is evt_2 because the script used and deleted evt_1. The body is the new event with that ID.
Step 8 · See safe and idempotent in practice
The method table makes promises about repeats. Test them. Send the same PUT twice, then the same POST twice:
put='{"name":"Harbour Jazz Night","venue":"Pier Hall","startsAt":"2027-03-14T19:00:00Z"}'
curl -s -w '\n' -X PUT --json "$put" http://127.0.0.1:8080/events/evt_2
curl -s -w '\n' -X PUT --json "$put" http://127.0.0.1:8080/events/evt_2
post='{"name":"Poetry Evening","venue":"Library Hall","startsAt":"2027-04-02T17:00:00Z"}'
curl -s -o /dev/null -w '%{http_code}\n' --json "$post" http://127.0.0.1:8080/events
curl -s -o /dev/null -w '%{http_code}\n' --json "$post" http://127.0.0.1:8080/eventsBoth PUT responses print the same event, with "startsAt":"2027-03-14T19:00:00Z": the second changed nothing. Both POST requests answer 201, and each made a new event. That is the retry problem from the method table, now on your own server.
Check it worked
curl -s http://127.0.0.1:8080/events | grep -o '"name":"Poetry Evening"' | wc -l | tr -d ' 'The output is 2: one duplicate event, created by a repeated POST. A repeated PUT could never do that.
Step 9 · Stop the server and clean up
Press Ctrl+C in the server terminal. If you want to keep the design document, copy ~/tickets-api-demo/API-DESIGN.md somewhere else first. Then delete the folder, which holds only what you made here:
cd ~
rm -rf ~/tickets-api-demoCheck it worked
ls ~/tickets-api-demo reports that there is no such file or directory, and curl http://127.0.0.1:8080/events fails to connect.
Next steps
- Turn
API-DESIGN.mdinto a machine-readable contract: describe an API with an OpenAPI 3.2 document. - Grow the stub into a real service with validation, error handling and tests: build a REST API with Express 5.
- Get more out of curl when you debug an API: test and debug an API with curl.
Part of these paths
Related tutorials
- How to Build a REST API with Express 5You will build a small items API with Express 5.3 on Node.js 26 that validates its input, returns the right HTTP status codes, never sends a stack trace to callers, and has automated tests that use only Node's built-in test runner.
- How to Test and Debug an API with curlYou will write a small practice API, then call it with curl 8 to read responses and headers, send JSON, send an authorization header without putting the secret on the command line, follow redirects, measure timing, set timeouts and retries, and read curl's verbose output when a request goes wrong.
- Describe an API with an OpenAPI 3.2 documentYou will write an OpenAPI 3.2 contract for a ticketing API by hand across several files, lint it clean with Redocly CLI 2, bundle it into one file and generate TypeScript types that a client uses against a mock server.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials