HTTP and APIs · Lesson 12 of 18
REST: resources and status codes
Design noun-based URLs and use verbs and status codes as stable contracts.
A REST API exposes resources such as /tasks and /tasks/42, not actions like /getTasks. The HTTP method carries the action: GET reads, POST creates, PUT replaces, PATCH partially updates and DELETE removes. The contract includes schema, status and errors.
GET /tasks
POST /tasks
PATCH /tasks/:id
DELETE /tasks/:id
function result(method, exists) {
if (method === "POST") return { status: 201, body: "created" }
if (!exists) return { status: 404, body: "not found" }
if (method === "DELETE") return { status: 204, body: "" }
return { status: 200, body: "ok" }
}
console.log(result("POST", false).status, result("GET", false).status, result("DELETE", true).status)Common statuses: 200 success, 201 created with Location, 204 success without a body, 400 malformed request, 401 unauthenticated, 403 known but forbidden, 404 absent, 409 conflict, 422 validation failure, and 500 unexpected server failure.
Quick question
A resource was created successfully. Best status?
Exercise
Write statusFor(action, found) returning 201 for create, 404 when absent, 204 for delete, otherwise 200. Print 201 404 204 200.
Expected output: 201 404 204 200
function statusFor(action, found) {
}
console.log(statusFor("create", false), statusFor("read", false), statusFor("delete", true), statusFor("read", true))Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.