REST API Cheat Sheet
Practical REST API reference covering HTTP methods, status codes, headers, authentication, JSON payloads, pagination, filtering, versioning, caching, idempotency, and API design best practices.
📚 Quick Navigation
Core REST Methods
REST APIs use HTTP verbs to describe intent. Keep resource URLs noun-based and let the method communicate the action.
GET /api/users
POST /api/users
GET /api/users/42
PUT /api/users/42
PATCH /api/users/42
DELETE /api/users/42
HEAD /api/users/42
OPTIONS /api/usersWhen to Use Each Method
Use GET for reads, POST for creates, PUT for full replacement, PATCH for partial updates, and DELETE for removal. Action verbs in URLs are usually a smell.
GET /orders # Read a collection
GET /orders/123 # Read one resource
POST /orders # Create a new resource
PUT /orders/123 # Replace the full resource
PATCH /orders/123 # Update part of a resource
DELETE /orders/123 # Delete a resource
# Avoid action-style endpoints like:
POST /createOrder
POST /deleteUserSafe vs Idempotent
Safe means read-only. Idempotent means repeating the same request should not create extra side effects. This matters for retries, caching, and client error recovery.
# Safe methods: should not change server state
GET /products
HEAD /products/10
OPTIONS /products
# Idempotent methods: same request repeated => same result
PUT /profile/42
DELETE /sessions/5
# Not inherently idempotent
POST /paymentsGood RESTful URL Patterns
Model URLs around resources. Use plural nouns for collections, IDs for single records, and query parameters for filtering or sorting.
# Collections
/api/users
/api/products
/api/orders
# Single resource
/api/users/42
/api/orders/abc123
# Nested resources
/api/users/42/orders
/api/orders/123/items
# Filtering via query string
/api/products?category=laptops&inStock=trueNaming Rules
Prefer lowercase kebab-case URLs. Keep names stable, readable, and predictable for developers and client applications.
# Good
/api/blog-posts
/api/user-profiles
/api/invoices/2024-001
# Avoid
/api/getUsers
/api/UserProfile
/api/blog_posts
/api/doPaymentNowCommon CRUD Mapping
A predictable CRUD mapping makes your API easier to learn and easier to document. Clients should not have to guess endpoint behavior.
GET /articles -> list articles
POST /articles -> create article
GET /articles/15 -> fetch article 15
PATCH /articles/15 -> update article 15
DELETE /articles/15 -> remove article 15
GET /articles/15/comments
POST /articles/15/commentsMost Important REST API Status Codes
Status codes tell clients what happened. Pick the narrowest correct code instead of dumping everything into 200 or 500.
200 OK # Successful GET, PUT, PATCH
201 Created # Resource created successfully
202 Accepted # Request accepted for async processing
204 No Content # Success with no response body
400 Bad Request # Invalid request syntax or malformed body
401 Unauthorized # Missing or invalid authentication
403 Forbidden # Authenticated but not allowed
404 Not Found # Resource does not exist
409 Conflict # Resource state conflict
422 Unprocessable Entity # Validation failed
429 Too Many Requests # Rate limit hit
500 Internal Server Error # Unexpected server error
503 Service Unavailable # Temporary outage or maintenanceTypical Responses by Action
Tie status codes to the operation outcome. Good API clients depend on these patterns for correct UI and retry behavior.
# Create
POST /api/users
-> 201 Created
Location: /api/users/42
# Delete
DELETE /api/users/42
-> 204 No Content
# Validation failure
POST /api/users
-> 422 Unprocessable Entity
# Missing resource
GET /api/users/999
-> 404 Not FoundQuick 4xx vs 5xx Rule
If the client can fix the request, it is usually 4xx. If your server or dependency broke, it is usually 5xx.
4xx = client sent a bad request
5xx = server failed to handle a valid request
# Examples
400 -> malformed JSON body
401 -> bad token
404 -> unknown resource
422 -> field validation error
500 -> uncaught exception
503 -> database or upstream service downCommon Request Headers
Headers tell the server what format the client expects, how the request is authenticated, and how caching or optimistic concurrency should work.
Accept: application/json
Content-Type: application/json
Authorization: Bearer <token>
If-None-Match: "etag-value"
If-Match: "etag-value"
X-Request-ID: 7f3a2c91-...Common Response Headers
Response headers provide metadata about the payload, caching behavior, pagination links, or the location of newly created resources.
Content-Type: application/json; charset=utf-8
Cache-Control: public, max-age=300
ETag: "user-42-v5"
Last-Modified: Fri, 10 Apr 2026 10:00:00 GMT
Location: /api/users/42
Link: </api/products?page=3>; rel="next"JSON API Request Example
A good REST request usually declares both the accepted response format and the submitted content type, especially for JSON APIs.
POST /api/users HTTP/1.1
Host: api.example.com
Accept: application/json
Content-Type: application/json
Authorization: Bearer eyJhbGci...
{
"name": "Alice",
"email": "alice@example.com"
}Bearer Token Authentication
Bearer tokens are the most common REST API auth mechanism. Keep access tokens short-lived and send them over HTTPS only.
GET /api/me HTTP/1.1
Authorization: Bearer <access-token>
Accept: application/jsonAPI Key Authentication
API keys are simple for server-to-server integrations, but putting them in URLs is risky because URLs leak into logs, analytics, and browser history.
# Header-based API key
GET /api/metrics
X-API-Key: your-api-key
# Query-string API keys are discouraged
GET /api/metrics?api_key=your-api-key401 vs 403
Use 401 when the identity is missing or invalid. Use 403 when the identity is valid but access should still be denied.
401 Unauthorized
# You are not authenticated
# Example: missing token, expired token, invalid token
403 Forbidden
# You are authenticated but do not have permission
# Example: normal user trying to access admin endpointTypical JSON Success Response
JSON is the default for modern REST APIs. Use consistent naming, consistent date formatting, and stable field types.
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 42,
"name": "Alice",
"email": "alice@example.com",
"createdAt": "2026-04-10T10:12:00Z"
}Collection Response Example
For lists, return the records plus metadata such as total count, current page, and page size. That saves clients from guessing pagination state.
{
"data": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
],
"meta": {
"total": 120,
"page": 1,
"pageSize": 20
}
}PATCH Request Example
PATCH should send only the fields being changed. PUT should normally replace the full resource representation.
PATCH /api/users/42
Content-Type: application/json
{
"displayName": "Alice Cooper",
"newsletter": true
}Offset Pagination
Offset or page-based pagination is easy to understand and document. It works well for many admin panels and moderate datasets.
GET /api/products?page=2&pageSize=25
{
"data": [...],
"meta": {
"page": 2,
"pageSize": 25,
"total": 240,
"totalPages": 10
}
}Cursor Pagination
Cursor pagination is better for large or rapidly changing datasets because it avoids duplicates and missing items between pages.
GET /api/events?limit=20&cursor=eyJpZCI6MTIzfQ==
{
"data": [...],
"pageInfo": {
"nextCursor": "eyJpZCI6MTQzfQ==",
"hasMore": true
}
}Filtering and Sorting
Use query parameters for filters, search terms, and sorting. Keep the syntax consistent across your API so clients can build reusable helpers.
GET /api/products?category=laptops&brand=dell&minPrice=500&maxPrice=2000&sort=-createdAt
# Possible sort patterns
sort=name
sort=-createdAt
sort=price,-ratingValidation Error Response
Validation errors should be machine-readable. Include a stable error code and field-level details so clients can render useful UI.
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request body is invalid.",
"details": [
{ "field": "email", "message": "Email is required." },
{ "field": "password", "message": "Password must be at least 12 characters." }
]
}
}Generic Error Shape
Keep error payloads consistent across the API. A predictable error format reduces frontend conditionals and makes observability cleaner.
{
"error": {
"code": "RESOURCE_NOT_FOUND",
"message": "User not found.",
"requestId": "req_01HR..."
}
}What Not to Expose
Do not leak raw stack traces, SQL errors, internal hostnames, or library details to clients. Log them server-side instead.
# Bad
{
"error": "SQLSTATE[23000]: Integrity constraint violation..."
}
# Better
{
"error": {
"code": "INTERNAL_ERROR",
"message": "Something went wrong.",
"requestId": "req_123"
}
}URL Versioning
URL versioning is explicit and easy to understand. It is the most common choice for public APIs because it is simple to document and test.
GET /api/v1/users
GET /api/v2/usersHeader Versioning
Header-based versioning keeps URLs cleaner, but it is less obvious for developers and harder to debug without good tooling.
GET /api/users
Accept: application/vnd.example.v2+jsonVersioning Guidance
Do not version for every tiny change. Additive changes often do not need a new version. Reserve new versions for breaking contract changes.
# Prefer backwards-compatible evolution when possible
- Add new optional fields
- Avoid renaming or removing fields abruptly
- Deprecate before removal
- Document breaking changes clearlyHTTP Caching Basics
Leverage built-in HTTP caching before inventing custom solutions. Cache headers are cheap performance wins for read-heavy APIs.
Cache-Control: public, max-age=300
ETag: "posts-v12"
Last-Modified: Fri, 10 Apr 2026 09:45:00 GMTConditional GET with ETag
ETags let clients avoid downloading unchanged responses. This reduces payload size and speeds up repeat reads.
GET /api/posts/42
If-None-Match: "posts-42-v7"
# If unchanged
304 Not ModifiedOptimistic Concurrency with If-Match
Use If-Match or version fields to avoid lost updates when multiple clients edit the same resource at the same time.
PATCH /api/posts/42
If-Match: "posts-42-v7"
Content-Type: application/json
{
"title": "Updated title"
}
# If version mismatch
409 ConflictDesign Checklist
A good REST API is predictable. Clients should be able to infer patterns instead of learning each endpoint from scratch.
✓ Use nouns, not verbs, in URLs
✓ Return correct HTTP status codes
✓ Keep JSON fields consistent
✓ Validate input strictly
✓ Document auth, rate limits, and errors
✓ Support filtering, sorting, and pagination
✓ Include request IDs for debugging
✓ Use HTTPS everywhereRate Limiting Example
If your API has limits, expose them clearly. That helps clients back off properly instead of hammering the server blindly.
HTTP/1.1 429 Too Many Requests
Retry-After: 60
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1712748600Example cURL Requests
Concrete examples make docs much more useful. cURL snippets are still the fastest universal way to explain API usage.
# GET collection
curl -H "Accept: application/json" https://api.example.com/users
# POST create
curl -X POST https://api.example.com/users -H "Content-Type: application/json" -H "Authorization: Bearer <token>" -d '{"name":"Alice","email":"alice@example.com"}'
# PATCH update
curl -X PATCH https://api.example.com/users/42 -H "Content-Type: application/json" -d '{"name":"Alice Cooper"}'What is a REST API?
A REST API is an HTTP-based interface built around resources, standard methods, and stateless requests. In practice, that means clients interact with URLs such as /api/users or /api/orders/123 using verbs like GET, POST, PATCH, and DELETE.
Good REST API design is about predictability. The best APIs use consistent URL structure, correct HTTP status codes, useful error payloads, and clean pagination or filtering rules so frontend developers and backend teams can move quickly without constant clarification.
Why REST is Popular
- ▸Built directly on standard HTTP semantics
- ▸Easy to test with browsers, cURL, Postman, and frontend apps
- ▸Works well with JSON, caching, CDNs, and proxies
- ▸Clear resource-based design is familiar to most developers
- ▸Strong fit for public APIs, admin panels, mobile backends, and SaaS integrations
REST API Rules That Matter Most
- ✓Use nouns in URLs and let HTTP methods define the action
- ✓Return precise status codes instead of generic success or failure
- ✓Keep requests stateless and authenticate each request properly
- ✓Design pagination, filters, and error shapes consistently
- ✗Do not treat REST as random JSON over HTTP with no contract
REST vs RPC Style Endpoints
| Approach | REST Style | Less RESTful / RPC Style |
|---|---|---|
| List users | GET /api/users | POST /api/getUsers |
| Create user | POST /api/users | POST /api/createUser |
| Delete user | DELETE /api/users/42 | POST /api/deleteUser?id=42 |
| Update user email | PATCH /api/users/42 | POST /api/updateUserEmail |
REST API Best Practice Notes
Use 201 Created for successful creation
Include a Location header or the created resource body so clients know exactly what was created.
Treat error payloads as part of the contract
Frontend code relies on stable error codes and field-level validation details just as much as success responses.
Do not overload POST for everything
If every endpoint is POST, clients lose the benefits of idempotency, caching, semantics, and predictable tooling behavior.
Be careful with PUT vs PATCH
PUT normally replaces the full representation. If you only change a few fields, PATCH is often the safer and clearer option.
Expose request IDs
Returning a request ID in headers or error payloads makes debugging production issues much less painful.
Use HTTP caching where it makes sense
ETags, Cache-Control, and conditional requests are boring, which is exactly why they are useful. They solve real API performance problems well.