| |

REST API 26 ๐ŸŒ Cheatsheet โ€” The Complete REST API Reference

โฑ๏ธ Estimated read: 9 min | |

This chapter is not a tutorial. It is a condensed reference for everything covered in the REST API series, organized for lookup rather than reading. Each section maps to a chapter, keeps only the facts that matter in practice, and omits the explanations that the chapters already provide. Use it when you know what you are looking for and need the exact syntax, status code, or header value without re-reading the full treatment.

Key point: A cheatsheet is useful only if it is accurate. Every entry here corresponds to a verified fact from the preceding twenty-five chapters. When in doubt, return to the source chapter rather than improvising.


01. REST and Architectural Constraints

ConstraintMeaning
Client-serverUI and data storage separate; independent evolution
StatelessEach request carries all context; no server session
CacheableResponses must declare cacheability
Uniform interfaceResources identified by URIs; manipulation via representations
Layered systemClient sees only the immediate layer
Code on demand (optional)Server may send executable code
PrincipleRule
Resource identificationEverything is a resource; URIs name them
RepresentationJSON is a representation, not the resource
StatelessnessEvery request includes auth and context

02. Resources, URIs, and Naming

ConventionExample
Plural nouns/users, /orders
Hierarchical/users/42/orders
No verbs in paths/users/42 not /getUser/42
Lowercase, hyphens/user-profiles not /userProfiles
No file extensions/users not /users.json
PatternURI
CollectionGET /users
Single itemGET /users/42
Sub-collectionGET /users/42/orders
Sub-itemGET /users/42/orders/7

03. HTTP Methods

MethodSemanticsSafeIdempotentBody
GETRead resourceYesYesNo
POSTCreate / non-idempotent actionNoNoYes
PUTReplace entire resourceNoYesYes
PATCHPartial updateNoNot guaranteedYes
DELETERemove resourceNoYesNo
HEADMetadata onlyYesYesNo
OPTIONSCapabilities / CORS preflightYesYesNo
RuleDetail
GET has no side effectsNever mutate on GET
PUT replacesOmitted fields are removed
PATCH mergesOmitted fields are untouched

04. Request and Response Headers

HeaderDirectionPurpose
Content-TypeRequestFormat of sent body
AcceptRequestDesired response format
AuthorizationRequestCredentials
User-AgentRequestClient identification
Content-TypeResponseFormat of response body
LocationResponseURI of created resource (201)
ETagResponseVersion tag for caching
Cache-ControlBothCaching directives
ValueMeaning
application/jsonJSON body
application/problem+jsonRFC 7807 error
application/x-www-form-urlencodedForm body
multipart/form-dataFile upload

05. Status Codes

CodeMeaningUse
200OKSuccessful GET/PUT/PATCH
201CreatedSuccessful POST; include Location
204No ContentSuccessful DELETE, no body
301 / 308Moved PermanentlyURI changed
304Not ModifiedClient cache is valid
400Bad RequestMalformed syntax
401UnauthorizedMissing/invalid credentials
403ForbiddenAuthenticated, not permitted
404Not FoundResource absent (also for unauthorized objects)
409ConflictState conflict (duplicate, version)
422Unprocessable EntityValid syntax, invalid semantics
429Too Many RequestsRate limited
500Internal Server ErrorUnexpected failure
502Bad GatewayUpstream failure
503Service UnavailableTemporarily down

06. JSON Payload Design

RuleExample
camelCase or snake_case, one convention{"firstName": "A"} or {"first_name": "A"}
Consistent date formatISO 8601: "2026-10-21T14:32:00Z"
No null for absent optional fieldsOmit the field
IDs as strings if opaque"id": "ord_8871"
No trailing commasInvalid JSON
Anti-patternFix
Mixed conventionsPick one, enforce with schema
Numbers as strings"total": 99.99 not "99.99"
Nulls everywhereOmit optional fields

07. Query Parameters

PurposeSyntax
Filter?status=active&role=admin
Sort?sort=-created_at,name
Search?q=widget
Fields?fields=id,name
Pagination?limit=20&offset=40
RuleDetail
- prefix for descending?sort=-created_at
Commas for multiple values?fields=id,name
Array syntax for repeated?tag=a&tag=b or ?tag[]=a&tag[]=b

08. Pagination

