Modern API rate limiting strategies for production systems: 1) Standardized response headers (IETF Draft): RateLimit-Limit (quota), RateLimit-Remaining (remaining requests), RateLimit-Reset (Unix timestamp when quota resets). Return 429 Too Many Requests with Retry-After: 60 header (seconds until retry). Legacy headers X-RateLimit-* still widely used (GitHub, Stripe). 2) Tiered limits by plan: Free tier (100 req/hour), Pro (1000 req/hour), Enterprise (custom). Separate limits for read vs write operations (10:1 ratio common). 3) Multiple limit dimensions: Per-user (authenticated requests), Per-IP (anonymous), Per-endpoint (expensive operations get lower limits), Per-organization (team quotas). 4) Dynamic rate limiting: Adjust limits based on server health metrics (CPU, memory, database connections). Adaptive algorithms reduce limits during incidents, increase during normal operation. 5) Client-side backoff: Implement exponential backoff with jitter (delay = min(max_delay, base_delay * 2^attempt + random_jitter)). Prevents thundering herd when limits reset. 6) Caching strategy: Cache-Control headers reduce API calls (Cache-Control: public, max-age=300). ETags for conditional requests (If-None-Match) save bandwidth. 7) Monitoring and alerting: Track 429 response rates (>5% indicates limits too restrictive). Monitor P95/P99 latency for rate limit checks (<5ms overhead). 8) Graceful degradation: Queue non-critical requests, reject least important first. 9) Communication: Document limits in OpenAPI spec (x-rate-limit extension), dashboard showing current usage. 10) Implementation: Redis for distributed rate limiting (INCR + EXPIRE atomic operations), Token bucket algorithm standard (AWS API Gateway, Kong, Nginx). Tools: Kong Rate Limiting plugin, AWS API Gateway throttling, Cloudflare Rate Limiting, Nginx limit_req module, Express rate-limit middleware. Cost: Prevents abuse (90% of API attacks involve excessive requests - Cloudflare data), protects infrastructure, ensures fair usage.
API Design Openapi FAQ & Answers
30 expert API Design Openapi answers researched from official documentation. Every answer cites authoritative sources you can verify.
unknown
30 questionsOpenAPI 3.1 achieves full JSON Schema Draft 2020-12 compatibility (3.0 used partial/modified JSON Schema). Adds webhooks object for async/event-driven APIs. Removes nullable keyword (use type: null instead). Changes exclusiveMinimum/exclusiveMaximum to independent numeric keywords vs boolean. Removes $ref restrictions. Adds jsonSchemaDialect field, Info.summary, License.identifier (SPDX codes), mutual TLS security scheme.
RFC 9110 (HTTP Semantics) defines current HTTP status codes in Section 15, obsoleting RFCs 2818, 7231, 7232, 7233, 7235, 7538, 7615, 7694. RFC 6585 adds 428 (Precondition Required), 429 (Too Many Requests), 431 (Request Header Fields Too Large), 511 (Network Authentication Required). Status codes organized in five categories: 1xx informational, 2xx successful, 3xx redirection, 4xx client error, 5xx server error.
- Fixed Window Counter: Counts requests in fixed time windows (e.g., 100 req/minute). Implementation: increment counter per window, reset at boundary. Pros: simple, low memory (one counter per user). Cons: burst at window edges (200 requests across two windows in 1 second). 2) Sliding Window Log: Tracks exact timestamps of all requests. Implementation: store request timestamps, remove old entries, count remaining. Pros: precise, no edge bursts. Cons: high memory (stores all timestamps). 3) Token Bucket: Refills tokens at constant rate, consumes on request. Implementation: tokens = min(capacity, tokens + (now - last_refill) * rate); allow if tokens >= 1. Pros: allows controlled bursts, smooth long-term rate. Cons: complex state management. Used by AWS API Gateway, Kong, Nginx. 4) Leaky Bucket: Queues requests, processes at fixed rate. Implementation: enqueue request, dequeue at constant rate. Pros: strict rate enforcement, smooths traffic. Cons: adds latency (queuing), queue overflow. Best choice: Token Bucket for bursty APIs (mobile apps, webhooks), Sliding Window Log for strict fairness (billing APIs), Fixed Window for simplicity (internal services). Industry standard: Token Bucket with capacity = 2x rate limit enables short bursts while enforcing average rate.
Cursor pagination uses opaque Base64-encoded token marking position in dataset (typically last item's ID or timestamp). Request: GET /api/posts?cursor=eyJpZCI6MTIzfQ&limit=20. Response includes next_cursor for subsequent page. Implementation: WHERE id > decoded_cursor ORDER BY id LIMIT 20. Offset pagination uses page number or skip count: GET /api/posts?offset=100&limit=20 (SELECT * FROM posts LIMIT 20 OFFSET 100). Performance comparison: Cursor is 17x faster for million-record PostgreSQL datasets, maintains constant O(1) time regardless of depth. Offset degrades to O(n) as database must read and discard offset rows before returning results. Consistency: Cursor prevents duplicate/missing items when data changes (new inserts don't shift results). Offset suffers from page drift (item added shifts all subsequent pages). Use cases: Cursor for real-time feeds (Twitter, Facebook), infinite scroll, large datasets. Offset for simple use cases with jump-to-page navigation, small datasets, admin panels. Industry adoption: Stripe, GitHub, Slack, Facebook Graph API all use cursor pagination. Trade-off: Cursor requires indexed column (id, created_at) and cannot jump to arbitrary pages. Implementation: Always encode cursor as Base64 to hide internal structure and prevent manipulation.
HATEOAS (Hypermedia as the Engine of Application State) is essential REST constraint where hypertext provides simultaneous presentation of information and controls. Fielding stated 'if the engine of application state is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API'. He criticized HTTP-based interfaces as RPC, saying 'REST is software design on scale of decades: every detail promotes longevity and independent evolution'.
- Broken Object-Level Authorization (BOLA) 2. Broken Authentication 3. Broken Object Property-Level Authorization (combines Excessive Data Exposure + Mass Assignment) 4. Unrestricted Resource Consumption 5. Broken Function-Level Authorization 6. Unrestricted Access to Sensitive Business Flows 7. Server-Side Request Forgery (SSRF) 8. Security Misconfiguration 9. Improper Inventory Management 10. Unsafe Consumption of APIs. Updated from 2019 version with refined categories.
Official JSON Schema specification defining 'application/schema+json' media type for describing JSON structure. Key features: prefixItems + items replace items + additionalItems for arrays, $dynamicRef/$dynamicAnchor replace $recursiveRef/$recursiveAnchor, Unicode regex support required, format split into format-annotation and format-assertion vocabularies, schema bundling guidance. Declare with '$schema': 'https://json-schema.org/draft/2020-12/schema'. Fully compatible with OpenAPI 3.1.
- URI Path Versioning: Embed version in URL path (GET /v1/users, /v2/users). Pros: simple, visible in logs, easy caching, client explicitly chooses version. Cons: violates REST URI uniqueness principle, URL proliferation. Most popular (used by Stripe, Twilio, Twitter). Google AIP-185 standard recommends this approach. 2) Query Parameter Versioning: Version in query string (GET /users?version=2 or /users?api-version=2025-01-15). Pros: simple routing, preserves base URI. Cons: less visible, breaks caching (query params often excluded), non-RESTful. Used by Netflix, Azure. 3) Header-Based Versioning: Custom header (X-API-Version: 2 or API-Version: 2). Pros: clean URIs, flexible per-request versioning. Cons: invisible in browser, harder to test, requires header parsing. Used by GitHub (Accept: application/vnd.github.v3+json). 4) Content Negotiation (Accept Header): Media type versioning (Accept: application/vnd.company.v2+json). Pros: most RESTful, follows HTTP standards, granular per-resource versioning. Cons: complex implementation, harder discovery. Roy Fielding preferred method. Best practices: Only version on breaking changes (new fields are non-breaking). Use date-based versioning (2025-01-15) for clarity or semantic versioning (v1, v2). Maintain N-1 version support (at least two major versions). Deprecation policy with sunset headers (Sunset: Sat, 31 Dec 2025 23:59:59 GMT). Industry standard: URI path versioning dominates (85% adoption) for simplicity despite being less RESTful.
Use Accept header for media type negotiation (most RESTful approach): Accept: application/json, application/xml;q=0.9, /;q=0.1 with quality factors (q=0-1, default 1.0). Return 406 Not Acceptable if unable to fulfill. Use Vary: Accept header for cache optimization. Related headers: Accept-Language (language preference), Accept-Encoding (compression). Server should have sensible default (typically JSON) if Accept missing. Best for API versioning to prevent link bloat.
OpenAPI 3.1 spec best practices for production-ready documentation: 1) Servers array required with real URLs (servers: [{url: 'https://api.example.com/v1', description: 'Production'}, {url: 'https://sandbox-api.example.com/v1', description: 'Sandbox'}]). Avoid localhost or example.com. 2) Unique operationId for every endpoint (used by SDK generators like OpenAPI Generator, Swagger Codegen). Format: getUserById, createOrder, deletePayment. 3) Comprehensive descriptions for all schemas, properties, endpoints (info.description explains API purpose, paths.description explains operation). 4) Real-world examples using examples property (supports request/response testing, Prism mock servers, Postman collections). Use realistic data (not foo/bar). 5) Tags for logical grouping (tags: Users, Orders, Payments enables Swagger UI sidebar navigation). 6) Security schemes clearly defined (securitySchemes: {bearerAuth: {type: http, scheme: bearer, bearerFormat: JWT}}). Apply to operations via security array. 7) All response status codes documented (200, 201, 400, 401, 403, 404, 429, 500) with schemas and examples. 8) Use $ref for reusability (components.schemas for shared models reduces duplication). 9) Deprecation markers (deprecated: true with info.x-sunset-date for removal timeline). 10) Contact info and license (info.contact.email, info.license for support). Tooling: Redocly for linting (checks 50+ rules), Spectral for custom validation, Swagger UI for interactive testing, Stoplight Studio for design. Metrics: Comprehensive docs reduce integration time by 30%, reduce support tickets by 40%.
GET: retrieve resources (idempotent, cacheable, no body). POST: create new resources (non-idempotent, not cacheable). PUT: update/replace entire resource (idempotent). PATCH: partial update (non-idempotent). DELETE: remove resource (idempotent). HEAD: GET without body (metadata only). OPTIONS: describe communication options. Idempotent operations can be repeated safely. Use proper status codes: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 404 Not Found.
REST API URI naming conventions following industry standards (Google AIP, Microsoft Azure, Zalando): 1) Use nouns, never verbs: GET /users (correct), GET /getUsers (wrong - HTTP method is the verb). 2) Plural nouns for collections: /users, /orders, /products (not /user). Google AIP-122 mandates plurals. 3) Hierarchical relationships show ownership: /users/123/orders/456 (user 123's order 456), /organizations/acme/projects (nested resources). Limit depth to 3 levels for readability. 4) Lowercase with hyphens (kebab-case): /user-profiles, /payment-methods (not camelCase or snake_case in URIs). 5) No file extensions: /users (correct), /users.json (wrong - use Accept: application/json header for content negotiation). 6) Keep URIs concise: /users/123 (not /api/v1/database/users/user_id/123). 7) Version at root: /v1/users, /v2/users (or domain versioning api.v2.example.com). 8) Query parameters for operations on collections: Filtering (?status=active&role=admin), Sorting (?sort=created_at&order=desc), Pagination (?page=2&limit=50 or ?cursor=abc123), Search (?q=john), Field selection (?fields=id,name,email). 9) Stable URIs: Avoid implementation details (database table names, internal IDs). URIs should not change when backend refactors. 10) Consistent patterns: All resources follow same structure (reduces cognitive load). Examples: Good URIs: GET /v1/users, GET /v1/users/123/orders, POST /v1/users, DELETE /v1/users/123. Bad URIs: GET /getAllUsers, GET /user/id/123, POST /createUser. Tools enforce conventions: API linters (Spectral, Redocly) validate naming patterns automatically.
OpenAPI Specification (OAS) is the standard for RESTful API definition, originally created as Swagger Specification by SmartBear. In 2015, donated to OpenAPI Initiative (Linux Foundation). 'Swagger' now refers to SmartBear's toolset: Swagger Editor (design), Swagger UI (interactive docs), Swagger Codegen (code generation), SwaggerHub (collaboration). OpenAPI 3.1 released 2021. Swagger tools support OpenAPI 3.0, 3.1, and AsyncAPI for event-driven APIs.
Use standard HTTP status codes (400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests, 500 Internal Server Error). Use RFC 9457 Problem Details format (obsoletes RFC 7807): Content-Type application/problem+json with fields: type (URI identifying problem), title (human-readable summary), status (HTTP status code), detail (explanation to help client fix), instance (URI for specific occurrence). Include traceId/requestId for correlation. Machine-readable error codes. Don't expose sensitive info. Validation errors list specific fields. Standardized format improves interoperability.
REST API JSON formatting standards for interoperability and developer experience: 1) Content-Type: Always use Content-Type: application/json (not text/plain). Accept application/json in requests, validate header server-side. 2) Naming conventions: camelCase for properties (firstName, createdAt) - most common in JavaScript ecosystem. Google JSON Style Guide mandates camelCase. snake_case acceptable for Python-centric APIs. Consistency within API critical. 3) Date/time format: ISO 8601 with UTC timezone (2025-01-15T10:30:00Z or 2025-01-15T10:30:00.000Z with milliseconds). Avoid Unix timestamps in JSON (poor readability). Use RFC 3339 profile of ISO 8601 (IETF standard). 4) Null handling: Omit null fields from response (reduces payload size, cleaner JSON). Exception: Explicitly setting field to null has semantic meaning (reset value). Microsoft Azure guidelines recommend omitting nulls. 5) Number formats: Use native JSON numbers for integers/floats. For precision (currency, coordinates), use strings to prevent float errors (amount: '99.95' not 99.95). 6) Collections: Always use arrays for lists ([{...}, {...}]), even single-item collections. Empty collections return [] not null. 7) Nested objects: Represent relationships with nested objects ({user: {id: 123, name: 'John'}}) or references ({userId: 123}). Avoid deep nesting (>3 levels). 8) Boolean values: Use true/false (lowercase), not 1/0 or 'true'/'false' strings. 9) Enums: String enums preferred over integers (status: 'active' vs status: 1) for readability. 10) Response formatting: Minified JSON for production (no whitespace). Pretty-printed (indent=2) for development if client sends Accept: application/json; indent=2. Gzip compression (Content-Encoding: gzip) reduces payload 70-90%. Tools: JSON Schema validation (Ajv, joi), linters (jsonlint), formatters (prettier). Metrics: Consistent JSON reduces integration errors by 25%, improves caching effectiveness.
REST APIs designed for synchronous operation aiming for 100 milliseconds for internal services with no HTTP dependencies, upper bound around one second for complex services. Sub-50ms possible with edge computing (CDN, edge functions) for critical paths. Latency budgets: <100ms excellent (user perceives instant), 100-500ms acceptable (slight delay noticeable), 500ms-1s tolerable for complex operations (user waiting threshold), >1s requires optimization or async pattern (202 Accepted + polling). Optimization techniques: caching (Redis/CDN), database indexing, connection pooling, pagination, GraphQL batching, HTTP/2 multiplexing.
API4:2023 Unrestricted Resource Consumption (OWASP API Security Top 10 2023, ranked #4) - APIs satisfying requests consume resources (network bandwidth, CPU, memory, storage, database connections). Attackers exploit lack of limits to cause Denial of Service (DoS) or inflate operational costs (cloud billing attacks). Common vulnerabilities: 1) No rate limiting or excessively high limits (1M requests/hour allows abuse). 2) Missing pagination limits (GET /users returns 10M records, crashes server). 3) No request size limits (100MB JSON upload exhausts memory). 4) Unbounded query complexity (GraphQL query with 1000 nested levels). 5) No timeout configuration (long-running queries lock database). 6) Missing response size limits (export endpoint returns 5GB CSV). 7) No resource quotas per user/tier (free users consume same resources as enterprise). Attack examples: Pagination attack (GET /api/posts?limit=999999999), GraphQL depth bomb (nested query 50 levels deep), Zip bomb upload (10KB file expands to 10GB), RegEx DoS (catastrophic backtracking pattern). Mitigation: 1) Rate limiting per IP/user (100 req/min free tier, 1000 req/min paid). Use Token Bucket algorithm. 2) Pagination enforcement (max limit=100, default=20). 3) Request size limits (max 10MB JSON, nginx client_max_body_size). 4) Query complexity analysis (GraphQL: limit depth to 7, max fields to 100). 5) Timeout configuration (API gateway 30s, database queries 10s). 6) Resource quotas (CPU: 1 vCPU per request, memory: 512MB max). 7) Streaming for large responses (chunked transfer encoding). Tools: AWS API Gateway throttling, Kong rate limiting, GraphQL depth limit (graphql-depth-limit npm package), nginx request limits. Metrics: 40% of API DoS attacks exploit missing resource limits (OWASP 2023 data). Cost: Unrestricted resources can result in 1000x cloud bill increases.
API7:2023 Server-Side Request Forgery (OWASP API Security Top 10 2023, ranked #7) - SSRF occurs when API fetches remote resource without validating user-supplied URI. Attacker coerces application to send crafted request to unexpected destination, bypassing firewall/VPN/ACL protection. API server becomes proxy for malicious requests. Common attack targets: 1) Cloud metadata endpoints (AWS: http://169.254.169.254/latest/meta-data/ exposes IAM credentials, Azure: http://169.254.169.254/metadata/instance, GCP: http://metadata.google.internal). 2) Internal services (http://localhost:8080/admin, http://192.168.1.100/database). 3) Network scanning (probe internal IPs to map infrastructure). 4) File reading (file:///etc/passwd on Linux). Vulnerable API example: POST /api/import with {url: 'http://169.254.169.254/latest/meta-data/iam/security-credentials/'} - API fetches URL and returns AWS credentials. Exploitation scenarios: Webhook poisoning (attacker registers webhook URL pointing to internal service), URL preview features (link unfurling), PDF generators (inject URL in HTML), image proxy services, XML parsers with external entities (XXE leading to SSRF). Mitigation: 1) URL allowlist (only permit specific domains like https://cdn.example.com). Blocklists insufficient (bypass via URL encoding, DNS rebinding, IPv6). 2) Disable HTTP redirects (prevent 301/302 to internal IPs). 3) Input validation (validate scheme (https only), parse URL safely, reject IP addresses, check DNS resolution points to public IP). 4) Network segmentation (API servers in separate subnet from sensitive services). 5) Response validation (don't return raw fetched content, validate content type). 6) Timeout limits (5s max for external fetches). 7) IMDSv2 for AWS (requires session token, blocks SSRF). Tools: URL parsing (Python urllib.parse, JavaScript URL API), DNS validation, Cloud provider SSRF protection (AWS VPC endpoints, Azure Private Link). Detection: Monitor outbound requests from API servers for suspicious patterns (169.254.x.x, localhost, RFC 1918 private IPs). Metrics: 15% of API vulnerabilities involve SSRF (OWASP 2023), 95% of SSRF attacks target cloud metadata endpoints.
Always match ORDER BY with cursor condition for consistency. Don't store pagination state server-side - encode in cursor (stateless). Never paginate by non-unique or volatile fields - use ID or timestamp+ID composite. Consistent response shape: {items: [], has_more: boolean, next_cursor: string}. Base64 encode cursors for opacity and security. Support bidirectional pagination (next/previous cursors). Document cursor format and expiry. Handle edge cases: empty results (return has_more: false), invalid cursors (return 400), deleted items (skip gracefully). Use indexed columns for cursor fields (performance). 17x faster than offset for large datasets.
API1:2023 OWASP (most critical) - Attackers exploit endpoints vulnerable to BOLA by manipulating object identifiers in requests to access unauthorized data. Example: GET /api/users/123/orders returns any user's orders by changing ID. Every API endpoint accepting object ID should verify user authorized to access that specific object. Implement access control checks at object level, not just function level. Validate user owns/can access resource. Use indirect references or UUIDs.
Six constraints: 1) Client-Server separation 2) Statelessness (each request contains all needed info) 3) Cacheability (responses explicitly indicate if cacheable) 4) Layered System (client can't tell if connected to end server or intermediary) 5) Uniform Interface (resource identification, manipulation through representations, self-descriptive messages, HATEOAS) 6) Code-on-Demand (optional, server can extend client functionality). True REST must satisfy all constraints.
API authentication and security best practices aligned with OWASP API Security Top 10 2023 and industry standards: 1) Transport security: Always enforce HTTPS/TLS 1.3 (minimum TLS 1.2). Use HSTS header (Strict-Transport-Security: max-age=31536000; includeSubDomains) to prevent downgrade attacks. Certificate pinning for mobile apps. 2) Authentication methods by use case: OAuth 2.0 + OIDC for user delegation (third-party access, social login), API keys for service-to-service (simple, revocable, rotate every 90 days), JWT (JSON Web Tokens) for stateless authentication (short-lived access tokens 15min, refresh tokens 7 days in httpOnly cookies), mTLS (mutual TLS) for high-security microservices (certificate-based, zero-trust architecture). 3) Authorization header standard: Use Authorization: Bearer
API3:2023 Broken Object Property-Level Authorization (OWASP API Security Top 10 2023, ranked #3) - Combines API3:2019 Excessive Data Exposure and API6:2019 Mass Assignment into single category. Root cause: lack of proper authorization validation at individual object property level, enabling unauthorized information disclosure or property manipulation. Two attack vectors: 1) Excessive Data Exposure (read): API returns sensitive properties user should not see. Example: GET /api/users/me returns {id: 123, email: '[email protected]', salary: 95000, ssn: '123-45-6789', role: 'admin'} - Regular user sees admin salary/SSN. Backend fetches entire database model, relies on client to filter sensitive fields (client-side filtering fails). 2) Mass Assignment (write): API allows updating restricted properties. Example: PATCH /api/users/123 with {email: '[email protected]', role: 'admin', isVerified: true} - User escalates to admin by including extra properties in request payload. No server-side validation of writable fields. Common vulnerable patterns: Auto-binding request body to database models (ORM features like ActiveRecord in Rails, Sequelize in Node.js), Generic toJSON() methods exposing all properties, GraphQL queries without field-level resolvers. Exploitation example: User enumeration via GET /api/users?fields=email,phone returns all users' contact info. Privilege escalation via PATCH /api/profile with {credits: 999999}. Mitigation: 1) Field-level authorization: Define allowed read/write properties per role. Example: Regular users see [id, email, name], admins see [id, email, name, salary, role]. 2) Data Transfer Objects (DTOs): Explicit response schemas (UserPublicDTO vs UserAdminDTO), separate input/output models. 3) Allowlist writable fields: Only accept specific properties in PATCH/PUT (allowedFields = ['email', 'name', 'avatar']). Reject requests with unexpected properties. 4) GraphQL field resolvers: Implement authorization per field, not just per query. 5) API documentation: Clearly mark sensitive fields in OpenAPI spec (x-internal: true, readOnly: true, writeOnly: true). 6) Automated testing: Security tests verify sensitive fields not exposed, restricted fields cannot be modified. Tools: API security scanners (42Crunch, StackHawk), ORM configuration (Django REST Framework serializers with exclude fields, NestJS class-validator), GraphQL Shield for field authorization. Metrics: 30% of API vulnerabilities involve property-level authorization failures (OWASP 2023). Common in microservices where service returns full object assuming API gateway filters.
Studies show comprehensive API documentation can reduce development time by 30%. Best practices: interactive Swagger UI/Redoc for testing, clear endpoint descriptions with purpose, request/response examples for all operations (success + error cases), error codes with meanings and fixes documented, authentication flow examples (OAuth 2.0, JWT, API keys), SDK/code samples in multiple languages (JavaScript, Python, Go, Java), getting started guide (5-minute quickstart), use case tutorials, changelog for API updates (semantic versioning), searchable documentation, versioned docs per API version. Tools: OpenAPI 3.1, Swagger UI, Postman Collections, ReadMe.io, Stoplight, Redocly.
API-First: design API contract (OpenAPI spec) before implementation, adopted by Zalando, Stripe, Twilio. Define API contract using OpenAPI/AsyncAPI before coding. Benefits: (1) Parallel development - frontend/backend teams work simultaneously with mock servers. (2) Contract testing - validate against spec automatically. (3) Early feedback - stakeholders review API design pre-code. (4) Consistent API design - reusable patterns. (5) Auto-generated docs/SDKs. (6) Mock servers for testing (Prism, Stoplight). Design for API consumers first, not internal implementation. Version control specs (.yaml/.json in git). Review API designs (design-first reviews) before coding. Tools: Swagger Editor, Stoplight Studio, OpenAPI Generator.
Offset-based: page (page number, 1-indexed like GitHub or 0-indexed), limit/per_page/page_size (items per page, default 20-100, max 1000), offset (items to skip, used with limit). Cursor-based: cursor/next_cursor/after (opaque Base64 token), limit/first (items to return), before/previous (backward pagination). Additional: sort/order_by (field to sort, e.g. created_at), order/direction (asc/desc). Response metadata: {total: 500, page: 2, per_page: 20, has_more: true, next_page_url: '?page=3', next_cursor: 'eyJpZCI6MTIzfQ=='}. Standard names improve developer experience. GitHub API example: ?per_page=30&page=2.
API10:2023 (OWASP API Security Top 10) - Developers trust third-party APIs more than user input, applying weaker security standards when consuming external APIs. Attackers target third-party services interacting with APIs rather than direct attack. Risks: no validation of responses, blindly following redirects, no timeout limits, trusting data without sanitization, no certificate validation. If third-party API compromised, your API vulnerable (supply chain attack). Mitigate: validate all third-party API responses (schema validation), timeout configuration (prevent DoS), allowlist endpoints, strict TLS/certificate validation, treat third-party data as untrusted input (sanitize), monitor third-party API calls (rate limits, anomaly detection), implement circuit breakers.
Microsoft Azure REST API Design Guidelines (official Microsoft Cloud API standards): 1) Resource-oriented URIs: Use nouns, not verbs (GET /users/123/orders not GET /getUserOrders). Hierarchical structure for relationships. Plural nouns for collections. Lowercase with hyphens. 2) Standard HTTP methods semantics: GET (retrieve, idempotent, cacheable), POST (create, non-idempotent), PUT (replace entire resource, idempotent), PATCH (partial update), DELETE (remove, idempotent). Use correct status codes: 200 OK, 201 Created with Location header, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 429 Too Many Requests, 500/503 server errors. 3) JSON everywhere: Content-Type: application/json, camelCase property names, ISO 8601 dates (2025-01-15T10:30:00Z), omit null values. 4) Pagination required for collections: Default page size 50-100, max 1000. Use continuation tokens (cursor-based) for large datasets. Response includes nextLink for next page. Example: {value: [...], nextLink: '/api/users?continuationToken=abc123'}. 5) Filtering and sorting: OData-style query operators (?$filter=status eq 'active'&$orderby=createdDate desc) or simple params (?status=active&sort=createdDate). Support field selection (?$select=id,name,email). 6) Versioning: URI path versioning (/api/v1/users) or query parameter (?api-version=2025-01-15). Date-based versions for clarity. Maintain backwards compatibility across minor versions. 7) Asynchronous operations (long-running tasks >2 seconds): Return 202 Accepted immediately with Operation-Location header pointing to status endpoint. Client polls GET /operations/{id} until completion (status: succeeded/failed/running). Final response includes result or error. Pattern: POST creates operation, returns 202, GET /operations/{id} tracks progress, DELETE /operations/{id} cancels. 8) Optimistic concurrency: Use ETags (entity tags) for conditional requests. GET returns ETag header. PUT/PATCH/DELETE includes If-Match: {etag} header. Return 412 Precondition Failed if ETag mismatch (resource changed). Prevents lost updates. 9) Error responses: RFC 9457 Problem Details format (application/problem+json) with type, title, status, detail, instance properties. Include correlation ID (x-ms-correlation-request-id) for support. 10) CORS support: Implement proper Access-Control headers for browser clients. 11) Rate limiting: Return RateLimit-* headers (Limit, Remaining, Reset). 429 Too Many Requests with Retry-After. 12) HATEOAS links: Include hypermedia links for related resources ({_links: {self: '/users/123', orders: '/users/123/orders'}}). 13) API lifecycle: Deprecation warnings (Sunset header with removal date), changelog documentation, breaking changes require new major version. Tools: Azure API Management for gateway, OpenAPI 3.1 spec, Swagger UI, Azure SDKs (auto-generated from OpenAPI). Microsoft prescriptive guidance used by all Azure services (Compute, Storage, Cosmos DB APIs).
API9:2023 (OWASP API Security Top 10, formerly Improper Assets Management in 2019) - Organizations lack proper documentation and accurate inventory of API hosts and deployed versions, creating unknown gaps in attack surface. APIs expose more endpoints than traditional web apps. Risks: old API versions with vulnerabilities still accessible, shadow APIs unknown to security teams, non-production environments publicly accessible, deprecated endpoints not decommissioned, undocumented APIs (zombie APIs). Mitigate: maintain complete API inventory (all hosts, versions, endpoints), document all API versions, retire/deprecate old versions (sunset headers), inventory all environments (dev/staging/prod), API gateway for centralized management, automated discovery tools (API scanners), version control OpenAPI specs.