rest_api 86 Q&As

REST API FAQ & Answers

86 expert REST API answers researched from official documentation. Every answer cites authoritative sources you can verify.

unknown

86 questions
A

REST (Representational State Transfer) is an architectural style for distributed systems defined by Roy Fielding in 2000. Six constraints: (1) Client-Server separation - independent evolution, (2) Stateless - each request self-contained with all context, (3) Cacheable - responses explicitly indicate cacheability, (4) Uniform interface - standardized interactions via HTTP methods (RFC 9110), (5) Layered system - intermediaries like proxies/gateways allowed, (6) Code-on-demand (optional) - executable code transfer. RESTful APIs use HTTP methods (GET/POST/PUT/PATCH/DELETE) per RFC 9110 HTTP Semantics (2022), resources identified by URIs (RFC 3986), representations typically JSON. Not a protocol but architectural constraints ensuring scalability, reliability, performance. Foundation of modern web APIs, microservices, cloud services. 2025 practice: combine with OpenAPI 3.1 specs, HATEOAS for discoverability.

99% confidence
A

GET method retrieves resource representations per RFC 9110 section 9.3.1. Usage: GET /users (collection), GET /users/123 (specific resource), GET /products?category=electronics&limit=20 (filtered). Characteristics: Safe (no side effects), Idempotent (repeated calls = same result), Cacheable (enable Cache-Control, ETag headers). Conditional requests: If-None-Match (ETag validation), If-Modified-Since (timestamp validation) return 304 Not Modified to save bandwidth. Response codes: 200 OK (success with body), 304 Not Modified (cached valid), 404 Not Found (resource missing), 400 Bad Request (invalid query params). Best practices 2025: implement pagination (cursor-based preferred), support field selection (?fields=id,name), add rate limiting headers (X-RateLimit-*), never use GET for operations with side effects. Example: GET /api/v1/users?status=active&sort=-created_at&limit=50.

99% confidence
A

POST method creates resources or processes data per RFC 9110 section 9.3.3. Usage: POST /users (create), POST /orders (submit), POST /auth/login (process). Characteristics: Not idempotent (multiple calls create duplicates), Not cacheable, Request body contains data (JSON/form-data). Response codes: 201 Created (success, includes Location: /users/456 header + created resource body), 202 Accepted (async processing, return job URL), 400 Bad Request (validation failed), 409 Conflict (duplicate resource), 422 Unprocessable Entity (semantic errors). Example: POST /api/v1/users with {"name":"John","email":"[email protected]"} returns 201 Created, Location: /users/456, body: {"id":456,"name":"John","email":"[email protected]","created_at":"2025-11-14T12:00:00Z"}. Best practices 2025: implement Idempotency-Key header (UUID) for safe retries, validate all inputs server-side, return created resource in response body.

99% confidence
A

PUT method replaces entire resources idempotently per RFC 9110 section 9.3.4. Usage: PUT /users/123 (full replacement), PUT /config/settings (upsert). Characteristics: Idempotent (repeated calls = same state), Requires complete resource representation, Can create if doesn't exist (201) or update (200). Response codes: 200 OK (updated, with body), 204 No Content (updated, no body), 201 Created (resource created), 404 Not Found (parent doesn't exist), 400 Bad Request (validation failed). Example: PUT /api/v1/users/123 with {"id":123,"name":"John Updated","email":"[email protected]","role":"admin"} returns 200 OK with full updated resource. Best practices 2025: use PUT for complete replacement only, PATCH for partial updates, implement optimistic locking (If-Match: ) to prevent lost updates, validate all required fields present. PUT semantics: must send ALL fields, omitted fields treated as null/deleted.

99% confidence
A

PATCH method performs partial resource modifications per RFC 5789. Usage: PATCH /users/123 (update subset of fields). Two standard formats: (1) JSON Merge Patch (RFC 7396) - simple, send changed fields: {"email":"[email protected]"} merges into resource, set null to delete: {"middleName":null}. (2) JSON Patch (RFC 6902) - precise operations array: [{"op":"replace","path":"/email","value":"[email protected]"},{"op":"remove","path":"/middleName"}]. Operations: add, remove, replace, move, copy, test. Response codes: 200 OK (with updated resource), 204 No Content, 400 Bad Request (invalid patch), 409 Conflict (precondition failed). Best practices 2025: validate only provided fields, use Content-Type: application/merge-patch+json or application/json-patch+json, implement Idempotency-Key for safe retries, combine with If-Match (ETag) for optimistic locking. PATCH preferred over PUT for bandwidth efficiency, mobile clients.

99% confidence
A

DELETE method removes resources idempotently per RFC 9110 section 9.3.5. Usage: DELETE /users/123 (remove resource), DELETE /sessions/current (logout). Characteristics: Idempotent (repeated calls = same state, subsequent DELETE returns 404), No request body typically needed, Supports If-Match header for conditional deletion. Response codes: 204 No Content (deleted, standard response), 200 OK (deleted with confirmation body), 202 Accepted (async deletion queued), 404 Not Found (already deleted or never existed), 409 Conflict (cannot delete due to dependencies). Example: DELETE /api/v1/users/123 returns 204 No Content, next DELETE /users/123 returns 404 Not Found. Best practices 2025: implement soft deletes (deleted_at timestamp) for audit trails, verify authorization carefully, document cascade behavior (related resources), return 404 for both non-existent and already-deleted to maintain idempotency. Consider bulk DELETE with query params: DELETE /users?status=inactive.

99% confidence
A

HEAD method (RFC 9110 section 9.3.2) retrieves metadata without body - identical headers to GET but no content. Usage: check resource existence (200 vs 404), get Content-Length/Last-Modified/ETag without data transfer for bandwidth efficiency. Example: HEAD /api/v1/files/large.zip returns 200 OK, Content-Length: 52428800, no body downloaded. OPTIONS method (RFC 9110 section 9.3.7) describes communication options for target resource. Returns Allow: GET, POST, PUT, DELETE, PATCH header listing supported methods. Primary use: CORS preflight requests - browser sends OPTIONS before actual request with custom headers. Example: OPTIONS /users/123 returns 200 OK, Allow: GET, PUT, PATCH, DELETE, Access-Control-Allow-Methods: GET, PUT, PATCH, DELETE. Both safe and idempotent. Best practices 2025: implement OPTIONS for CORS support, use HEAD for efficient resource validation, include Accept-Patch, Accept-Post headers in OPTIONS responses.

99% confidence
A

2xx codes (RFC 9110 section 15.3) indicate successful request processing. 200 OK: standard success for GET/PUT/PATCH with resource body. 201 Created: resource created via POST, MUST include Location: /resource/123 header pointing to new resource, body contains created resource. 202 Accepted: request queued for async processing, return job tracking URL in Location header or body. 204 No Content: success with no response body (DELETE, PUT/PATCH returning nothing). 206 Partial Content: range request fulfilled, include Content-Range: bytes 0-1023/2048 header. Best practices 2025: use 201 (not 200) for POST creation, always add Location header with 201/202, use 204 for DELETE (not 200 with empty body), implement 206 for large file downloads with Range support. IANA Status Code Registry defines all official codes. Avoid non-standard 2xx codes.

99% confidence
A

4xx codes (RFC 9110 section 15.5) indicate client errors. 400 Bad Request: malformed syntax, invalid JSON, type errors. 401 Unauthorized: authentication missing/invalid, include WWW-Authenticate header. 403 Forbidden: authenticated but lacks permissions (NEVER 401 for authorization failures). 404 Not Found: resource doesn't exist. 405 Method Not Allowed: HTTP method unsupported, include Allow: GET, POST header. 409 Conflict: state conflict (duplicate email, concurrent modification). 422 Unprocessable Entity: valid syntax but semantic errors (email format invalid, age < 0). 429 Too Many Requests (RFC 6585): rate limited, MUST include Retry-After: 60 header. Best practices 2025: use RFC 7807 Problem Details format for error bodies, return 422 (not 400) for validation errors, use 404 (not 403) for missing resources to prevent information disclosure, implement proper 429 rate limiting with headers.

99% confidence
A

5xx codes (RFC 9110 section 15.6) indicate server failures. 500 Internal Server Error: unexpected condition, unhandled exception (log full trace internally, mask details in response). 501 Not Implemented: functionality not supported (rare). 502 Bad Gateway: gateway/proxy received invalid response from upstream service. 503 Service Unavailable: temporarily overloaded or down for maintenance, MUST include Retry-After: 120 header (seconds or HTTP-date). 504 Gateway Timeout: upstream timeout exceeded. Best practices 2025: NEVER expose stack traces/internal details in 5xx responses (security risk per OWASP API Security 2023), always include correlation/request ID (X-Request-ID header) for debugging, use 503 (not 500) for planned maintenance, log all 5xx errors for monitoring/alerts, return RFC 7807 Problem Details with safe error info. Distinguish temporary (503, retryable) from permanent (500, investigate). Monitor 5xx rate as key SLI.

99% confidence
A