StrategyParamsProsCons
Offset?limit=20&offset=40Simple, jump to pageSlow on deep pages
Cursor?limit=20&cursor=abcStable under insertsNo random access
Keyset?after=1043&limit=20EfficientRequires indexed key
Response fieldPurpose
items or dataCurrent page
next_cursorOpaque cursor for next page
has_moreWhether more pages exist
totalTotal count (offset only)

09. Input Validation and Error Handling

ValidationWhen
Schema validationAt request boundary, before business logic
Type coercionReject wrong types, do not coerce silently
Length limitsStrings, arrays, bodies
Range checksNumbers, dates
Allow-listEnums, not free-form strings
Error fieldPurpose
typeURI identifying error class
titleHuman-readable summary
detailSpecific explanation
instanceRequest URI

10. RFC 7807 Problem Details

FieldTypePurpose
typestring (URI)Error class
titlestringShort summary
statusintegerHTTP status
detailstringSpecific explanation
instancestring (URI)Request URI
(extension)anyAdditional context
{
  "type": "https://example.com/errors/validation",
  "title": "Validation failed",
  "status": 422,
  "detail": "The 'email' field is not a valid address.",
  "instance": "/api/users"
}

Media type: application/problem+json.


11. Authentication Methods

MethodHeaderUse When
API keyX-API-Key: <key> or Authorization: ApiKey <key>Server-to-server
BasicAuthorization: Basic <base64(user:pass)>Only over HTTPS, legacy
BearerAuthorization: Bearer <token>User sessions, OAuth
RuleDetail
Never in URLKeys in query strings are logged
Always over HTTPSCredentials in plaintext otherwise
Rotate keysSupport multiple active keys during rotation

12. JWT and Refresh Tokens

JWT partContent
Header{"alg": "HS256", "typ": "JWT"}
PayloadClaims: sub, exp, iat, iss, aud
SignatureHMAC or RSA over header + payload
ClaimPurpose
subSubject (user ID)
expExpiration (Unix time)
iatIssued at
issIssuer
audAudience
RuleDetail
Validate algReject none
Validate expReject expired
Validate signatureAlways, server-side
Short-lived access5โ€“15 minutes
Refresh rotationOne-time refresh tokens

13. OAuth 2.0 and OIDC

FlowUse When
Authorization Code + PKCEWeb and mobile apps
Client CredentialsServer-to-server
Device CodeInput-constrained devices
Implicit (deprecated)Never; use PKCE
EndpointPurpose
/authorizeUser grants consent
/tokenExchange code for tokens
/introspectValidate opaque token
/.well-known/openid-configurationOIDC discovery
OIDC tokenPurpose
ID token (JWT)User identity claims
Access tokenAPI access
Refresh tokenObtain new access tokens

14. RBAC vs ABAC

ModelBasisExample
RBACRole of calleradmin can delete users
ABACAttributes of caller + resourceowner can edit own document
ReBACRelationship graphmember of team can access repo
RuleDetail
Never trust client-declared rolesRoles come from the server’s identity store
Object-level check is separateRBAC does not cover ownership (API1)
Policy engineOPA, Casbin for centralized rules

15. CORS

HeaderPurpose
Access-Control-Allow-OriginAllowed origin(s)
Access-Control-Allow-MethodsAllowed HTTP methods
Access-Control-Allow-HeadersAllowed request headers
Access-Control-Allow-CredentialsSend cookies
Access-Control-Max-AgePreflight cache duration
RuleDetail
Never * with credentialsBrowser rejects it
Explicit originshttps://app.example.com
Preflight for non-simpleCustom headers, PUT, DELETE

16. Rate Limiting

HeaderMeaning
X-RateLimit-LimitMax requests per window
X-RateLimit-RemainingRemaining in window
X-RateLimit-ResetWindow reset time
Retry-AfterSeconds to wait (429)
AlgorithmBehavior
Fixed windowSimple, burst at boundary
Sliding windowSmoother, more memory
Token bucketAllows bursts up to capacity
Leaky bucketConstant output rate
RuleDetail
Per-consumer limitsNot just per-IP
429 with Retry-AfterTell client when to retry
Separate login limits5/min for credential endpoints

17. Caching

