REST API Cheat Sheet

Complete REST API quick reference: HTTP methods, status codes, headers, authentication patterns, pagination, error handling, and URL design best practices.

On This Page

HTTP Methods

Method Idempotent Safe Request Body Use Case
GET Retrieve a resource or collection
POST Create a new resource
PUT Replace a resource entirely
PATCH Partially update a resource
DELETE Remove a resource
OPTIONS Describe communication options (CORS preflight)
HEAD Get headers only (no response body)

Status Codes

2xx Success

CodeNameDescription
200OKRequest succeeded. Standard response for successful GET, PUT, PATCH requests.
201CreatedResource created successfully. Return after POST with Location header pointing to new resource.
204No ContentRequest succeeded but no content to return. Common response for DELETE requests.

3xx Redirection

CodeNameDescription
301Moved PermanentlyResource has a new permanent URL. Clients should update bookmarks. SEO-friendly redirect.
302FoundResource temporarily at a different URL. Original URL should still be used for future requests.
304Not ModifiedResource has not changed since last request. Client should use cached version. Saves bandwidth.
307Temporary RedirectLike 302, but the HTTP method must not change. POST stays POST.
308Permanent RedirectLike 301, but the HTTP method must not change. POST stays POST.

4xx Client Errors

CodeNameDescription
400Bad RequestMalformed syntax, invalid parameters, or missing required fields in the request.
401UnauthorizedAuthentication required. Missing or invalid credentials. Include WWW-Authenticate header.
403ForbiddenAuthenticated but not authorized. The user does not have permission for this action.
404Not FoundResource does not exist at the given URL. Also used to hide existence of forbidden resources.
405Method Not AllowedHTTP method not supported on this endpoint (e.g., POST on a read-only resource).
409ConflictRequest conflicts with current server state (e.g., duplicate entry, version mismatch).
422Unprocessable EntityRequest is syntactically valid but semantically incorrect (e.g., validation errors).
429Too Many RequestsRate limit exceeded. Check Retry-After and X-RateLimit headers for timing info.

5xx Server Errors

CodeNameDescription
500Internal Server ErrorGeneric server error. Something went wrong but the server cannot be more specific.
502Bad GatewayServer acting as proxy received an invalid response from the upstream server.
503Service UnavailableServer temporarily unable to handle requests (overloaded or in maintenance).
504Gateway TimeoutServer acting as proxy did not receive a timely response from the upstream server.

URL Naming Conventions

REST API URL Design Rules

RuleGoodBad
Use nouns, not verbs /users /getUsers
Plural resource names /users, /posts /user, /post
Nested resources for relationships /users/123/posts /getUserPosts?userId=123
Query params for filtering /users?role=admin&status=active /users/role/admin/status/active
Lowercase with hyphens /blog-posts /BlogPosts or /blog_posts
Version in URL path /v1/users /users?version=1
No trailing slashes /users /users/
No file extensions /users/123 /users/123.json

Keep nesting shallow — avoid going deeper than two levels (e.g., /users/123/posts is fine, /users/123/posts/456/comments/789/likes is too deep).

Common Headers

Request Headers

HeaderDescriptionExample
AuthorizationAuthentication credentialsBearer eyJhbGci...
Content-TypeMedia type of the request bodyapplication/json
AcceptMedia types the client can handleapplication/json
Accept-LanguagePreferred response languageen-US, en;q=0.9
If-None-MatchConditional request (ETag)"a1b2c3d4"
If-Modified-SinceConditional request (date)Mon, 10 Feb 2026 08:00:00 GMT
X-Request-IDUnique identifier for request tracing550e8400-e29b-41d4
User-AgentClient application identifierMyApp/1.0

Response Headers

HeaderDescriptionExample
Content-TypeMedia type of the response bodyapplication/json; charset=utf-8
LocationURL of newly created resource/api/users/43
ETagEntity tag for caching"a1b2c3d4"
Cache-ControlCaching directivesmax-age=3600, public
Retry-AfterWhen to retry after 429 or 50360 (seconds)
LinkPagination links (RFC 8288)</users?page=3>; rel="next"
X-Request-IDEcho request ID for tracing550e8400-e29b-41d4
Access-Control-Allow-OriginCORS allowed originshttps://app.example.com

Authentication Methods

MethodHeaderBest ForNotes
API Key X-API-Key: abc123 Server-to-server, simple integrations Easy to implement. Send in header or query param. No expiration by default.
Bearer Token Authorization: Bearer eyJ... SPAs, mobile apps, microservices Most common pattern. Typically JWT. Include expiration and refresh flow.
Basic Auth Authorization: Basic dXNlcjpwYXNz Simple internal APIs, testing Base64-encoded username:password. Always use HTTPS. Not suitable for production user-facing APIs.
OAuth 2.0 Authorization: Bearer <token> Third-party integrations, social login Delegated authorization. Flows: Authorization Code, Client Credentials, PKCE for SPAs.

Pagination Patterns

