Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

REST API Security and Design Cheat Sheet

A one-page REST API cheat sheet: status codes, headers, authentication choices, token rules, security checklist, pagination, caching and error format, with two demos.

This is a one-page reminder for everything in this part of the course: which status code to send, which authentication to pick, what to check on every request, and which headers to set. Each section links to the lesson that explains the topic in depth. Two small demos at the end turn the most error-prone decisions (status codes and error bodies) into code you can run.

Five habits of a solid API

Authenticate Verify the token, every time.
Authorize Check the role and the object.
Validate Allowlist fields, cap sizes.
Limit Rate limits and page caps.

Plus consistent errors and HTTPS everywhere.

1 / 2

Status codes

Code Name Use it when
200 OK A read or update succeeded and you return a body
201 Created A new resource was created; send Location
202 Accepted Work was queued; return a status URL
204 No Content Success with no body (usual for DELETE)
304 Not Modified Conditional GET matched the ETag
400 Bad Request Malformed syntax, such as invalid JSON
401 Unauthorized Missing or invalid credentials; send WWW-Authenticate
403 Forbidden Authenticated but not allowed (including missing scope)
404 Not Found No such resource (also used to hide other users' records)
405 Method Not Allowed Wrong method; send Allow
409 Conflict State conflict, such as a duplicate email
410 Gone Permanently removed (retired API version)
412 Precondition Failed If-Match or If-Unmodified-Since failed
413 Content Too Large Body exceeds the limit
415 Unsupported Media Type Wrong Content-Type
422 Unprocessable Content Valid JSON, but values break your rules
428 Precondition Required Client must send If-Match
429 Too Many Requests Rate limit hit; send Retry-After
500 Internal Server Error Your bug; generic message only
502, 503, 504 Bad gateway, unavailable, timeout Upstream or overload problems; Retry-After on 503

Authentication quick guide

Method Best for Watch out for
Session cookie (HttpOnly, Secure, SameSite) First-party browser apps CSRF protection
Bearer access token (JWT or opaque) Mobile, SPAs, service calls Short life, pinned algorithm, JWT pitfalls
Refresh token Renewing access tokens Rotate, hash at rest, detect reuse (lesson)
OAuth 2.0 code + PKCE Third-party apps acting for a user Exact redirect URI, state (lesson)
OpenID Connect "Sign in with..." Validate iss, aud, exp, nonce (lesson)
Client credentials Server-to-server Keep the secret on servers
API key Developer and partner access Hash at rest, scope, rotate (lesson)
Basic auth Only over HTTPS, for simple internal tools Weak, no revocation per session

JWT checklist

TEXT
alg pinned (never none)        exp set (5-15 min for access tokens)
iss and aud checked            leeway for clock skew (about 30 s)
secret 32+ random bytes        kid for key rotation (RS256, ES256)
no secrets in the payload      revocation plan: jti denylist or short life

Security checklist for every endpoint

  1. HTTPS only, HSTS on.
  2. Authentication required unless the route is deliberately public.
  3. Object-level check: the record belongs to the caller (BOLA).
  4. Function-level check: role or scope allows the action; deny by default.
  5. Input validated: types, lengths, ranges, unknown fields rejected, body size capped (lesson).
  6. Writable fields allowlisted; response fields explicit.
  7. Parameterized queries; no user input in shell commands or file paths.
  8. Rate limit by key, user and IP; stricter on login and expensive routes (lesson).
  9. CORS allowlist of exact origins, never * with credentials (lesson).
  10. Errors are generic outward, detailed in private logs; no tokens or passwords in logs.

Headers you will use

Header Direction Purpose
Authorization: Bearer <token> Request Credentials
WWW-Authenticate: Bearer Response (401) Tells clients how to authenticate
Content-Type: application/json Both Body format
Location Response (201, 3xx) URL of the new resource
Cache-Control, ETag, Vary Response Caching (lesson)
If-None-Match, If-Match Request Conditional GET, safe updates
Retry-After, RateLimit-* Response Rate limit state
Link: <...>; rel="next" Response Pagination links
Deprecation, Sunset Response Retirement of old versions (lesson)
Strict-Transport-Security, X-Content-Type-Options Response Transport and content hardening

Pagination, caching and versions at a glance

  • Pagination: always paginate; default 20, maximum 100; prefer cursors for feeds and large tables, with a total sort order (lesson).
  • Caching: public, max-age for static reference data, private, no-cache for personal data, no-store for secrets; validate with ETag.
  • Versions: add, never remove or change within a version; /v1 in the path is the simplest; announce deprecation with headers and dates.
  • Docs and tests: OpenAPI file in the repository, linted in CI; contract tests for each consumer (OpenAPI, Contract testing).

Demo: choosing a status code

Most status code mistakes come from skipping questions in the right order. A decision function written once makes the order explicit: authentication first, then existence, then permission, then input.

Node.js A status code decision function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Demo: a consistent error body

Use one error shape for every failure. This helper builds an RFC 9457 "problem details" object, so clients can parse every error the same way and never see internals.

Node.js Problem Details error responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Send these with Content-Type: application/problem+json, and log the real error server-side with the same request ID.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A request has a valid token but the token lacks the needed scope. Which status?

    The caller is identified but not permitted, so 403.
  2. 2. Which Cache-Control value suits a response containing personal data that may be reused after revalidation?

    Private keeps shared caches out, and no-cache requires revalidation before reuse.
  3. 3. Which credential fits a nightly server-to-server job?

    There is no user, so the application authenticates as itself.
  4. 4. What should a 500 response body contain?

    Internals help attackers. Log them privately and give the client a correlation ID.
  5. 5. In which order should an endpoint check things?

    Cheap identity and access checks come first, so unauthenticated callers learn nothing about validation rules or data.

Summary

  • Choose status codes in a fixed order: syntax, authentication, limits, existence and ownership, permission, preconditions, validation, then success.
  • Pick credentials by caller: cookies for first-party browsers, OAuth with PKCE for third-party apps, client credentials for services, scoped keys for developers.
  • Every endpoint needs authentication, object and function checks, validated input, allowlisted fields, limits and safe errors.
  • Set caching, pagination and version headers deliberately, and document and test the contract.
  • Use one problem-details error shape and never leak internals.

Next: REST APIs and Authentication