Overview

14 Adapting API design to context

Great API designs are context-aware: beyond security and efficiency, they must account for consumer capabilities, domain standards, communication patterns, the nature of data and operations, implementation realities, and business or infrastructure constraints. The chapter shows how to surface these factors early, challenge assumptions, and then make pragmatic trade-offs when needed. Typical adaptations include supporting method-limited clients via the X-HTTP-Method-Override header; offering content negotiation or separate APIs to reconcile XML/JSON audiences; handling planned downtime with 503 plus Retry-After or by accepting requests and returning 202 Accepted; ensuring URL-safe identifiers and controlling URL length; and preferring JSON Merge Patch for partial updates while accommodating alternatives when warranted.

Files demand tailored flows, models, and documentation. The text contrasts attaching documents directly to business resources with using a generic File API, and explains one-shot submissions that mix data and binaries via Base64 (larger payloads) or multipart/form-data (more efficient, but not universally supported). It details how to describe raw and mixed bodies in OpenAPI (content types, encodings, multipart parts) and how to keep file exchange efficient: don’t echo files on upload, enable caching and conditional requests, support partial transfer with Range and Content-Range, and use Expect: 100-continue to avoid waste. When infrastructure can’t transit binaries, delegate to storage systems with signed URLs—redirect downloads with 303 See Other and provide upload instructions (URL, method, headers) instead of proxying content.

For provider-originated events and long-running work, the chapter recommends webhooks and callbacks. Webhooks should be optional and interoperable (e.g., CloudEvents), include the right payload granularity (lightweight pointers for volatile or large data, heavier payloads for small/static data), be secured (signatures, mutual TLS, allowlists, OAuth), respond quickly with a 2xx, and offer failure strategies (automatic retries, on-demand redelivery, history) with clear OpenAPI descriptions. Long operations should return 202 with a status resource, progress and timing hints, or use callbacks to avoid polling; the Prefer header can allow selective synchronous handling. Finally, designers should stay tool-agnostic and consider alternatives to REST—event-driven architecture for internal events, Server-Sent Events for streams, WebSockets for bidirectional chat, GraphQL for backend-for-frontend needs, and gRPC for efficient service-to-service—choosing the best fit for the context.

Many contextual factors other than security and efficiency constrain API design.
CH14 F01 lauret3
The Verify Account Information operation request with custom JSON and standard ISO20022 data.
CH14 F02 lauret3
We can send a mix of data and files by encoding file content in Base64 strings in JSON or using the multipart/form-data media type.
CH14 F03 lauret3
Base64 encodes any binary or textual data into a string; it can be embedded into a JSON string.
CH14 F04 lauret3
When we can’t directly return file content to the consumer, we can leverage a 303 See Other redirection response to redirect consumers to the file.
CH14 F05 lauret3
When we can’t directly receive file content, we can provide an operation that generates a URL targeting a system that can receive it in the place of our API.
CH14 F06 lauret3
The Banking notification system calls the Transaction Notification webhook to prevent the consumers from polling transactions.
CH14 F07 lauret3
The Banking notification system notifies a consumer of a new transaction with a POST request whose body leverages the CloudEvents format.
CH14 F08 lauret3
A light event only contains a reference that can be used to get data via a regular API call. A heavy event contains usable data and may not necessitate an API call.
CH14 F09 lauret3
Webhooks go under the webhooks property of the OpenAPI document. A webhook doesn’t have a path but an identifier. For the rest, a webhook is defined like any other operation under paths.
CH14 F10 lauret3
An operation callback is defined under callbacks within the operation object. Its path can be static or contain runtime variables. We use a design consistent with the previously defined transaction notification webhook.
CH14 F11 lauret3

FAQ

What does it mean to adapt an API design to its context?It means tailoring design choices to real-world constraints and usage: consumer limitations, domain standards, communication patterns, data/operation nature, implementation, and infrastructure/business realities. First challenge constraints to find root causes; then make explicit trade-offs only when unavoidable, aiming for a design that meets needs, is secure, efficient, and implementable.
How can I uncover and challenge constraints before changing my design?Continuously ask targeted questions during design: consumer method/format limits, industry standards, real-time or reverse communication needs, data compatibility with URLs and files, operation duration/human steps, implementability, and infra/business availability. Validate whether constraints are still true, solvable, or workarounds exist; only then adapt the design.
How do I support clients that don’t support PATCH or DELETE?Support the de facto standard header X-HTTP-Method-Override. For example, instead of PATCH /resources/123, accept POST /resources/123 with X-HTTP-Method-Override: PATCH (and similarly for DELETE). This avoids redesigning resources while enabling legacy consumers.
What’s the best way to serve both JSON- and XML-centric consumers?Use content negotiation so consumers choose via Accept (for example, application/json or application/xml). If domain standards (like ISO20022) overly constrain design or flows, consider separate APIs or committing to a single format based on goals and audiences.
How should I handle planned downtime or business-hour-only processing?Two patterns: return 503 Service Unavailable with a Retry-After header indicating when to retry, or accept and queue valid requests and return 202 Accepted with a status like DELAYED and a processingDate. Choose based on feasibility and user experience.
How do I keep IDs URL-safe and avoid overly long URLs?Avoid special characters in IDs used in paths/queries; if present, require URL encoding or transform to URL-compatible forms at the API boundary. Keep URLs under ~2000 chars; if filters get large (for example, many IDs), use POST /.../search with a body instead of long query strings.
What are my options for sending/receiving files, and how do I document them?Flows: attach files directly to a business resource (for example, PUT /resources/{id}/documents/{type}) or use a generic File API (POST /files then reference fileId). One-call uploads mixing data+files: either embed Base64 in JSON (larger) or use multipart/form-data (preferred). In OpenAPI, describe raw files by listing media types under content (empty schema), Base64 in JSON with contentMediaType + contentEncoding, and multipart parts with encoding to set per-part media types.
How can I make file transfers efficient and resilient?Enable caching and conditional requests; don’t return full file content on upload/create. Support partial download with Range (206/416) and partial upload with Content-Range (202 + Location for continuation). For large files, allow pre-checks with Expect: 100-continue to avoid waste on rejected uploads.
When should I use webhooks or callbacks, and how do I design and secure them?Use webhooks for provider-initiated events (for example, new transactions) and callbacks for consumer-initiated long operations finishing (for example, simulation end). Prefer CloudEvents for interoperable payloads; choose light events (links) for volatile/large data and heavy events for small/static data. Secure with measures like mutual TLS, signatures, allowlisting, or OAuth; define simple 2XX success behavior; plan retries/redelivery and, if needed, history endpoints. Document webhooks under webhooks and callbacks under callbacks in OpenAPI.
When should I consider API types beyond REST?Consider SSE for server-to-client streaming, WebSockets for real-time bidirectional communication, EDA (messaging) for internal event distribution, GraphQL for BFF-style aggregation/precise data selection (mind caching and query limits), and gRPC for efficient service-to-service communication over HTTP/2 (not browser-native). Choose based on needs like streaming, bidirectionality, internal events, or BFF specifics.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Design of Web APIs, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Design of Web APIs, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Design of Web APIs, Second Edition ebook for free