Offset-Based Pagination

Simple and widely used. Allows jumping to any page. Can be slow on large datasets.

GET /api/users?page=2&per_page=20

Response Headers:
  X-Total-Count: 150
  Link: </api/users?page=3&per_page=20>; rel="next",
        </api/users?page=1&per_page=20>; rel="prev",
        </api/users?page=8&per_page=20>; rel="last"

Response Body:
{
  "data": [...],
  "meta": {
    "page": 2,
    "per_page": 20,
    "total": 150,
    "total_pages": 8
  }
}

Cursor-Based Pagination

Better performance on large datasets. No skipping pages. Consistent results even when data changes.

GET /api/users?cursor=abc123&limit=20

Response Body:
{
  "data": [...],
  "meta": {
    "next_cursor": "def456",
    "has_more": true
  }
}

Use offset pagination for small/medium datasets where users need page numbers. Use cursor pagination for large datasets, real-time feeds, or infinite scroll.

Error Response Format

Standard Error Response

Always return a consistent error structure across your API:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request body contains invalid fields.",
    "details": [
      {
        "field": "email",
        "message": "Must be a valid email address."
      },
      {
        "field": "age",
        "message": "Must be a positive integer."
      }
    ]
  }
}
FieldTypeDescription
error.codestringMachine-readable error code (e.g., NOT_FOUND, RATE_LIMITED)
error.messagestringHuman-readable error description
error.detailsarrayOptional. Per-field validation errors or additional context

CRUD Mapping

How standard CRUD operations map to HTTP methods in a REST API:

Action Method URL Status Code
List all GET /api/users 200 OK
Get one GET /api/users/123 200 OK
Create POST /api/users 201 Created
Replace PUT /api/users/123 200 OK
Update PATCH /api/users/123 200 OK
Delete DELETE /api/users/123 204 No Content

Content Negotiation

How Content Negotiation Works

The client specifies what format it wants using the Accept header, and what format it is sending using the Content-Type header:

# Client requests JSON response and sends JSON body
POST /api/users HTTP/1.1
Accept: application/json
Content-Type: application/json

{"name": "Jane Doe"}

# Client requests XML response
GET /api/users/123 HTTP/1.1
Accept: application/xml

# Client sends form data
POST /api/login HTTP/1.1
Content-Type: application/x-www-form-urlencoded

username=jane&password=secret
Content TypeUse Case
application/jsonMost common for REST APIs. Lightweight and widely supported.
application/xmlLegacy APIs, enterprise integrations, SOAP services.
multipart/form-dataFile uploads mixed with form fields.
application/x-www-form-urlencodedHTML form submissions. Key-value pairs.
text/plainSimple text responses, logs, health checks.
application/octet-streamBinary file downloads.

Rate Limiting Headers

HeaderDescriptionExample
X-RateLimit-LimitMaximum number of requests allowed in the window1000
X-RateLimit-RemainingNumber of requests remaining in the current window742
X-RateLimit-ResetUnix timestamp when the rate limit window resets1707667200
Retry-AfterSeconds to wait before retrying (sent with 429 response)30

Rate Limit Response Example

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1707667200
Retry-After: 30

{
  "error": {
    "code": "RATE_LIMITED",
    "message": "Rate limit exceeded. Try again in 30 seconds."
  }
}

Frequently Asked Questions

What is a REST API and how does it work?

REST (Representational State Transfer) is an architectural style for designing networked applications. A REST API uses standard HTTP methods (GET, POST, PUT, PATCH, DELETE) to perform CRUD operations on resources identified by URLs. It is stateless, meaning each request contains all information needed to process it. REST APIs typically exchange data in JSON format and use HTTP status codes to indicate success or failure.

What is the difference between PUT and PATCH in a REST API?

PUT replaces an entire resource with the provided data (full update), requiring you to send all fields even if only one changed. PATCH applies a partial modification, sending only the fields that need to change. PUT is always idempotent by specification, while PATCH is typically idempotent by convention. For most update operations, PATCH is more practical because it uses less bandwidth and does not risk overwriting unchanged fields with defaults.

How should I handle errors in a REST API?

REST API errors should use appropriate HTTP status codes (4xx for client errors, 5xx for server errors) and return a consistent JSON error response body. A good error response includes a machine-readable error code, a human-readable message, and optionally a details array for validation errors. Common patterns include: 400 for bad requests, 401 for unauthorized, 403 for forbidden, 404 for not found, 422 for validation errors, and 429 for rate limiting.

What are the best practices for REST API URL design?

REST API URLs should use plural nouns for resources (e.g., /users, /posts), not verbs (avoid /getUsers). Use nested paths for relationships (e.g., /users/123/posts). Use query parameters for filtering, sorting, and pagination (e.g., /users?role=admin&sort=name). Keep URLs lowercase with hyphens for multi-word resources. Avoid deep nesting beyond two levels, and use versioning in the URL path (e.g., /v1/users) or via headers.