3xx codes (RFC 9110 section 15.4) indicate redirection. 301 Moved Permanently: resource permanently relocated, clients update bookmarks, MUST include Location header. 302 Found: temporary redirect (legacy, method may change to GET). 304 Not Modified: conditional request (If-None-Match, If-Modified-Since), resource unchanged, no body sent (bandwidth optimization). 307 Temporary Redirect: temporary with method preserved (use instead of 302). 308 Permanent Redirect: permanent with method preserved (use instead of 301 for POST/PUT). Usage: 301 for deprecated API version (/api/v1/* → /api/v2/*), 304 for cache validation (ETag/Last-Modified), 307 for temporary maintenance mode, 308 for permanent endpoint migration. Best practices 2025: prefer 307/308 over 302/301 (method preservation), always include Location header, implement 304 with ETag for bandwidth savings, use Sunset header (RFC 8594) before applying 301 for API deprecation.

99% confidence
A

REST API URL design per RFC 3986 and 2025 best practices: (1) Nouns not verbs - GET /users (not /getUsers), HTTP method is the verb. (2) Plural nouns for collections - /users, /products, /orders (consistency). (3) Resource hierarchy - /users/123/orders/456 (max 2-3 levels to avoid complexity). (4) Lowercase with hyphens - /user-profiles (not /user_profiles or /userProfiles). (5) No file extensions - /users (not /users.json), use Accept: application/json header. (6) Version in URL - /api/v1/users (recommended), /api/v2/users for breaking changes. (7) Query params for filtering - /users?status=active&role=admin&limit=20. (8) Use UUIDs or slugs - /users/550e8400-e29b-41d4-a716-446655440000 (security, not sequential IDs). (9) Consistent naming - choose camelCase or snake_case globally. Examples: GET /api/v1/organizations/acme/teams/engineering/members?status=active.

99% confidence
A

REST API versioning strategies for 2025: (1) URI versioning (most common): /api/v1/users - straightforward, cache-friendly, easily discoverable. (2) Header versioning: Accept: application/vnd.myapi.v2+json or custom X-API-Version header - cleaner URLs but harder to debug. (3) Query parameter: /users?version=2 - flexible but complicates caching. Best practices: version from day one, use major versions only for breaking changes (field removal, type changes, required field additions), maintain old versions during 6-12 month deprecation period. URI versioning recommended for REST APIs due to simplicity and developer experience. Include version in all responses. Document migration paths between versions. Never remove versions without proper deprecation notice.

99% confidence
A

Idempotency: multiple identical requests produce same result as single request (RFC 9110). Idempotent methods: GET, PUT, DELETE, HEAD, OPTIONS (safe retries). Non-idempotent: POST (creates duplicates), PATCH (depends on implementation). Critical benefits 2025: safe automatic retries on network failures, resilience in distributed systems, prevents duplicate payments/orders. Implementation via Idempotency-Key header: client generates UUID (128+ bits entropy), sends Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000, server stores result in cache (Redis) with key, duplicate requests return cached result (200 OK, not 201). TTL: 24 hours typical. ACID requirement: recording token + mutation must be atomic transaction. Example: POST /payments with Idempotency-Key prevents duplicate charges on retry. AWS best practice: incorporate client request identifier into API contract. Essential for production reliability, payment processing, order creation.

99% confidence
A

REST API pagination strategies for 2025: (1) Cursor-based (recommended): /users?limit=20&after=opaque_cursor - stable, efficient, prevents duplicate/skipped records when data changes. Use opaque base64-encoded cursors to allow internal logic changes. (2) Offset-based: /users?limit=20&offset=40 - simple but unstable with concurrent writes. (3) Keyset/seek: /users?limit=20&after_id=100 - efficient, stable. Response best practices: include next/prev links (RFC 8288 Link header), has_more boolean, cursor/page metadata. Example response headers: Link: </users?after=xyz>; rel="next". Set default limit (20-50) and max limit (100) to prevent abuse. Cursor-based ideal for feeds, real-time data, infinite scroll. Use offset only for small, stable datasets with jump-to-page UI.

99% confidence
A

JWT (JSON Web Token - RFC 7519) provides stateless authentication. Structure: header.payload.signature (base64url encoded). Implementation 2025 per RFC 8725 Best Practices: (1) Client POST credentials to /auth/login, (2) Server validates, returns JWT with short expiration (15-30 min access token + refresh token), (3) Client sends Authorization: Bearer , (4) Server validates signature + claims every request. Required claims: sub (user ID), iat (issued timestamp), exp (expiration), aud (audience). Algorithm: use RS256 (RSA 2048-bit) or ES256 (ECDSA), NEVER alg: none. Key size: HS256 requires 256+ bit secret (32 ASCII chars minimum). Security 2025: enforce HTTPS only, store tokens in httpOnly cookies (not localStorage, XSS risk), validate signature cryptographically, check exp claim, implement token rotation, use refresh tokens for long sessions. Return 401 for invalid/missing/expired tokens, 403 for valid but insufficient permissions. Example: {"sub":"user123","exp":1731600000,"role":"admin"}.

99% confidence
A

OAuth 2.0/2.1 provides delegated authorization for REST APIs (2025 best practices per RFC 9700). Grant types: (1) Authorization Code with PKCE (mandatory for all clients in OAuth 2.1) - web/mobile apps, (2) Client Credentials - server-to-server, (3) Device Code - IoT/limited input devices. Flow: (1) Client initiates with code_challenge (PKCE), (2) User consents at /oauth/authorize, (3) Server returns authorization code, (4) Client exchanges code + code_verifier for tokens at /oauth/token, (5) Client uses access token in Authorization: Bearer header. Security 2025: PKCE required (not optional), short-lived access tokens (15-30 min), refresh token rotation (RTR), no implicit flow (deprecated). Scopes define permissions granularly. Validate tokens on every request, implement proper CORS for browser clients.

99% confidence
A

API key authentication provides simple server-to-server access control for REST APIs. Implementation methods: (1) Custom header X-API-Key: (recommended, secure), (2) Authorization: Bearer (standard), (3) Query parameter ?api_key= (avoid - leaks in logs/URLs). Key format: cryptographically random 32+ character string or UUID v4. Storage: hash keys using bcrypt/argon2 (never plaintext), store with metadata (created_at, last_used, rate_limits). Validation: verify hashed key, check expiration/revocation status, track usage. Security 2025: require HTTPS only, implement per-key rate limits, support key rotation without downtime, allow instant revocation. Monitor for: repeated invalid keys (brute force), unusual usage patterns. Best for: internal APIs, B2B integrations. Use OAuth/JWT for user-facing authentication.

99% confidence
A

RBAC controls REST API access based on user roles and permissions. Implementation steps: (1) Define roles (admin, editor, viewer) with clear hierarchies, (2) Map permissions to roles (users:create, posts:delete, analytics:view), (3) Assign roles to users via user.role_id, (4) Enforce permissions on every endpoint request. Database schema: users (id, role_id), roles (id, name), permissions (id, action, resource), role_permissions (role_id, permission_id). Middleware validates user.role.permissions.includes('posts:delete') before allowing access. JWT integration: embed role/permissions in token claims for stateless validation. Response codes: 401 (unauthenticated), 403 (authenticated but forbidden). Advanced: implement attribute-based access (ABAC) for resource-level rules like 'user can edit own posts'. OWASP API Security 2023: addresses broken authorization (API1, API5). Essential for enterprise APIs, multi-tenant systems.

99% confidence
A

HATEOAS (Hypermedia As The Engine Of Application State) is the REST constraint where responses include hypermedia links to available actions. Example: { "id": 1, "name": "User", "_links": { "self": "/users/1", "orders": "/users/1/orders", "edit": { "href": "/users/1", "method": "PUT" } } }. Benefits: self-documenting API, client decoupling from URL structures, evolvable (add operations without breaking clients). Industry reality 2025: most JSON APIs don't implement HATEOAS (pragmatic REST). JSON isn't natural hypermedia; HTML/hypermedia are better suited. Use cases: complex workflows requiring discoverability, public APIs needing evolution flexibility, HAL/JSON:API formats. Skip for: small internal APIs, tightly-coupled clients, performance-critical APIs. If implementing, use standards: HAL, JSON:API, or Siren. Most teams prioritize OpenAPI documentation over HATEOAS.

99% confidence
A

REST API error handling best practices 2025: (1) Use correct HTTP status codes - 400 (bad syntax), 401 (unauthenticated), 403 (forbidden), 404 (not found), 422 (validation failed), 429 (rate limited), 500 (server error), 503 (unavailable). (2) Consistent RFC 7807 Problem Details format: { "type": "https://api.example.com/errors/validation", "title": "Validation Failed", "status": 422, "detail": "Email format invalid", "instance": "/users/123", "errors": [{ "field": "email", "message": "Must be valid email" }] }. (3) Include trace/request ID for debugging. (4) Never expose stack traces in production. (5) Provide actionable error messages. (6) Use error codes for programmatic handling. (7) Return 429 with Retry-After header for rate limits. OWASP API Security: proper error handling prevents information disclosure.

99% confidence
A

REST API filtering enables clients to retrieve specific resource subsets. Patterns 2025: (1) Equality: /users?status=active&role=admin, (2) Multiple values: /users?role=admin,moderator (CSV) or /users?role[]=admin&role[]=moderator (array syntax), (3) Range operators: /products?price[gte]=10&price[lte]=100, /events?date[between]=2025-01-01,2025-12-31, (4) Pattern matching: /users?name[contains]=john, /users?email[startswith]=admin. Implementation: parse query parameters, validate against field whitelist, build parameterized database queries (never string concatenation). Security: prevent SQL injection using prepared statements, limit filter complexity (max fields, operators), sanitize all inputs. Performance: index all filterable columns. Standards: JSON:API filter parameter, OData $filter. Example: GET /products?category=electronics&price[lte]=1000&rating[gte]=4&in_stock=true returns filtered, production-ready results.

99% confidence
A

REST API sorting controls result ordering via query parameters. Standard patterns 2025: (1) Single field: /users?sort=created_at (ascending default), (2) Direction prefix: /users?sort=-created_at (- for descending, + for ascending), (3) Multiple fields: /users?sort=name,-created_at (primary: name asc, secondary: created_at desc), (4) Explicit direction: /users?order_by=created_at&direction=desc. Implementation: parse sort parameter, validate field names against whitelist (prevent SQL injection), build ORDER BY clause with parameterization, handle NULL values (NULLS FIRST/LAST in SQL). Security: only allow sorting on indexed columns to prevent DoS via slow queries. Consistency: establish deterministic tie-breaking (add secondary sort on ID) for stable pagination. Standards: JSON:API sort parameter. Example: GET /products?sort=-price,+name,id orders by price descending, name ascending, ID ascending (deterministic).

99% confidence
A

REST API search enables text-based resource discovery. Implementation approaches 2025: (1) Simple search: /users?q=john searches across multiple fields (name, email, bio), (2) Field-specific: /users?name=john&email=*@gmail.com for targeted queries, (3) Dedicated endpoint: GET /search?q=tutorial&type=articles with relevance ranking. Backend options: (1) SQL LIKE/ILIKE (basic, case-insensitive), (2) PostgreSQL full-text search (tsvector/tsquery with GIN indexes, stemming), (3) Elasticsearch/OpenSearch (advanced ranking, facets, autocomplete), (4) Algolia/Meilisearch (managed, instant search), (5) Vector/semantic search (embeddings for meaning-based results). Response: include relevance scores, highlighted matches, total count, facets. Performance: index searchable fields, implement pagination, cache common queries. Example: GET /search?q=react+hooks&facet=category,author returns ranked results with filter counts.

99% confidence
A

REST API response design best practices 2025: (1) Consistent JSON structure across all endpoints, (2) Naming convention - choose camelCase or snake_case globally, never mix, (3) No envelope for simple responses ({ "id": 1, "name": "User" }), envelope for metadata ({ "data": {...}, "meta": { "page": 1 } }), (4) Timestamps in ISO 8601 with timezone: "2025-11-13T14:30:00Z", (5) POST 201 returns created resource + Location header, (6) Null handling - be consistent (include nulls or omit), document choice, (7) Include pagination metadata (total, hasMore, nextCursor), (8) Error responses follow RFC 7807 Problem Details, (9) Content-Type: application/json header, (10) Include API version in X-API-Version header. Consistency critical for developer experience and API adoption.

99% confidence
A

Rate limiting algorithms for REST APIs (2025 best practices): (1) Token Bucket (recommended) - tokens refill at constant rate, requests consume tokens, allows controlled bursts. Config: capacity=100, refill=10/second. (2) Sliding Window Log - precise tracking of requests in rolling time window, prevents boundary gaming. (3) Sliding Window Counter - hybrid approach, efficient + accurate. (4) Fixed Window - simple, resets at intervals, but allows burst at boundaries (avoid for critical APIs). (5) Leaky Bucket - constant request processing rate, smooth traffic. Implementation: Redis for distributed systems (INCR/EXPIRE or sorted sets), in-memory for single server. Rate limit by: user ID, API key, IP address (careful with proxies). Return 429 with X-RateLimit headers + Retry-After. API gateway integration (Kong, AWS API Gateway, Cloudflare) recommended. Monitor violations, adjust limits based on patterns.

99% confidence
A

REST API rate limiting headers (2025 standards): Include in every response: (1) X-RateLimit-Limit or RateLimit-Limit: max requests per window ("1000"), (2) X-RateLimit-Remaining or RateLimit-Remaining: requests left in current window ("743"), (3) X-RateLimit-Reset or RateLimit-Reset: Unix timestamp when limit resets ("1700000000"). For 429 responses: (4) Retry-After: seconds until retry allowed ("60") per RFC 6585. Optional: X-RateLimit-Policy for multi-tier limits. IETF draft standard (RateLimit-* without X- prefix) gaining adoption. Implementation: calculate remaining = limit - current_usage, include headers in ALL responses (not just 429), support CORS preflight. Client benefits: implement exponential backoff, display quota in UI, schedule batch operations. Example: RateLimit-Limit: 100, RateLimit-Remaining: 87, RateLimit-Reset: 1731513600, Retry-After: 45.

99% confidence
A

Partial responses/field selection optimizes REST API bandwidth for client needs. Implementation patterns 2025: (1) fields parameter: /users?fields=id,name,email returns only specified fields, (2) Sparse fieldsets (JSON:API): /users?fields[users]=name,email&fields[posts]=title for multiple resource types, (3) Nested paths: /users/123?fields=id,profile.avatar,settings.theme for deep selection. Benefits: reduced bandwidth (critical for mobile), faster responses, improved performance on constrained devices. Implementation: parse fields parameter, validate against field whitelist (prevent NoSQL injection), handle nested objects carefully, maintain type safety. Default behavior: return full resource representation. Security: never expose internal/sensitive fields via field selection. Alternative: GraphQL for complex field requirements. Document all selectable fields and nested path syntax. Use for: mobile apps, bandwidth-constrained networks, large resource payloads.

99% confidence
A

REST API caching best practices 2025: (1) Cache-Control header - max-age=3600 (1 hour), public (CDN cacheable), private (user-specific), no-cache (revalidate), no-store (sensitive data). (2) ETag (entity tag) - content hash, client sends If-None-Match, return 304 Not Modified if match (bandwidth saved). (3) Last-Modified - timestamp-based, client sends If-Modified-Since for conditional requests. (4) Vary header - Vary: Accept-Encoding, Accept-Language caches different representations. (5) Expires - legacy fallback. HTTP methods: GET/HEAD cacheable, POST/PUT/PATCH/DELETE not cacheable. Layers: (1) Browser cache (private data), (2) CDN (public resources, Cloudflare/Fastly), (3) Application cache (Redis for computed results). Invalidation: update ETag on resource changes, use cache-busting for static assets. Essential for scalability, reduces latency and server load.

99% confidence
A

REST API relationship design patterns 2025: (1) Nested endpoints: /users/123/orders for tight one-to-many relationships (user owns orders), limit nesting to 2 levels max. (2) Query filters: /orders?user_id=123 for independent resources or many-to-many. (3) Compound documents (JSON:API): /users/123?include=orders,posts eager-loads related resources, prevents N+1 queries. (4) Resource IDs: /users/123 returns { "id": 123, "order_ids": [1,2,3] }, client fetches /orders?ids=1,2,3 for flexibility. Best practices: avoid deep nesting (/users/123/orders/456/items/789 too complex), provide both nested and flat endpoints, document relationship loading strategies, use ?include for optional eager loading. Performance: implement database join optimization, cache compound responses. Alternative: GraphQL for complex relationship requirements. Choose pattern based on: relationship strength, query frequency, client needs.

99% confidence
A

REST API documentation best practices 2025: (1) OpenAPI 3.1 specification (machine-readable, code generation, validation), (2) Interactive documentation (Swagger UI, Redoc, Stoplight, RapiDoc), (3) Authentication/authorization complete guide with examples, (4) Multi-language code samples (cURL, JavaScript/TypeScript, Python, Go), (5) Rate limiting policies and headers, (6) Complete error catalog with status codes and solutions, (7) Pagination, filtering, sorting documentation with examples, (8) Versioning strategy and deprecation timeline, (9) Changelog with breaking changes highlighted, (10) Sandbox/staging environment for testing. Tools: OpenAPI Generator, Postman Collections, Stoplight Studio. Best practices: auto-generate docs from code (stay in sync), include quickstart guide, provide Postman/Insomnia collections, host on dedicated domain (docs.api.example.com), implement search functionality. Essential for developer adoption and API success.

99% confidence
A

REST API bulk operations strategies 2025: (1) Batch endpoint: POST /users/batch with array payload [{ "name": "User1" }, { "name": "User2" }], (2) Multiple IDs: DELETE /users?ids=1,2,3 or POST /users/delete with { "ids": [1,2,3] }, (3) Query-based: PATCH /users?status=active with { "role": "moderator" } updates matching records. Response handling: (1) All-or-nothing (atomic transaction) - 200 success, 400 any failure, (2) Partial success (recommended) - 207 Multi-Status with { "success": [{ "id": 1 }], "errors": [{ "id": 3, "error": "validation failed" }] }. Limits: enforce max batch size (100-1000), reject oversized requests with 413 Payload Too Large. Async pattern for large batches: return 202 Accepted with job ID, client polls GET /jobs/{id}. Document batch limits, error handling, use for data imports, bulk updates, deletions.

99% confidence
A

HTTPS/TLS encrypts data in transit (mandatory for production APIs). 2025 implementation: (1) Obtain certificate - Let's Encrypt (free, automated), AWS Certificate Manager, commercial CA. (2) Configure TLS 1.3 only (deprecate TLS 1.2, disable TLS 1.0/1.1, SSLv2/v3) - TLS 1.3 has faster handshake, perfect forward secrecy mandatory. (3) Cipher suites - use AEAD ciphers (AES-GCM, ChaCha20-Poly1305), disable RC4/3DES/CBC mode. (4) Enforce HSTS - Strict-Transport-Security: max-age=31536000; includeSubDomains; preload forces HTTPS. (5) Mutual TLS (mTLS) for service-to-service - both client and server authenticate with certificates (high security). Certificate management: automated renewal (certbot), 90-day rotation, monitor expiration. Testing: SSL Labs test, check vulnerabilities. Redirect HTTP→HTTPS: 301 Moved Permanently. NEVER accept credentials over HTTP. Financial services require TLS 1.3 in 2025.

99% confidence
A

Input validation prevents injection attacks per OWASP API Security 2023. Validation types: (1) Type (string/number/boolean), (2) Format (email RFC 5322, UUID v4, ISO 8601 dates), (3) Length (min/max), (4) Range (numeric bounds), (5) Pattern (regex), (6) Enum (allowlist values). 2025 best practice: allowlisting (define what IS authorized, reject everything else) preferred over denylisting. Implementation: use validation libraries - Joi/Zod (JavaScript), Pydantic (Python), Hibernate Validator (Java). Server-side mandatory (never trust client validation). SQL: ALWAYS use parameterized queries/prepared statements (NEVER string concatenation). Response: 422 Unprocessable Entity with RFC 7807 Problem Details: {"type":"validation-error","errors":[{"field":"email","message":"Invalid format"}]}. Security: enforce request size limits (413 Payload Too Large if exceeded), sanitize HTML (DOMPurify), validate at middleware→service→database layers. OWASP broken authorization (API1, API5) addressed by proper validation.

99% confidence
A

CORS (Cross-Origin Resource Sharing) controls REST API cross-domain requests. Configuration headers: (1) Access-Control-Allow-Origin: https://app.example.com (specific origin) or * (public APIs only), (2) Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, (3) Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, (4) Access-Control-Max-Age: 86400 (cache preflight 24h). Preflight: Browsers send OPTIONS request for non-simple requests (custom headers, methods besides GET/POST). Security 2025: (1) NEVER use * with credentials (Access-Control-Allow-Credentials: true), (2) Validate Origin header against whitelist, (3) Don't echo untrusted Origin header, (4) Limit exposed headers with Access-Control-Expose-Headers. Implementation: nginx/Apache config, Express cors middleware, API Gateway policies. OWASP API Security: improper CORS enables unauthorized cross-origin access. Test: browser DevTools Network tab, verify preflight OPTIONS responses.

99% confidence
A

REST API asynchronous operation pattern for long-running tasks (2025 best practices): (1) Initiate: Client sends POST /reports or POST /jobs with request payload, (2) Immediate response: Server returns 202 Accepted with { "job_id": "abc123", "status": "pending", "poll_url": "/jobs/abc123" } and Location: /jobs/abc123 header, (3) Polling: Client polls GET /jobs/abc123 returning { "status": "processing", "progress": 45, "estimated_completion": "2025-11-13T15:30:00Z" }, (4) Completion: status becomes "completed" with result, or "failed" with error details. Enhancements: (1) Webhooks - POST callback URL when done, (2) WebSockets - real-time progress updates, (3) Server-Sent Events (SSE) - unidirectional streaming. Timeout: enforce max processing time, auto-fail stale jobs. Use for: file uploads/processing, report generation, bulk operations, email sending. Essential for responsive user experience.

99% confidence
A

REST API deprecation best practices 2025: (1) Announce early - 6-12 months advance notice via email, blog, changelog, (2) Sunset header (RFC 8594): Sunset: Sat, 31 Dec 2025 23:59:59 GMT in all responses for deprecated endpoints, (3) Deprecation header (draft): Deprecation: true or Deprecation: @1735689600 (Unix timestamp), (4) Warning headers: Warning: 299 - "Deprecated API, migrate to v2 by 2025-12-31", (5) Documentation: clear migration guides with code examples, highlight breaking changes, (6) Version overlap: support old + new versions simultaneously during transition, (7) Usage monitoring: track API key/user activity on old version, contact heavy users, (8) Gradual rollout: phased migration milestones, (9) Clear migration path with automated tools/scripts when possible, (10) Never break without notice - only deprecate for major version increments. Communicate via: in-app notifications, developer portal, status page, direct outreach.

99% confidence
A

REST API partial update design 2025: Use PATCH method (not PUT for partial). Two standard approaches: (1) JSON Merge Patch (RFC 7396) - simple, send changed fields: PATCH /users/123 with { "email": "[email protected]", "name": "Updated Name" } merges into existing resource. Set field to null to delete: { "middleName": null }. (2) JSON Patch (RFC 6902) - precise operations: PATCH /users/123 with [{ "op": "replace", "path": "/email", "value": "[email protected]" }, { "op": "remove", "path": "/middleName" }]. Operations: add, remove, replace, move, copy, test. Best practices: (1) Validate only provided fields, (2) Document null vs omitted semantics, (3) Return 200 OK with full updated resource, (4) Use Idempotency-Key header for critical updates, (5) Implement optimistic locking (If-Match with ETag) to prevent lost updates. Use PATCH for partial, PUT for full replacement only.

99% confidence
A

Unit testing isolates individual API components using mocks. 2025 frameworks: Jest/Vitest (Node.js), pytest (Python), JUnit 5 (Java), xUnit (.NET). Test structure: Arrange-Act-Assert (AAA) pattern. Testing scope: (1) Request validation logic, (2) Business logic functions, (3) Response serialization, (4) Error handling paths. Mock external dependencies: database (in-memory or mocks), external APIs (nock, responses), auth middleware. Example (Jest): test('GET /users/123 returns user', async () => { const mockUser = {id:123, name:'John'}; userService.getById = jest.fn().mockResolvedValue(mockUser); const res = await request(app).get('/users/123'); expect(res.status).toBe(200); expect(res.body).toEqual(mockUser); expect(userService.getById).toHaveBeenCalledWith(123); }). Best practices 2025: 80%+ coverage (critical paths), test edge cases (null, empty, invalid), use test.each for parameterized tests, run in CI/CD (GitHub Actions, GitLab CI), mock time/randomness for deterministic tests. Tools: supertest (Express), httpx (FastAPI), MockMvc (Spring).

99% confidence
A

REST API integration testing validates end-to-end behavior with real dependencies (2025 best practices): Setup: (1) Dedicated test database (Docker container, separate schema), (2) Test environment with realistic config, (3) HTTP client for real requests. Testing scope: (1) Complete request/response flow, (2) Database transactions and rollbacks, (3) Authentication/authorization middleware, (4) External service integrations (mocked or sandboxes). Tools: Postman/Newman (collections), REST Assured (Java), Supertest (Node.js), pytest + httpx (Python), Karate DSL (BDD). Example: describe('User API', () => { test('POST creates and GET retrieves user', async () => { const created = await request(app).post('/users').send({ name: 'John', email: '[email protected]' }); expect(created.status).toBe(201); const fetched = await request(app).get(/users/${created.body.id}); expect(fetched.body).toMatchObject(created.body); }); }). Best practices: test isolation (cleanup after each test), realistic test data, CI/CD integration, test auth flows, verify database state.

99% confidence
A

REST API contract testing ensures interface compliance (2025 best practices): Approaches: (1) Provider-side: validate API implementation matches OpenAPI/Swagger spec, (2) Consumer-driven (Pact): consumers define contracts, providers verify. Tools: (1) Schemathesis - property-based testing from OpenAPI, auto-generates test cases, (2) Prism - mock server validates requests/responses against OpenAPI, (3) Dredd - HTTP API testing framework, (4) Pact - consumer-driven contracts for microservices, (5) Specmatic - contract-first development. Implementation: (1) Define OpenAPI 3.1 spec as source of truth, (2) Validate request/response schemas with JSON Schema, (3) Test all status codes (200, 400, 401, 404, 500), (4) Verify required/optional fields, (5) Check header constraints. CI/CD: run on every PR, fail on violations, track contract coverage. Benefits: catch breaking changes pre-release, living documentation, enable parallel development. Essential for microservices, public APIs, multi-team projects.

99% confidence
A

REST API anti-patterns to avoid (2025): (1) Verbs in URLs - use GET /users not /getUsers (HTTP method is the verb), (2) Ignoring HTTP methods - don't use only GET/POST, leverage PUT/PATCH/DELETE, (3) Wrong status codes - returning 200 for all responses (use 201, 400, 401, 403, 404, 500 appropriately), (4) No versioning - breaking changes without version increment breaks clients, (5) Inconsistent naming - mixing users/user, camelCase/snake_case across endpoints, (6) No pagination - returning unbounded result sets causes performance issues, (7) Exposing internal database IDs - use UUIDs or opaque tokens for security, (8) Chatty APIs - N+1 query problem, too many round trips (use compound documents), (9) Generic errors - returning 500 without details or HTML error pages, (10) Stateful sessions - violates REST principles, use stateless auth (JWT), (11) Ignoring caching - missing Cache-Control/ETag headers. Follow REST constraints, HTTP semantics, OWASP API Security guidelines.

99% confidence
A

REST API observability (2025 best practices, Three Pillars): (1) Logging - structured JSON logs (timestamp, request_id, method, endpoint, status, duration, user_id, error), levels (debug, info, warn, error), centralized (ELK Stack, Splunk, Loki). (2) Metrics - request rate, latency percentiles (p50, p75, p95, p99), error rate by endpoint, status code distribution (2xx, 4xx, 5xx), active connections. Tools: Prometheus + Grafana, Datadog, New Relic. (3) Distributed Tracing - track requests across microservices, correlation IDs, spans. Tools: OpenTelemetry, Jaeger, Zipkin, AWS X-Ray. Health endpoints: GET /health (liveness), GET /ready (readiness checks dependencies). Alerts: SLI/SLO violations, error rate >1%, p99 latency spike, uptime. Security: monitor failed auth attempts, rate limit hits. Include: X-Request-ID header for request correlation. Essential for production reliability, debugging, performance optimization.

99% confidence
A

REST (Representational State Transfer) is an architectural style for distributed systems defined by Roy Fielding in 2000. Six constraints: (1) Client-Server separation - independent evolution, (2) Stateless - each request self-contained with all context, (3) Cacheable - responses explicitly indicate cacheability, (4) Uniform interface - standardized interactions via HTTP methods (RFC 9110), (5) Layered system - intermediaries like proxies/gateways allowed, (6) Code-on-demand (optional) - executable code transfer. RESTful APIs use HTTP methods (GET/POST/PUT/PATCH/DELETE) per RFC 9110 HTTP Semantics (2022), resources identified by URIs (RFC 3986), representations typically JSON. Not a protocol but architectural constraints ensuring scalability, reliability, performance. Foundation of modern web APIs, microservices, cloud services. 2025 practice: combine with OpenAPI 3.1 specs, HATEOAS for discoverability.

99% confidence
A

GET method retrieves resource representations per RFC 9110 section 9.3.1. Usage: GET /users (collection), GET /users/123 (specific resource), GET /products?category=electronics&limit=20 (filtered). Characteristics: Safe (no side effects), Idempotent (repeated calls = same result), Cacheable (enable Cache-Control, ETag headers). Conditional requests: If-None-Match (ETag validation), If-Modified-Since (timestamp validation) return 304 Not Modified to save bandwidth. Response codes: 200 OK (success with body), 304 Not Modified (cached valid), 404 Not Found (resource missing), 400 Bad Request (invalid query params). Best practices 2025: implement pagination (cursor-based preferred), support field selection (?fields=id,name), add rate limiting headers (X-RateLimit-*), never use GET for operations with side effects. Example: GET /api/v1/users?status=active&sort=-created_at&limit=50.

99% confidence
A

POST method creates resources or processes data per RFC 9110 section 9.3.3. Usage: POST /users (create), POST /orders (submit), POST /auth/login (process). Characteristics: Not idempotent (multiple calls create duplicates), Not cacheable, Request body contains data (JSON/form-data). Response codes: 201 Created (success, includes Location: /users/456 header + created resource body), 202 Accepted (async processing, return job URL), 400 Bad Request (validation failed), 409 Conflict (duplicate resource), 422 Unprocessable Entity (semantic errors). Example: POST /api/v1/users with {"name":"John","email":"[email protected]"} returns 201 Created, Location: /users/456, body: {"id":456,"name":"John","email":"[email protected]","created_at":"2025-11-14T12:00:00Z"}. Best practices 2025: implement Idempotency-Key header (UUID) for safe retries, validate all inputs server-side, return created resource in response body.

99% confidence
A

PUT method replaces entire resources idempotently per RFC 9110 section 9.3.4. Usage: PUT /users/123 (full replacement), PUT /config/settings (upsert). Characteristics: Idempotent (repeated calls = same state), Requires complete resource representation, Can create if doesn't exist (201) or update (200). Response codes: 200 OK (updated, with body), 204 No Content (updated, no body), 201 Created (resource created), 404 Not Found (parent doesn't exist), 400 Bad Request (validation failed). Example: PUT /api/v1/users/123 with {"id":123,"name":"John Updated","email":"[email protected]","role":"admin"} returns 200 OK with full updated resource. Best practices 2025: use PUT for complete replacement only, PATCH for partial updates, implement optimistic locking (If-Match: ) to prevent lost updates, validate all required fields present. PUT semantics: must send ALL fields, omitted fields treated as null/deleted.

99% confidence
A

PATCH method performs partial resource modifications per RFC 5789. Usage: PATCH /users/123 (update subset of fields). Two standard formats: (1) JSON Merge Patch (RFC 7396) - simple, send changed fields: {"email":"[email protected]"} merges into resource, set null to delete: {"middleName":null}. (2) JSON Patch (RFC 6902) - precise operations array: [{"op":"replace","path":"/email","value":"[email protected]"},{"op":"remove","path":"/middleName"}]. Operations: add, remove, replace, move, copy, test. Response codes: 200 OK (with updated resource), 204 No Content, 400 Bad Request (invalid patch), 409 Conflict (precondition failed). Best practices 2025: validate only provided fields, use Content-Type: application/merge-patch+json or application/json-patch+json, implement Idempotency-Key for safe retries, combine with If-Match (ETag) for optimistic locking. PATCH preferred over PUT for bandwidth efficiency, mobile clients.

99% confidence
A

DELETE method removes resources idempotently per RFC 9110 section 9.3.5. Usage: DELETE /users/123 (remove resource), DELETE /sessions/current (logout). Characteristics: Idempotent (repeated calls = same state, subsequent DELETE returns 404), No request body typically needed, Supports If-Match header for conditional deletion. Response codes: 204 No Content (deleted, standard response), 200 OK (deleted with confirmation body), 202 Accepted (async deletion queued), 404 Not Found (already deleted or never existed), 409 Conflict (cannot delete due to dependencies). Example: DELETE /api/v1/users/123 returns 204 No Content, next DELETE /users/123 returns 404 Not Found. Best practices 2025: implement soft deletes (deleted_at timestamp) for audit trails, verify authorization carefully, document cascade behavior (related resources), return 404 for both non-existent and already-deleted to maintain idempotency. Consider bulk DELETE with query params: DELETE /users?status=inactive.

99% confidence
A

HEAD method (RFC 9110 section 9.3.2) retrieves metadata without body - identical headers to GET but no content. Usage: check resource existence (200 vs 404), get Content-Length/Last-Modified/ETag without data transfer for bandwidth efficiency. Example: HEAD /api/v1/files/large.zip returns 200 OK, Content-Length: 52428800, no body downloaded. OPTIONS method (RFC 9110 section 9.3.7) describes communication options for target resource. Returns Allow: GET, POST, PUT, DELETE, PATCH header listing supported methods. Primary use: CORS preflight requests - browser sends OPTIONS before actual request with custom headers. Example: OPTIONS /users/123 returns 200 OK, Allow: GET, PUT, PATCH, DELETE, Access-Control-Allow-Methods: GET, PUT, PATCH, DELETE. Both safe and idempotent. Best practices 2025: implement OPTIONS for CORS support, use HEAD for efficient resource validation, include Accept-Patch, Accept-Post headers in OPTIONS responses.

99% confidence
A

2xx codes (RFC 9110 section 15.3) indicate successful request processing. 200 OK: standard success for GET/PUT/PATCH with resource body. 201 Created: resource created via POST, MUST include Location: /resource/123 header pointing to new resource, body contains created resource. 202 Accepted: request queued for async processing, return job tracking URL in Location header or body. 204 No Content: success with no response body (DELETE, PUT/PATCH returning nothing). 206 Partial Content: range request fulfilled, include Content-Range: bytes 0-1023/2048 header. Best practices 2025: use 201 (not 200) for POST creation, always add Location header with 201/202, use 204 for DELETE (not 200 with empty body), implement 206 for large file downloads with Range support. IANA Status Code Registry defines all official codes. Avoid non-standard 2xx codes.

99% confidence
A

4xx codes (RFC 9110 section 15.5) indicate client errors. 400 Bad Request: malformed syntax, invalid JSON, type errors. 401 Unauthorized: authentication missing/invalid, include WWW-Authenticate header. 403 Forbidden: authenticated but lacks permissions (NEVER 401 for authorization failures). 404 Not Found: resource doesn't exist. 405 Method Not Allowed: HTTP method unsupported, include Allow: GET, POST header. 409 Conflict: state conflict (duplicate email, concurrent modification). 422 Unprocessable Entity: valid syntax but semantic errors (email format invalid, age < 0). 429 Too Many Requests (RFC 6585): rate limited, MUST include Retry-After: 60 header. Best practices 2025: use RFC 7807 Problem Details format for error bodies, return 422 (not 400) for validation errors, use 404 (not 403) for missing resources to prevent information disclosure, implement proper 429 rate limiting with headers.

99% confidence
A

5xx codes (RFC 9110 section 15.6) indicate server failures. 500 Internal Server Error: unexpected condition, unhandled exception (log full trace internally, mask details in response). 501 Not Implemented: functionality not supported (rare). 502 Bad Gateway: gateway/proxy received invalid response from upstream service. 503 Service Unavailable: temporarily overloaded or down for maintenance, MUST include Retry-After: 120 header (seconds or HTTP-date). 504 Gateway Timeout: upstream timeout exceeded. Best practices 2025: NEVER expose stack traces/internal details in 5xx responses (security risk per OWASP API Security 2023), always include correlation/request ID (X-Request-ID header) for debugging, use 503 (not 500) for planned maintenance, log all 5xx errors for monitoring/alerts, return RFC 7807 Problem Details with safe error info. Distinguish temporary (503, retryable) from permanent (500, investigate). Monitor 5xx rate as key SLI.

99% confidence
A

3xx codes (RFC 9110 section 15.4) indicate redirection. 301 Moved Permanently: resource permanently relocated, clients update bookmarks, MUST include Location header. 302 Found: temporary redirect (legacy, method may change to GET). 304 Not Modified: conditional request (If-None-Match, If-Modified-Since), resource unchanged, no body sent (bandwidth optimization). 307 Temporary Redirect: temporary with method preserved (use instead of 302). 308 Permanent Redirect: permanent with method preserved (use instead of 301 for POST/PUT). Usage: 301 for deprecated API version (/api/v1/* → /api/v2/*), 304 for cache validation (ETag/Last-Modified), 307 for temporary maintenance mode, 308 for permanent endpoint migration. Best practices 2025: prefer 307/308 over 302/301 (method preservation), always include Location header, implement 304 with ETag for bandwidth savings, use Sunset header (RFC 8594) before applying 301 for API deprecation.

99% confidence
A

REST API URL design per RFC 3986 and 2025 best practices: (1) Nouns not verbs - GET /users (not /getUsers), HTTP method is the verb. (2) Plural nouns for collections - /users, /products, /orders (consistency). (3) Resource hierarchy - /users/123/orders/456 (max 2-3 levels to avoid complexity). (4) Lowercase with hyphens - /user-profiles (not /user_profiles or /userProfiles). (5) No file extensions - /users (not /users.json), use Accept: application/json header. (6) Version in URL - /api/v1/users (recommended), /api/v2/users for breaking changes. (7) Query params for filtering - /users?status=active&role=admin&limit=20. (8) Use UUIDs or slugs - /users/550e8400-e29b-41d4-a716-446655440000 (security, not sequential IDs). (9) Consistent naming - choose camelCase or snake_case globally. Examples: GET /api/v1/organizations/acme/teams/engineering/members?status=active.

99% confidence
A

REST API versioning strategies for 2025: (1) URI versioning (most common): /api/v1/users - straightforward, cache-friendly, easily discoverable. (2) Header versioning: Accept: application/vnd.myapi.v2+json or custom X-API-Version header - cleaner URLs but harder to debug. (3) Query parameter: /users?version=2 - flexible but complicates caching. Best practices: version from day one, use major versions only for breaking changes (field removal, type changes, required field additions), maintain old versions during 6-12 month deprecation period. URI versioning recommended for REST APIs due to simplicity and developer experience. Include version in all responses. Document migration paths between versions. Never remove versions without proper deprecation notice.

99% confidence
A

Idempotency: multiple identical requests produce same result as single request (RFC 9110). Idempotent methods: GET, PUT, DELETE, HEAD, OPTIONS (safe retries). Non-idempotent: POST (creates duplicates), PATCH (depends on implementation). Critical benefits 2025: safe automatic retries on network failures, resilience in distributed systems, prevents duplicate payments/orders. Implementation via Idempotency-Key header: client generates UUID (128+ bits entropy), sends Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000, server stores result in cache (Redis) with key, duplicate requests return cached result (200 OK, not 201). TTL: 24 hours typical. ACID requirement: recording token + mutation must be atomic transaction. Example: POST /payments with Idempotency-Key prevents duplicate charges on retry. AWS best practice: incorporate client request identifier into API contract. Essential for production reliability, payment processing, order creation.

99% confidence
A

REST API pagination strategies for 2025: (1) Cursor-based (recommended): /users?limit=20&after=opaque_cursor - stable, efficient, prevents duplicate/skipped records when data changes. Use opaque base64-encoded cursors to allow internal logic changes. (2) Offset-based: /users?limit=20&offset=40 - simple but unstable with concurrent writes. (3) Keyset/seek: /users?limit=20&after_id=100 - efficient, stable. Response best practices: include next/prev links (RFC 8288 Link header), has_more boolean, cursor/page metadata. Example response headers: Link: </users?after=xyz>; rel="next". Set default limit (20-50) and max limit (100) to prevent abuse. Cursor-based ideal for feeds, real-time data, infinite scroll. Use offset only for small, stable datasets with jump-to-page UI.

99% confidence
A

JWT (JSON Web Token - RFC 7519) provides stateless authentication. Structure: header.payload.signature (base64url encoded). Implementation 2025 per RFC 8725 Best Practices: (1) Client POST credentials to /auth/login, (2) Server validates, returns JWT with short expiration (15-30 min access token + refresh token), (3) Client sends Authorization: Bearer , (4) Server validates signature + claims every request. Required claims: sub (user ID), iat (issued timestamp), exp (expiration), aud (audience). Algorithm: use RS256 (RSA 2048-bit) or ES256 (ECDSA), NEVER alg: none. Key size: HS256 requires 256+ bit secret (32 ASCII chars minimum). Security 2025: enforce HTTPS only, store tokens in httpOnly cookies (not localStorage, XSS risk), validate signature cryptographically, check exp claim, implement token rotation, use refresh tokens for long sessions. Return 401 for invalid/missing/expired tokens, 403 for valid but insufficient permissions. Example: {"sub":"user123","exp":1731600000,"role":"admin"}.

99% confidence
A

OAuth 2.0/2.1 provides delegated authorization for REST APIs (2025 best practices per RFC 9700). Grant types: (1) Authorization Code with PKCE (mandatory for all clients in OAuth 2.1) - web/mobile apps, (2) Client Credentials - server-to-server, (3) Device Code - IoT/limited input devices. Flow: (1) Client initiates with code_challenge (PKCE), (2) User consents at /oauth/authorize, (3) Server returns authorization code, (4) Client exchanges code + code_verifier for tokens at /oauth/token, (5) Client uses access token in Authorization: Bearer header. Security 2025: PKCE required (not optional), short-lived access tokens (15-30 min), refresh token rotation (RTR), no implicit flow (deprecated). Scopes define permissions granularly. Validate tokens on every request, implement proper CORS for browser clients.

99% confidence
A

API key authentication provides simple server-to-server access control for REST APIs. Implementation methods: (1) Custom header X-API-Key: (recommended, secure), (2) Authorization: Bearer (standard), (3) Query parameter ?api_key= (avoid - leaks in logs/URLs). Key format: cryptographically random 32+ character string or UUID v4. Storage: hash keys using bcrypt/argon2 (never plaintext), store with metadata (created_at, last_used, rate_limits). Validation: verify hashed key, check expiration/revocation status, track usage. Security 2025: require HTTPS only, implement per-key rate limits, support key rotation without downtime, allow instant revocation. Monitor for: repeated invalid keys (brute force), unusual usage patterns. Best for: internal APIs, B2B integrations. Use OAuth/JWT for user-facing authentication.

99% confidence
A

RBAC controls REST API access based on user roles and permissions. Implementation steps: (1) Define roles (admin, editor, viewer) with clear hierarchies, (2) Map permissions to roles (users:create, posts:delete, analytics:view), (3) Assign roles to users via user.role_id, (4) Enforce permissions on every endpoint request. Database schema: users (id, role_id), roles (id, name), permissions (id, action, resource), role_permissions (role_id, permission_id). Middleware validates user.role.permissions.includes('posts:delete') before allowing access. JWT integration: embed role/permissions in token claims for stateless validation. Response codes: 401 (unauthenticated), 403 (authenticated but forbidden). Advanced: implement attribute-based access (ABAC) for resource-level rules like 'user can edit own posts'. OWASP API Security 2023: addresses broken authorization (API1, API5). Essential for enterprise APIs, multi-tenant systems.

99% confidence
A

HATEOAS (Hypermedia As The Engine Of Application State) is the REST constraint where responses include hypermedia links to available actions. Example: { "id": 1, "name": "User", "_links": { "self": "/users/1", "orders": "/users/1/orders", "edit": { "href": "/users/1", "method": "PUT" } } }. Benefits: self-documenting API, client decoupling from URL structures, evolvable (add operations without breaking clients). Industry reality 2025: most JSON APIs don't implement HATEOAS (pragmatic REST). JSON isn't natural hypermedia; HTML/hypermedia are better suited. Use cases: complex workflows requiring discoverability, public APIs needing evolution flexibility, HAL/JSON:API formats. Skip for: small internal APIs, tightly-coupled clients, performance-critical APIs. If implementing, use standards: HAL, JSON:API, or Siren. Most teams prioritize OpenAPI documentation over HATEOAS.

99% confidence
A

REST API error handling best practices 2025: (1) Use correct HTTP status codes - 400 (bad syntax), 401 (unauthenticated), 403 (forbidden), 404 (not found), 422 (validation failed), 429 (rate limited), 500 (server error), 503 (unavailable). (2) Consistent RFC 7807 Problem Details format: { "type": "https://api.example.com/errors/validation", "title": "Validation Failed", "status": 422, "detail": "Email format invalid", "instance": "/users/123", "errors": [{ "field": "email", "message": "Must be valid email" }] }. (3) Include trace/request ID for debugging. (4) Never expose stack traces in production. (5) Provide actionable error messages. (6) Use error codes for programmatic handling. (7) Return 429 with Retry-After header for rate limits. OWASP API Security: proper error handling prevents information disclosure.

99% confidence
A

REST API filtering enables clients to retrieve specific resource subsets. Patterns 2025: (1) Equality: /users?status=active&role=admin, (2) Multiple values: /users?role=admin,moderator (CSV) or /users?role[]=admin&role[]=moderator (array syntax), (3) Range operators: /products?price[gte]=10&price[lte]=100, /events?date[between]=2025-01-01,2025-12-31, (4) Pattern matching: /users?name[contains]=john, /users?email[startswith]=admin. Implementation: parse query parameters, validate against field whitelist, build parameterized database queries (never string concatenation). Security: prevent SQL injection using prepared statements, limit filter complexity (max fields, operators), sanitize all inputs. Performance: index all filterable columns. Standards: JSON:API filter parameter, OData $filter. Example: GET /products?category=electronics&price[lte]=1000&rating[gte]=4&in_stock=true returns filtered, production-ready results.

99% confidence
A

REST API sorting controls result ordering via query parameters. Standard patterns 2025: (1) Single field: /users?sort=created_at (ascending default), (2) Direction prefix: /users?sort=-created_at (- for descending, + for ascending), (3) Multiple fields: /users?sort=name,-created_at (primary: name asc, secondary: created_at desc), (4) Explicit direction: /users?order_by=created_at&direction=desc. Implementation: parse sort parameter, validate field names against whitelist (prevent SQL injection), build ORDER BY clause with parameterization, handle NULL values (NULLS FIRST/LAST in SQL). Security: only allow sorting on indexed columns to prevent DoS via slow queries. Consistency: establish deterministic tie-breaking (add secondary sort on ID) for stable pagination. Standards: JSON:API sort parameter. Example: GET /products?sort=-price,+name,id orders by price descending, name ascending, ID ascending (deterministic).

99% confidence
A

REST API search enables text-based resource discovery. Implementation approaches 2025: (1) Simple search: /users?q=john searches across multiple fields (name, email, bio), (2) Field-specific: /users?name=john&email=*@gmail.com for targeted queries, (3) Dedicated endpoint: GET /search?q=tutorial&type=articles with relevance ranking. Backend options: (1) SQL LIKE/ILIKE (basic, case-insensitive), (2) PostgreSQL full-text search (tsvector/tsquery with GIN indexes, stemming), (3) Elasticsearch/OpenSearch (advanced ranking, facets, autocomplete), (4) Algolia/Meilisearch (managed, instant search), (5) Vector/semantic search (embeddings for meaning-based results). Response: include relevance scores, highlighted matches, total count, facets. Performance: index searchable fields, implement pagination, cache common queries. Example: GET /search?q=react+hooks&facet=category,author returns ranked results with filter counts.

99% confidence
A

REST API response design best practices 2025: (1) Consistent JSON structure across all endpoints, (2) Naming convention - choose camelCase or snake_case globally, never mix, (3) No envelope for simple responses ({ "id": 1, "name": "User" }), envelope for metadata ({ "data": {...}, "meta": { "page": 1 } }), (4) Timestamps in ISO 8601 with timezone: "2025-11-13T14:30:00Z", (5) POST 201 returns created resource + Location header, (6) Null handling - be consistent (include nulls or omit), document choice, (7) Include pagination metadata (total, hasMore, nextCursor), (8) Error responses follow RFC 7807 Problem Details, (9) Content-Type: application/json header, (10) Include API version in X-API-Version header. Consistency critical for developer experience and API adoption.

99% confidence
A

Rate limiting algorithms for REST APIs (2025 best practices): (1) Token Bucket (recommended) - tokens refill at constant rate, requests consume tokens, allows controlled bursts. Config: capacity=100, refill=10/second. (2) Sliding Window Log - precise tracking of requests in rolling time window, prevents boundary gaming. (3) Sliding Window Counter - hybrid approach, efficient + accurate. (4) Fixed Window - simple, resets at intervals, but allows burst at boundaries (avoid for critical APIs). (5) Leaky Bucket - constant request processing rate, smooth traffic. Implementation: Redis for distributed systems (INCR/EXPIRE or sorted sets), in-memory for single server. Rate limit by: user ID, API key, IP address (careful with proxies). Return 429 with X-RateLimit headers + Retry-After. API gateway integration (Kong, AWS API Gateway, Cloudflare) recommended. Monitor violations, adjust limits based on patterns.

99% confidence
A

REST API rate limiting headers (2025 standards): Include in every response: (1) X-RateLimit-Limit or RateLimit-Limit: max requests per window ("1000"), (2) X-RateLimit-Remaining or RateLimit-Remaining: requests left in current window ("743"), (3) X-RateLimit-Reset or RateLimit-Reset: Unix timestamp when limit resets ("1700000000"). For 429 responses: (4) Retry-After: seconds until retry allowed ("60") per RFC 6585. Optional: X-RateLimit-Policy for multi-tier limits. IETF draft standard (RateLimit-* without X- prefix) gaining adoption. Implementation: calculate remaining = limit - current_usage, include headers in ALL responses (not just 429), support CORS preflight. Client benefits: implement exponential backoff, display quota in UI, schedule batch operations. Example: RateLimit-Limit: 100, RateLimit-Remaining: 87, RateLimit-Reset: 1731513600, Retry-After: 45.

99% confidence
A

Partial responses/field selection optimizes REST API bandwidth for client needs. Implementation patterns 2025: (1) fields parameter: /users?fields=id,name,email returns only specified fields, (2) Sparse fieldsets (JSON:API): /users?fields[users]=name,email&fields[posts]=title for multiple resource types, (3) Nested paths: /users/123?fields=id,profile.avatar,settings.theme for deep selection. Benefits: reduced bandwidth (critical for mobile), faster responses, improved performance on constrained devices. Implementation: parse fields parameter, validate against field whitelist (prevent NoSQL injection), handle nested objects carefully, maintain type safety. Default behavior: return full resource representation. Security: never expose internal/sensitive fields via field selection. Alternative: GraphQL for complex field requirements. Document all selectable fields and nested path syntax. Use for: mobile apps, bandwidth-constrained networks, large resource payloads.

99% confidence
A

REST API caching best practices 2025: (1) Cache-Control header - max-age=3600 (1 hour), public (CDN cacheable), private (user-specific), no-cache (revalidate), no-store (sensitive data). (2) ETag (entity tag) - content hash, client sends If-None-Match, return 304 Not Modified if match (bandwidth saved). (3) Last-Modified - timestamp-based, client sends If-Modified-Since for conditional requests. (4) Vary header - Vary: Accept-Encoding, Accept-Language caches different representations. (5) Expires - legacy fallback. HTTP methods: GET/HEAD cacheable, POST/PUT/PATCH/DELETE not cacheable. Layers: (1) Browser cache (private data), (2) CDN (public resources, Cloudflare/Fastly), (3) Application cache (Redis for computed results). Invalidation: update ETag on resource changes, use cache-busting for static assets. Essential for scalability, reduces latency and server load.

99% confidence
A

REST API relationship design patterns 2025: (1) Nested endpoints: /users/123/orders for tight one-to-many relationships (user owns orders), limit nesting to 2 levels max. (2) Query filters: /orders?user_id=123 for independent resources or many-to-many. (3) Compound documents (JSON:API): /users/123?include=orders,posts eager-loads related resources, prevents N+1 queries. (4) Resource IDs: /users/123 returns { "id": 123, "order_ids": [1,2,3] }, client fetches /orders?ids=1,2,3 for flexibility. Best practices: avoid deep nesting (/users/123/orders/456/items/789 too complex), provide both nested and flat endpoints, document relationship loading strategies, use ?include for optional eager loading. Performance: implement database join optimization, cache compound responses. Alternative: GraphQL for complex relationship requirements. Choose pattern based on: relationship strength, query frequency, client needs.

99% confidence
A

REST API documentation best practices 2025: (1) OpenAPI 3.1 specification (machine-readable, code generation, validation), (2) Interactive documentation (Swagger UI, Redoc, Stoplight, RapiDoc), (3) Authentication/authorization complete guide with examples, (4) Multi-language code samples (cURL, JavaScript/TypeScript, Python, Go), (5) Rate limiting policies and headers, (6) Complete error catalog with status codes and solutions, (7) Pagination, filtering, sorting documentation with examples, (8) Versioning strategy and deprecation timeline, (9) Changelog with breaking changes highlighted, (10) Sandbox/staging environment for testing. Tools: OpenAPI Generator, Postman Collections, Stoplight Studio. Best practices: auto-generate docs from code (stay in sync), include quickstart guide, provide Postman/Insomnia collections, host on dedicated domain (docs.api.example.com), implement search functionality. Essential for developer adoption and API success.

99% confidence
A

REST API bulk operations strategies 2025: (1) Batch endpoint: POST /users/batch with array payload [{ "name": "User1" }, { "name": "User2" }], (2) Multiple IDs: DELETE /users?ids=1,2,3 or POST /users/delete with { "ids": [1,2,3] }, (3) Query-based: PATCH /users?status=active with { "role": "moderator" } updates matching records. Response handling: (1) All-or-nothing (atomic transaction) - 200 success, 400 any failure, (2) Partial success (recommended) - 207 Multi-Status with { "success": [{ "id": 1 }], "errors": [{ "id": 3, "error": "validation failed" }] }. Limits: enforce max batch size (100-1000), reject oversized requests with 413 Payload Too Large. Async pattern for large batches: return 202 Accepted with job ID, client polls GET /jobs/{id}. Document batch limits, error handling, use for data imports, bulk updates, deletions.

99% confidence
A

HTTPS/TLS encrypts data in transit (mandatory for production APIs). 2025 implementation: (1) Obtain certificate - Let's Encrypt (free, automated), AWS Certificate Manager, commercial CA. (2) Configure TLS 1.3 only (deprecate TLS 1.2, disable TLS 1.0/1.1, SSLv2/v3) - TLS 1.3 has faster handshake, perfect forward secrecy mandatory. (3) Cipher suites - use AEAD ciphers (AES-GCM, ChaCha20-Poly1305), disable RC4/3DES/CBC mode. (4) Enforce HSTS - Strict-Transport-Security: max-age=31536000; includeSubDomains; preload forces HTTPS. (5) Mutual TLS (mTLS) for service-to-service - both client and server authenticate with certificates (high security). Certificate management: automated renewal (certbot), 90-day rotation, monitor expiration. Testing: SSL Labs test, check vulnerabilities. Redirect HTTP→HTTPS: 301 Moved Permanently. NEVER accept credentials over HTTP. Financial services require TLS 1.3 in 2025.

99% confidence
A

Input validation prevents injection attacks per OWASP API Security 2023. Validation types: (1) Type (string/number/boolean), (2) Format (email RFC 5322, UUID v4, ISO 8601 dates), (3) Length (min/max), (4) Range (numeric bounds), (5) Pattern (regex), (6) Enum (allowlist values). 2025 best practice: allowlisting (define what IS authorized, reject everything else) preferred over denylisting. Implementation: use validation libraries - Joi/Zod (JavaScript), Pydantic (Python), Hibernate Validator (Java). Server-side mandatory (never trust client validation). SQL: ALWAYS use parameterized queries/prepared statements (NEVER string concatenation). Response: 422 Unprocessable Entity with RFC 7807 Problem Details: {"type":"validation-error","errors":[{"field":"email","message":"Invalid format"}]}. Security: enforce request size limits (413 Payload Too Large if exceeded), sanitize HTML (DOMPurify), validate at middleware→service→database layers. OWASP broken authorization (API1, API5) addressed by proper validation.

99% confidence
A

CORS (Cross-Origin Resource Sharing) controls REST API cross-domain requests. Configuration headers: (1) Access-Control-Allow-Origin: https://app.example.com (specific origin) or * (public APIs only), (2) Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, (3) Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, (4) Access-Control-Max-Age: 86400 (cache preflight 24h). Preflight: Browsers send OPTIONS request for non-simple requests (custom headers, methods besides GET/POST). Security 2025: (1) NEVER use * with credentials (Access-Control-Allow-Credentials: true), (2) Validate Origin header against whitelist, (3) Don't echo untrusted Origin header, (4) Limit exposed headers with Access-Control-Expose-Headers. Implementation: nginx/Apache config, Express cors middleware, API Gateway policies. OWASP API Security: improper CORS enables unauthorized cross-origin access. Test: browser DevTools Network tab, verify preflight OPTIONS responses.

99% confidence
A

REST API asynchronous operation pattern for long-running tasks (2025 best practices): (1) Initiate: Client sends POST /reports or POST /jobs with request payload, (2) Immediate response: Server returns 202 Accepted with { "job_id": "abc123", "status": "pending", "poll_url": "/jobs/abc123" } and Location: /jobs/abc123 header, (3) Polling: Client polls GET /jobs/abc123 returning { "status": "processing", "progress": 45, "estimated_completion": "2025-11-13T15:30:00Z" }, (4) Completion: status becomes "completed" with result, or "failed" with error details. Enhancements: (1) Webhooks - POST callback URL when done, (2) WebSockets - real-time progress updates, (3) Server-Sent Events (SSE) - unidirectional streaming. Timeout: enforce max processing time, auto-fail stale jobs. Use for: file uploads/processing, report generation, bulk operations, email sending. Essential for responsive user experience.

99% confidence
A

REST API deprecation best practices 2025: (1) Announce early - 6-12 months advance notice via email, blog, changelog, (2) Sunset header (RFC 8594): Sunset: Sat, 31 Dec 2025 23:59:59 GMT in all responses for deprecated endpoints, (3) Deprecation header (draft): Deprecation: true or Deprecation: @1735689600 (Unix timestamp), (4) Warning headers: Warning: 299 - "Deprecated API, migrate to v2 by 2025-12-31", (5) Documentation: clear migration guides with code examples, highlight breaking changes, (6) Version overlap: support old + new versions simultaneously during transition, (7) Usage monitoring: track API key/user activity on old version, contact heavy users, (8) Gradual rollout: phased migration milestones, (9) Clear migration path with automated tools/scripts when possible, (10) Never break without notice - only deprecate for major version increments. Communicate via: in-app notifications, developer portal, status page, direct outreach.

99% confidence
A

REST API partial update design 2025: Use PATCH method (not PUT for partial). Two standard approaches: (1) JSON Merge Patch (RFC 7396) - simple, send changed fields: PATCH /users/123 with { "email": "[email protected]", "name": "Updated Name" } merges into existing resource. Set field to null to delete: { "middleName": null }. (2) JSON Patch (RFC 6902) - precise operations: PATCH /users/123 with [{ "op": "replace", "path": "/email", "value": "[email protected]" }, { "op": "remove", "path": "/middleName" }]. Operations: add, remove, replace, move, copy, test. Best practices: (1) Validate only provided fields, (2) Document null vs omitted semantics, (3) Return 200 OK with full updated resource, (4) Use Idempotency-Key header for critical updates, (5) Implement optimistic locking (If-Match with ETag) to prevent lost updates. Use PATCH for partial, PUT for full replacement only.

99% confidence
A

Unit testing isolates individual API components using mocks. 2025 frameworks: Jest/Vitest (Node.js), pytest (Python), JUnit 5 (Java), xUnit (.NET). Test structure: Arrange-Act-Assert (AAA) pattern. Testing scope: (1) Request validation logic, (2) Business logic functions, (3) Response serialization, (4) Error handling paths. Mock external dependencies: database (in-memory or mocks), external APIs (nock, responses), auth middleware. Example (Jest): test('GET /users/123 returns user', async () => { const mockUser = {id:123, name:'John'}; userService.getById = jest.fn().mockResolvedValue(mockUser); const res = await request(app).get('/users/123'); expect(res.status).toBe(200); expect(res.body).toEqual(mockUser); expect(userService.getById).toHaveBeenCalledWith(123); }). Best practices 2025: 80%+ coverage (critical paths), test edge cases (null, empty, invalid), use test.each for parameterized tests, run in CI/CD (GitHub Actions, GitLab CI), mock time/randomness for deterministic tests. Tools: supertest (Express), httpx (FastAPI), MockMvc (Spring).

99% confidence
A

REST API integration testing validates end-to-end behavior with real dependencies (2025 best practices): Setup: (1) Dedicated test database (Docker container, separate schema), (2) Test environment with realistic config, (3) HTTP client for real requests. Testing scope: (1) Complete request/response flow, (2) Database transactions and rollbacks, (3) Authentication/authorization middleware, (4) External service integrations (mocked or sandboxes). Tools: Postman/Newman (collections), REST Assured (Java), Supertest (Node.js), pytest + httpx (Python), Karate DSL (BDD). Example: describe('User API', () => { test('POST creates and GET retrieves user', async () => { const created = await request(app).post('/users').send({ name: 'John', email: '[email protected]' }); expect(created.status).toBe(201); const fetched = await request(app).get(/users/${created.body.id}); expect(fetched.body).toMatchObject(created.body); }); }). Best practices: test isolation (cleanup after each test), realistic test data, CI/CD integration, test auth flows, verify database state.

99% confidence
A

REST API contract testing ensures interface compliance (2025 best practices): Approaches: (1) Provider-side: validate API implementation matches OpenAPI/Swagger spec, (2) Consumer-driven (Pact): consumers define contracts, providers verify. Tools: (1) Schemathesis - property-based testing from OpenAPI, auto-generates test cases, (2) Prism - mock server validates requests/responses against OpenAPI, (3) Dredd - HTTP API testing framework, (4) Pact - consumer-driven contracts for microservices, (5) Specmatic - contract-first development. Implementation: (1) Define OpenAPI 3.1 spec as source of truth, (2) Validate request/response schemas with JSON Schema, (3) Test all status codes (200, 400, 401, 404, 500), (4) Verify required/optional fields, (5) Check header constraints. CI/CD: run on every PR, fail on violations, track contract coverage. Benefits: catch breaking changes pre-release, living documentation, enable parallel development. Essential for microservices, public APIs, multi-team projects.

99% confidence
A

REST API anti-patterns to avoid (2025): (1) Verbs in URLs - use GET /users not /getUsers (HTTP method is the verb), (2) Ignoring HTTP methods - don't use only GET/POST, leverage PUT/PATCH/DELETE, (3) Wrong status codes - returning 200 for all responses (use 201, 400, 401, 403, 404, 500 appropriately), (4) No versioning - breaking changes without version increment breaks clients, (5) Inconsistent naming - mixing users/user, camelCase/snake_case across endpoints, (6) No pagination - returning unbounded result sets causes performance issues, (7) Exposing internal database IDs - use UUIDs or opaque tokens for security, (8) Chatty APIs - N+1 query problem, too many round trips (use compound documents), (9) Generic errors - returning 500 without details or HTML error pages, (10) Stateful sessions - violates REST principles, use stateless auth (JWT), (11) Ignoring caching - missing Cache-Control/ETag headers. Follow REST constraints, HTTP semantics, OWASP API Security guidelines.

99% confidence
A

REST API observability (2025 best practices, Three Pillars): (1) Logging - structured JSON logs (timestamp, request_id, method, endpoint, status, duration, user_id, error), levels (debug, info, warn, error), centralized (ELK Stack, Splunk, Loki). (2) Metrics - request rate, latency percentiles (p50, p75, p95, p99), error rate by endpoint, status code distribution (2xx, 4xx, 5xx), active connections. Tools: Prometheus + Grafana, Datadog, New Relic. (3) Distributed Tracing - track requests across microservices, correlation IDs, spans. Tools: OpenTelemetry, Jaeger, Zipkin, AWS X-Ray. Health endpoints: GET /health (liveness), GET /ready (readiness checks dependencies). Alerts: SLI/SLO violations, error rate >1%, p99 latency spike, uptime. Security: monitor failed auth attempts, rate limit hits. Include: X-Request-ID header for request correlation. Essential for production reliability, debugging, performance optimization.

99% confidence