HeaderPurpose
Cache-Control: public, max-age=3600Cacheable for 1 hour
Cache-Control: private, no-storeNever cache
ETagVersion identifier
Last-ModifiedTimestamp version
If-None-MatchConditional request (ETag)
If-Modified-SinceConditional request (date)
StatusMeaning
200Fresh response
304Not Modified; use cache
412Precondition failed
RuleDetail
ETag for per-resourceStrong or weak (W/"...")
Vary for negotiationVary: Accept-Encoding, Accept-Language
No caching for sensitive datano-store

18. API Versioning

StrategyExampleProsCons
URI/v1/usersExplicit, cacheableURI churn
Query?version=1SimpleEasy to miss
HeaderAccept: application/vnd.api+json; version=1Clean URIHidden
Content negotiationAccept-Version: 1FlexibleHarder to debug
RuleDetail
Breaking change = new versionAdditive changes do not need one
Deprecation headersSunset, Deprecation
Support overlapOld and new version coexist during migration

19. Idempotency Keys

HeaderPurpose
Idempotency-Key: <uuid>Client-generated unique key
RuleDetail
Stored server-sideKey โ†’ response mapping
TTL24โ€“48 hours typical
Same key, same responseReplay returns original result
Key per attemptRetries reuse; new operations use new key
Required for POSTOnly for non-idempotent writes

20. API Testing Tools

ToolTypeUse
cURLCLIQuick checks, scripts
PostmanGUICollections, environments, collaboration
BrunoGUI/CLIGit-friendly, offline-first
httpieCLIHuman-readable output
NewmanCLIRun Postman collections in CI
cURL commandPurpose
curl -X POST -H "Content-Type: application/json" -d '{}' URLPOST JSON
curl -H "Authorization: Bearer $TOKEN" URLAuthenticated GET
curl -i URLInclude headers in output
curl -o file URLSave body to file

21. Automated Testing

Test typeScopeSpeed
UnitSingle functionMilliseconds
IntegrationAPI + real DBSeconds
End-to-endFull workflowMinutes
Schema validationResponse structureMilliseconds
RuleDetail
Integration asserts persistenceQuery DB after HTTP call
Mock external servicesReal internal dependencies
Factories for test dataNever depend on seed data
CI stagingUnit โ†’ Integration โ†’ E2E

22. OpenAPI and Swagger

SectionPurpose
openapiSpec version (3.0.3, 3.1.0)
infoTitle, version, description
serversBase URLs
pathsEndpoint definitions
componentsReusable schemas, security
ToolPurpose
Swagger EditorAuthor and validate
Swagger UIInteractive rendering
RedocRead-only reference
OpenAPI GeneratorClient SDK generation
Redocly CLILint, bundle, build
CommandPurpose
redocly lint openapi.yamlValidate
redocly build-docs openapi.yamlStatic HTML
redocly bundle openapi.yamlResolve $ref

23. Webhooks

Handler stageActionFailure response
1Verify signature on raw body401
2Parse JSON400
3Check event ID for duplicate200 (no side effect)
4Process event5xx (retry)
5Mark processed, acknowledge200
HeaderPurpose
X-Webhook-SignatureHMAC-SHA256 of raw body
X-Webhook-TimestampReplay protection
X-Webhook-IdIdempotency key (alternate)
ResponseProvider behavior
2xxNo retry
4xx (except 429)No retry
429Retry after delay
5xxRetry with backoff
RuleDetail
Verify before parsingSignature covers raw bytes
Constant-time comparehmac.compare_digest
Queue-firstEnqueue, return 2xx, process async
ReconciliationPoll API for missed events

24. OWASP API Top 10 (2023)

RiskFailureFix
API1 BOLAObject accessed without ownership checkScope query to authenticated user
API2 Broken AuthTokens unverifiedValidate signature, expiry, algorithm
API3 Property AuthMass assignment, data exposureAllow-list request and response
API4 Resource UseNo size or cost limitsServer-enforced caps
API5 Function AuthAdmin endpoint open to usersCentralized role middleware
API6 Business FlowAutomation abuseCAPTCHA, fingerprinting
API7 SSRFUser URL fetched uncheckedAllow-list hosts, block private IPs
API8 MisconfigurationWildcard CORS, verbose errorsExplicit origins, generic errors
API9 InventoryForgotten endpointsEndpoint inventory, deprecation
API10 Unsafe ConsumptionThird-party data trustedSchema validation
RuleDetail
BOLA fix is a query changeWHERE id=? AND user_id=?
404 for unauthorizedAvoids enumeration signal
Allow-list both directionsRequest body and response body
Gateway is not authorizationServices still enforce object-level

25. Gateways, Proxies, Load Balancing

ComponentPrimary jobScope
Reverse proxyForward and secureInfrastructure
Load balancerDistribute across replicasAvailability
API gatewayGovern API consumersPolicy and identity
NGINX directivePurpose
upstreamDefine backend group
proxy_passForward to upstream
least_connLeast-connections algorithm
ip_hashSession persistence
max_fails / fail_timeoutPassive health checks
limit_req_zoneRate limiting
proxy_set_header X-Real-IPForward client IP
LayerJob
L4 load balancerDistribute TCP connections
API gatewayPer-route auth, quotas
Service meshEast-west mTLS, retries
RuleDetail
One job per layerRemove layers that duplicate
Gateway latency~5โ€“9ms p99 versus plain proxy
Trace >20% proxy timeRemove redundancy
Do not use gateway for single serviceReverse proxy costs less

Summary

ChapterCore takeaway
01REST is six constraints; statelessness is the defining one
02Plural nouns, hierarchical URIs, no verbs
03GET/PUT/DELETE idempotent; POST is not
04Content-Type describes body; Accept describes wanted response
05201 for create, 204 for delete, 404 for hidden
06One naming convention, ISO 8601 dates, no nulls for absent
07?sort=-field, ?fields=id,name
08Cursor for stability, offset for random access
09Validate at boundary, reject wrong types
10RFC 7807 with application/problem+json
11API key, Basic, Bearer โ€” never in URL
12Validate alg, exp, signature; refresh with rotation
13Authorization Code + PKCE for users; Client Credentials for services
14RBAC for roles; object-level check is separate
15Explicit origins; never * with credentials
16Per-consumer limits; 429 with Retry-After
17ETag + If-None-Match โ†’ 304
18URI versioning for clarity; deprecation headers
19Idempotency-Key for POST; replay returns original
20cURL for scripts; Postman/Bruno for collections
21Integration asserts persistence; E2E asserts workflow
22Spec is the contract; tools derive from it
23Verify โ†’ parse โ†’ idempotency โ†’ process
24BOLA is top risk; scope queries to user
25One job per layer; remove redundant proxies

Key takeaways:

  • The most common production bugs are authorization gaps. Chapters 14 and 24 are the ones to revisit when an API is compromised. BOLA accounts for the single largest category of real-world API incidents, and its fix is a query change, not a framework upgrade.
  • Idempotency is the difference between a retry and a duplicate. Chapters 03, 19, and 23 all touch this. GET, PUT, and DELETE are safe to retry by design. POST requires an Idempotency-Key. Webhook handlers require an event ID check.
  • HTTP status codes carry semantics that clients depend on. Returning 200 with {"error": ...} breaks every client that checks status codes. 201 with Location, 204 with no body, 404 for both missing and unauthorized โ€” these are contracts, not suggestions.
  • Caching is a contract between client and server. Cache-Control, ETag, If-None-Match, and 304 are the mechanism. A server that omits Cache-Control on a cacheable response forces clients to re-download data that has not changed.
  • The testing pyramid is a division of responsibility. Unit tests catch logic errors. Integration tests catch wiring errors. End-to-end tests catch workflow errors. None substitutes for the others, and CI staging keeps feedback fast.
  • The OpenAPI spec is the source; everything else is derived. Documentation, client SDKs, mock servers, and contract tests all read the same file. Hand-editing the rendered docs instead of the spec guarantees drift.
  • Security is structural, not additive. Authorization in the data access layer, allow-lists for fields, server-enforced limits, and centralized role checks prevent entire classes of vulnerabilities by construction.

Remember: This cheatsheet compresses twenty-five chapters into lookup tables. It is useful for confirming syntax, checking a status code, or finding the right header name. It is not a substitute for the chapters themselves when you need to understand why a pattern exists or how to apply it to a situation the tables do not cover. The most valuable entries are the ones that are easy to get wrong: idempotency keys, RFC 7807 format, CORS credentials rules, JWT alg validation, BOLA query scoping, and webhook signature verification. These are the details that separate an API that works in a demo from one that survives production.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!