Chapter 6: Reliable API Design: Public Contracts and Synchronous Communication
This chapter introduction previews API contracts, REST and GraphQL, AI-facing APIs, REST’s origins, and versioned endpoints.
After this chapter you will be able to
- Public API and Protected Core. Explain why a protected domain core still needs a public API and describe the API as a promise to its consumers.
- Client and server roles. Explain how the client-server model splits work between a client that initiates a request and a server that holds resources and fulfills it.
- Network boundary costs. Describe where the network boundary lies and why crossing it introduces latency, failure, and complexity compared with an in-memory call.
- Cost of boundary crossings. Explain how crossing the client-server boundary changes a call and why each crossing deserves attention as a possible failure point.
- Client and server responsibilities. Distinguish the client's role in capturing intent, validating input, and presenting results from the server's role in applying business rules, managing data and security, executing logic, and returning results.
- Request Response Cycle. Trace a web request from the client’s request through server processing and response to the client’s UI update. Explain who initiates the exchange.
- Communication Versus Work Flow. Distinguish the synchronous request-and-acknowledgment exchange from the flow of work it triggers. Explain how an early receipt can release the caller while work continues in the background.
- Stateless Requests And Scale. Explain what a stateless server does not remember, what each request must supply, and why that lets different servers handle successive requests.
- Client feedback and server authority. Explain why the section favors thick clients for user experience while retaining critical business rules on the server, using the email example.
- Scale through server separation. Explain how a client-server design can serve more users by adding servers without changing the lightweight client, and contrast this with distributing and updating a combined UI-and-logic executable.
- Specialized teams and API agreement. Explain how separating client and server lets frontend and backend teams change their respective parts independently, provided they agree on the API contract.
- API as public contract. Explain that an API is more than a list of endpoints: it is an agreement specifying allowed requests, data formats, and responses. Describe REST and GraphQL as specific styles that implement this broader contract idea.
- Published contract change limits. Explain why changing a published API differs from refactoring internal code: the provider cannot update every dependent client, so a change can break systems that rely on the contract.
- API Menu Contract. Explain how the restaurant’s kitchen, customer, and menu correspond to the server, client, and API, and how the menu defines the available requests.
- Decoupling Through a Stable Menu. Explain why the kitchen can change without the customer needing to know, provided it still delivers what the menu promises.
- Four API contract clauses. Describe the endpoint, headers, request and response bodies, and status codes as parts of the agreement between client and server. Explain how changing an expected address or field, or returning a misleading status, breaks that agreement.
- Idempotency under network retries. Explain why a lost response can cause a client to retry and how idempotency prevents an identical request from repeating an action, such as charging for a payment twice.
- Published API contract obligations. Explain why changing a published API is riskier than changing internal service code, and why an endpoint must remain supported until its consumers have migrated away.
- Breaking versus nonbreaking changes. Distinguish the API changes this section calls breaking from additions it calls non-breaking, using the examples of fields, data types, and parameters.
- Hidden API behavioral contract. Explain Hyrum’s Law using the user-list example: clients can rely on observable behavior even when it is absent from the written API contract. Describe why a change to that behavior calls for a formal versioning strategy.
- Side-by-Side API Contracts. Explain how URI-path versioning lets an API change its response format while existing clients continue using the old contract.
- Date-Based Compatibility Translation. Trace how a date-based API version request is handled at the architectural level.
- REST and GraphQL tradeoff. Distinguish REST and GraphQL as ways to expose an API contract over HTTP, and explain why the choice depends on the consumers' needs rather than one style always winning or both being required.
- REST Resource Contract. Explain how REST exposes resources at URLs and why a request ordinarily returns the resource’s representation rather than just the fields a client wants. Describe field filtering as a way to reduce over-fetching while keeping REST’s simplicity.
- HTTP Verb Retry Safety. Distinguish the retry behavior of GET, PUT, and DELETE from POST, and explain why architects choose verbs according to the retry strategy rather than how a verb sounds.
- Idempotent Payment Contract. Describe how a payment contract can use PUT with a transaction ID instead of POST to avoid double-charging on retries. Explain how the server handles a repeated request when the desired state already exists.
- GraphQL Data Selection Tradeoffs. Explain how a GraphQL client requests exactly the data it needs, including data from different resources in one request, and describe the server-complexity and caching costs.
- GraphQL Reads And Writes. Distinguish a safe GraphQL query from a data-changing mutation, and explain why sending both over HTTP POST does not make a mutation safe to retry.
- Mutation Idempotency Key Handling. Trace how a client-generated idempotency key lets the server recognize a retried mutation and return the original success response without repeating the payment.
- Consumer Driven API Choice. Explain how the API consumer and network conditions shape the REST-versus-GraphQL decision in the Chip Inventory example. Compare the warehouse scanner’s multiple REST requests with its single GraphQL request.
- Public API Decision Record. Justify the example’s REST choice for the public partner API and describe what its ADR records about benefits, costs, and possible mitigation.
- Tailored Frontend API Adapters. Describe the Backends for Frontends pattern and explain how a warehouse-specific GraphQL adapter could coexist with a general REST API.
- APIs for AI agents. Explain how AI agents change the audience for an API and why its design must communicate clearly to them.
- Explicit instructions for AI agents. Explain why an AI agent needs clear, explicit instructions rather than vague slang or internal acronyms.
- Focused responses and context cost. Explain how oversized API responses affect an AI agent, and why a specific tool may be preferable to a giant one-size-fits-all tool.
- API schema as instruction. Explain why endpoint and field names guide an LLM calling an API, and how vague names can cause it to guess incorrectly.
- API Specification as AI Interface. Explain why an OpenAPI or Swagger specification should be treated as an interface for AI agents, not just as documentation for people.
- Client Server Contract Boundary. Explain where the client and server sit in the diagram and how they communicate through the API contract rather than touching directly.
- Controller as boundary translator. Explain how a controller receives HTTP and JSON at the edge of the system, turns them into application-level calls, delegates work to a service, and translates the answer back. Distinguish its HTTP responsibilities from business rules and SQL.
- Controller as replaceable translator. Explain that the Controller translates web requests into calls to a service rather than containing the business logic, so a CLI could call the same service through a different adapter.
- Abstraction’s Hidden Tradeoff. Explain why a clean interface can simplify a client’s work while concealing performance problems or other complexity on the server.
- N Plus One Query Pattern. Explain how one query for a list of parent items can lead to a separate child-data query for every item, producing N+1 database calls.
- REST Lazy Loading Trap. Describe how accessing related data inside a loop can make an ORM issue a query for each item, and how eager loading avoids those separate queries.
- GraphQL Resolver Batching. Trace how independently resolved GraphQL fields can cause per-order user lookups, and explain how DataLoader batches those lookups.
- API Sprawl and Its Cost. Explain how easily created, feature-specific endpoints accumulate into API sprawl and why that becomes a problem for the team.
- Generalized Endpoint and Pruning. Describe the proposed fix: use one robust endpoint with filtering capabilities for related needs, and regularly prune the API.
- Database Abstraction Skill Gap. Explain how relying entirely on a database abstraction can leave a developer unable to diagnose failures, and describe the SQL knowledge the section says developers need.
- Synchronous call chain costs. Explain why having the Order API wait for Inventory, Payment, and Shipping creates a distributed monolith, increasing user wait time and making order placement depend on Shipping being available.
- Asynchronous shipping label task. Describe the section's proposed split: check stock and charge the card synchronously, but put printing the shipping label in a queue for later processing because the user need not wait for it.
- REST’s Observational Origin. Explain why Fielding’s contribution is presented as an observation of the Web rather than an invention, against the backdrop of enterprise distributed-system protocols of the time.
- REST resource model. Explain that REST is an architectural style rather than a strict protocol, organizing an application around resources identified by URLs and acted on with standard web verbs.
- REST architectural constraints. Describe the four REST constraints named here and what each requires: client-server separation, stateless requests, explicitly cacheable responses, and a uniform interface.
- Client-held application state. Explain why Fielding argued that the server should stop remembering what a client was doing and instead transfer that state to the client, usually in a JSON or HTML representation.
- Response Links as Action Guides. Explain how HATEOAS puts links to valid next actions in an API response instead of requiring the client to hardcode the sequence of URLs. Describe how a frontend can use the presence or absence of a cancel link to decide whether to show a Cancel button.
- REST Maturity and Practicality. Explain that the Richardson Maturity Model grades how RESTful an API is across four levels, and distinguish the purist view of Level 3 from the section’s pragmatic view that Level 2 is usually sufficient.
- Essential REST Design Constraints. Explain why an API need not implement full HATEOAS to be successful, but should respect statelessness and cacheability. Describe the resilience and scalability the section associates with those constraints.
- Contract-first feature planning. Explain why the architect starts with the contract rather than immediately coding a to-do list feature that lets users see and add tasks.
- Function-style API contract pitfalls. Explain why the proposed GET /api/getMyThings and POST /api/saveThing endpoints are a poor API design, and why returning only strings creates problems for identifying and extending items.
- UserProfile RESTful contract. Apply the exercise’s review criteria to propose a resource-based UserProfile API: name the resource, use HTTP methods for reading and updating it, and return an extensible JSON object instead of a raw address string.
- API Public Contract. Explain that an API is a public contract that cannot be easily broken, and recognize breaking changes as a serious problem in API development.
- Retry Safety Through Idempotency. Explain that idempotency protects against duplicate actions during network retries, and distinguish the approaches named for REST and GraphQL.
- Client Server Communication Boundary. Explain how clients and servers divide responsibilities, and why a synchronous API call can start asynchronous background work instead of making the caller wait through a blocking chain.
- Reliable Public API Contract. Explain why an API must be treated as a public contract, including how stateless requests, idempotent retries, and versioning address different reliability risks.
What it builds on
- Inside, Ports, and Adapters (chapter 5) · Introduces the protected core and its ports.
- Separation of Concerns (chapter 3) · Separation of concerns as a way to assign distinct responsibilities.
- 1. The Inside (The Core) (chapter 5) · The application core as the inside of the system.
- The Architectural Thinking Process: From an Idea to a Blueprint (chapter 1) · The five-step architectural thinking process.
- Architecture Decision Records (ADR) (chapter 2) · Architecture Decision Records as records of architectural decisions.
- S – Single Responsibility Principle (SRP) (chapter 3) · The Single Responsibility Principle used to distinguish general access from frontend performance.
Section by section
Introduction
This chapter introduction previews API contracts, REST and GraphQL, AI-facing APIs, REST’s origins, and versioned endpoints.
Introduction
Introduces APIs as public interfaces that let outside consumers use a protected domain core, and defines API-driven architecture as integration between services through APIs.
- Public API and Protected Core: Explain why a protected domain core still needs a public API and describe the API as a promise to its consumers.
Why it matters: The API makes protected software usable from outside while establishing expectations for its consumers. - API-Driven Architecture Scope: Describe what API-Driven Architecture means in this section and distinguish that scope from language-specific constructs.
Why it matters: This definition keeps the discussion focused on how services interact, not on a particular programming-language feature.
Key terms: Domain Core, Ports, Public Interface, API, Public Contract, consumers, API-Driven Architecture, API-Based Architecture, API-Driven Development, service boundaries
6.2 The Client-Server Model
This section defines the client-server split and explains why communicating across its network boundary is more costly than an in-memory call.
- Client and server roles: Explain how the client-server model splits work between a client that initiates a request and a server that holds resources and fulfills it.
Why it matters: Identifying who requests and who fulfills the request makes their communication easier to reason about. - Network boundary costs: Describe where the network boundary lies and why crossing it introduces latency, failure, and complexity compared with an in-memory call.
Why it matters: A network call has risks and costs that a local function call does not.
Key terms: Client-Server Model, Client, Server, Network Boundary, latency, failure, complexity
6.2.1 The Cost of Crossing the Line
Crossing the client-server boundary trades the speed and reliability of an in-memory call for the reach and scale of a network request.
- Cost of boundary crossings: Explain how crossing the client-server boundary changes a call and why each crossing deserves attention as a possible failure point.
Why it matters: Recognizing the cost of a network crossing helps you spot where an architecture may become slower or fail.
Key terms: boundary, in-memory function call, network request, scale and reach, point of failure
6.2.2 The Separation of Duties
This section divides client and server responsibilities and explains why a clear boundary makes systems easier to maintain and scale.
- Client and server responsibilities: Distinguish the client's role in capturing intent, validating input, and presenting results from the server's role in applying business rules, managing data and security, executing logic, and returning results.
Why it matters: A clear division tells you where user-facing behavior ends and the system's rules begin. - System-level separation benefits: Explain how assigning distinct duties to clients and servers supports maintenance and scaling, and why the server handles different kinds of clients according to the same contract.
Why it matters: A shared server contract lets different clients use the system without changing who owns the core rules.
Key terms: Client, Server, Presentation, Input Validation, Business Logic, Separation of Concerns, contract, maintain, scale
6.2.3 The Anatomy of the Conversation (Request/Response)
Explains how a client-server request and response work, why synchronous communication need not mean synchronous work, and how stateless requests support scaling.
- Request Response Cycle: Trace a web request from the client’s request through server processing and response to the client’s UI update. Explain who initiates the exchange.
Why it matters: Following each step gives you a starting point for debugging an API interaction. - Communication Versus Work Flow: Distinguish the synchronous request-and-acknowledgment exchange from the flow of work it triggers. Explain how an early receipt can release the caller while work continues in the background.
Why it matters: Separating the acknowledgment from the work helps prevent a slow task from holding up the caller. - Stateless Requests And Scale: Explain what a stateless server does not remember, what each request must supply, and why that lets different servers handle successive requests.
Why it matters: Self-contained requests make it easier to spread traffic across multiple servers.
Key terms: Request-Response Cycle, Request, Processing, Response, Rendering, Synchronous Communication, Asynchronous Flow, 202 Accepted, Blocking Chain, Statelessness
6.2.4 The "Clarity" Tradeoff: Thick vs. Thin Clients
This section compares thin and thick clients and explains why fast client-side feedback should be paired with server-side enforcement of critical business rules.
- Thin client tradeoffs: Describe what a thin client leaves to the server and the benefits and costs of that choice.
Why it matters: Where the work happens affects security, updates, responsiveness, and offline use. - Thick client tradeoffs: Describe what a thick client does with server data and the benefits and costs of doing more work locally.
Why it matters: A more responsive interface comes with code and versioning costs that the architecture must account for. - Client feedback and server authority: Explain why the section favors thick clients for user experience while retaining critical business rules on the server, using the email example.
Why it matters: Fast feedback is useful, but a client-side check should not be the final authority on whether an action is allowed.
Key terms: Thin Client, Server-Side Rendering, round-trip, Thick Client, Single Page Apps, Mobile Apps, JSON, UI state, Critical Business Rules, Fast feedback
6.2.5 Why We Split Them (Scale and Specialization)
This section explains why separating clients from servers is worth the network costs: it supports scaling and lets specialized teams work independently.
- Scale through server separation: Explain how a client-server design can serve more users by adding servers without changing the lightweight client, and contrast this with distributing and updating a combined UI-and-logic executable.
Why it matters: The separation can accommodate more users without requiring everyone to install a changed client. - Specialized teams and API agreement: Explain how separating client and server lets frontend and backend teams change their respective parts independently, provided they agree on the API contract.
Why it matters: An agreed API lets teams focus on different expertise without tying every internal change to the other team’s work.
Key terms: Client-Server model, Monolith, Horizontal Scaling, Frontend Engineers, Backend Engineers, Contract, API
6.3 API as a Public Contract
This section frames an API as a client-server commitment and explains why publishing it limits the changes its provider can safely make.
- API as public contract: Explain that an API is more than a list of endpoints: it is an agreement specifying allowed requests, data formats, and responses. Describe REST and GraphQL as specific styles that implement this broader contract idea.
Why it matters: Treating an API as a contract shifts attention from endpoint code to what clients can rely on. - Published contract change limits: Explain why changing a published API differs from refactoring internal code: the provider cannot update every dependent client, so a change can break systems that rely on the contract.
Why it matters: A change that looks small to the API provider may disrupt clients the provider cannot update.
Key terms: API, public contract, Client, Server, REST, GraphQL, published contract, dependent services, breaking change
6.3.1 The "Restaurant Menu" Analogy
The restaurant-menu analogy shows how an API defines what clients can request while hiding the server’s internal workings.
- API Menu Contract: Explain how the restaurant’s kitchen, customer, and menu correspond to the server, client, and API, and how the menu defines the available requests.
Why it matters: The menu analogy makes clear that clients interact with a defined interface, not the server’s internals. - Decoupling Through a Stable Menu: Explain why the kitchen can change without the customer needing to know, provided it still delivers what the menu promises.
Why it matters: A stable external promise lets a team change the server without forcing clients to follow its internal changes.
Key terms: Kitchen, Server, Customer, Client, Menu, API, Decoupling, contract
6.3.2 The Clauses of the Contract
This section defines the four clauses of an API contract and explains why idempotency makes retries safe when network responses are lost.
- Four API contract clauses: Describe the endpoint, headers, request and response bodies, and status codes as parts of the agreement between client and server. Explain how changing an expected address or field, or returning a misleading status, breaks that agreement.
Why it matters: A client can depend on an API only when its address, metadata, data shapes, and reported outcome mean what the contract says they mean. - Idempotency under network retries: Explain why a lost response can cause a client to retry and how idempotency prevents an identical request from repeating an action, such as charging for a payment twice.
Why it matters: A dropped response should not turn a reasonable retry into a duplicate payment or other repeated action.
Key terms: Endpoint, Headers, Request Body, Response Body, Status Codes, Redirect, Idempotency, network boundary, no-op
6.3.3 The "Breaking Change" Nightmare
This section explains why published APIs are difficult to change and distinguishes breaking changes from changes existing clients can ignore.
- Published API contract obligations: Explain why changing a published API is riskier than changing internal service code, and why an endpoint must remain supported until its consumers have migrated away.
Why it matters: An API change can disrupt clients you do not deploy alongside your service. - Breaking versus nonbreaking changes: Distinguish the API changes this section calls breaking from additions it calls non-breaking, using the examples of fields, data types, and parameters.
Why it matters: This distinction helps you recognize which API edits could break existing clients.
Key terms: contract, API endpoint, consumer, breaking change, Non-Breaking Change, required parameter, optional parameter, response field
6.3.4 Hyrum's Law: The Hidden Contract
Explains why clients may depend on undocumented API behavior and why changing that behavior requires a formal versioning strategy.
- Hidden API behavioral contract: Explain Hyrum’s Law using the user-list example: clients can rely on observable behavior even when it is absent from the written API contract. Describe why a change to that behavior calls for a formal versioning strategy.
Why it matters: A change that looks safe against the documentation can still break real clients.
Key terms: Hyrum’s Law, Public Contract, observable behaviors, formal versioning strategy
6.3.5 The Escape Hatch: Versioning
Explains how API versioning lets a public contract evolve without breaking existing clients, and compares URI-path and date-based approaches.
- Side-by-Side API Contracts: Explain how URI-path versioning lets an API change its response format while existing clients continue using the old contract.
Why it matters: You can introduce a new contract without immediately breaking integrations that rely on the old one. - Date-Based Compatibility Translation: Trace how a date-based API version request is handled at the architectural level.
Why it matters: It explains how older client contracts can be supported without keeping the core application on old domain models. - Versioning Strategy Tradeoff: Justify when to favor simple URI-path versioning versus exploring date-based versioning, using the client and server costs described here.
Why it matters: The choice shifts migration work between API consumers and the team maintaining the API.
Key terms: Versioning, URI Path Versioning, v1, v2, public contract, Date-Based Versioning, release date header, API Gateway, Middleware, backward-compatibility transformations
6.4 REST or GraphQL
Introduces REST and GraphQL as alternative HTTP styles for exposing an API contract and frames the choice as an engineering tradeoff.
- REST and GraphQL tradeoff: Distinguish REST and GraphQL as ways to expose an API contract over HTTP, and explain why the choice depends on the consumers' needs rather than one style always winning or both being required.
Why it matters: The API style should serve its consumers rather than follow a supposed universal winner.
Key terms: REST, GraphQL, Public Contract, endpoints, targeted querying
6.4.1 REST: The Vending Machine
This section explains REST’s resource-based contract, its over-fetching tradeoff, and how HTTP verb choices make retries safe or unsafe.
- REST Resource Contract: Explain how REST exposes resources at URLs and why a request ordinarily returns the resource’s representation rather than just the fields a client wants. Describe field filtering as a way to reduce over-fetching while keeping REST’s simplicity.
Why it matters: It helps you weigh REST’s straightforward contract against sending data a client does not need. - HTTP Verb Retry Safety: Distinguish the retry behavior of GET, PUT, and DELETE from POST, and explain why architects choose verbs according to the retry strategy rather than how a verb sounds.
Why it matters: A verb choice can determine whether a client safely recovers from a dropped connection or repeats a costly action. - Idempotent Payment Contract: Describe how a payment contract can use PUT with a transaction ID instead of POST to avoid double-charging on retries. Explain how the server handles a repeated request when the desired state already exists.
Why it matters: It turns retry safety into a concrete API-contract decision for a high-stakes operation.
Key terms: REST, Resource, URL, over-fetching, field filtering, idempotency, GET, PUT, DELETE, POST
6.4.2 GraphQL: The Personal Shopper
This section explains GraphQL’s precise client-selected responses, the retry risk of mutations, and the tradeoffs that shape when to use GraphQL, REST, or gRPC.
- GraphQL Data Selection Tradeoffs: Explain how a GraphQL client requests exactly the data it needs, including data from different resources in one request, and describe the server-complexity and caching costs.
Why it matters: It helps you weigh fewer, more precise network calls against implementation and caching costs. - GraphQL Reads And Writes: Distinguish a safe GraphQL query from a data-changing mutation, and explain why sending both over HTTP POST does not make a mutation safe to retry.
Why it matters: Distinguishing reads from writes prevents treating every POST request as having the same retry risk. - Mutation Idempotency Key Handling: Trace how a client-generated idempotency key lets the server recognize a retried mutation and return the original success response without repeating the payment.
Why it matters: This protects customers from duplicate charges when a client must retry an uncertain request. - API Style Suitability: Describe the uses and limitations the section gives for REST, GraphQL, and gRPC rather than treating one as universally best.
Why it matters: The intended clients and communication needs help determine which API style is a defensible choice.
Key terms: GraphQL, over-fetching, Personal Shopper, HTTP POST, query, mutation, idempotent, Idempotency Key, UUID, REST
6.4.3 Making The Defensible Decision
Uses the Chip Inventory example to choose an API style based on its consumers, document the tradeoff, and tailor APIs for different frontends.
- Consumer Driven API Choice: Explain how the API consumer and network conditions shape the REST-versus-GraphQL decision in the Chip Inventory example. Compare the warehouse scanner’s multiple REST requests with its single GraphQL request.
Why it matters: The right API style depends on who uses it and what each request costs them. - Public API Decision Record: Justify the example’s REST choice for the public partner API and describe what its ADR records about benefits, costs, and possible mitigation.
Why it matters: Recording both the reasons and the costs makes the public API choice defensible to the team. - Tailored Frontend API Adapters: Describe the Backends for Frontends pattern and explain how a warehouse-specific GraphQL adapter could coexist with a general REST API.
Why it matters: Different frontends can get data suited to their needs without forcing every consumer through one generic interface.
Key terms: Napkin Sketch, REST, GraphQL, round-trips, chatty, Architecture Decision Record, ADR, RESTful API, HTTP caching, OpenAPI
6.5 Designing for the New User: The AI Agent
This section explains why AI agents as API consumers make clear API documentation and design more important.
- APIs for AI agents: Explain how AI agents change the audience for an API and why its design must communicate clearly to them.
Why it matters: Your API may need to make sense to an agent deciding how to use it, not just to a developer writing code.
Key terms: APIs, LLMs, AI Agents, API documentation
6.5.1 The "Dumb Genius" Paradox
This section explains why APIs for AI agents need explicit language and focused responses: agents can reason well but lack implicit context, and unnecessary data consumes limited context and money.
- Explicit instructions for AI agents: Explain why an AI agent needs clear, explicit instructions rather than vague slang or internal acronyms.
Why it matters: Clear API language helps an agent use what you provide instead of guessing what you meant. - Focused responses and context cost: Explain how oversized API responses affect an AI agent, and why a specific tool may be preferable to a giant one-size-fits-all tool.
Why it matters: Returning only useful data can reduce token costs and preserve room for the agent's task instructions.
Key terms: AI Agent, Genius Intern, hallucinate, Context Window, tokens, Granularity, Convenience
6.5.2 Naming IS Prompt Engineering
This section explains how clear API names and explicit values guide LLM callers and reduce harmful guesses.
- API schema as instruction: Explain why endpoint and field names guide an LLM calling an API, and how vague names can cause it to guess incorrectly.
Why it matters: A vague API name can lead an AI caller to take the wrong action, not merely make the API harder to read. - Explicit DTO fields and values: Describe how the moderation DTO example makes an intended action clearer through a descriptive field name and a string enum instead of cryptic fields and a magic number.
Why it matters: Descriptive fields and values make the intended request clearer to an AI caller.
Key terms: API Schema, System Prompt, endpoint names, field names, Hallucination Hazard, Data Transfer Object (DTO), reasonType, string Enum, magic number, prompt engineered
6.5.3 The Modern Architect's AI Rule
This section explains how clear API specifications help AI agents choose the right tools and avoid unnecessary calls.
- API Specification as AI Interface: Explain why an OpenAPI or Swagger specification should be treated as an interface for AI agents, not just as documentation for people.
Why it matters: An endpoint description can affect whether an AI agent uses an API correctly. - Rules in Endpoint Descriptions: Describe how a specific rule in an endpoint summary can guide an AI agent's decision, using the ebook shipping example.
Why it matters: A well-written usage rule can prevent an error before an API call happens. - Specification First Source of Truth: State what the section says is generated from an OpenAPI specification when it is created first.
Why it matters: The server and AI tool definitions can be derived from the same contract.
Key terms: API Specification, OpenAPI/Swagger, User Interface for the Robot, XML comments, Rules of Engagement, digital items, OpenAPI specs, server stubs, AI tool definitions, same source of truth
6.6 Diagram: Client-Server
The section uses a client-server diagram to show the API contract as the boundary between an outside client and a controlled server.
- Client Server Contract Boundary: Explain where the client and server sit in the diagram and how they communicate through the API contract rather than touching directly.
Why it matters: This picture helps you reason about an endpoint or a bad request without treating the client and server as one system. - Gateway And Contract Roles: Distinguish the API contract shown as the middleman from the API gateway that may be placed in front of it in production.
Why it matters: Separating these roles keeps the API’s rules distinct from the gateway’s protective work.
Key terms: Client, Server, Contract (API), API Gateway, rate limiting, security
6.7 Code Snippet: API Endpoint
This section explains how a clean API controller translates between HTTP and application code without taking on business logic.
- Controller as boundary translator: Explain how a controller receives HTTP and JSON at the edge of the system, turns them into application-level calls, delegates work to a service, and translates the answer back. Distinguish its HTTP responsibilities from business rules and SQL.
Why it matters: Keeping translation separate from business work makes the API boundary easier to reason about. - Controller without an API view: Explain why a modern Web API still has a controller even though it returns JSON rather than a user-interface view.
Why it matters: A JSON-only API still needs a component to coordinate communication across its boundary.
Key terms: Controller, HTTP, JSON, Service, Routes, Status Codes, MVC, Model-View-Controller, View, Web APIs
6.7.1 Why This Matters
This subsection explains how a translating controller keeps business logic independent of the web, while warning that a clean API endpoint can conceal database performance problems.
- Controller as replaceable translator: Explain that the Controller translates web requests into calls to a service rather than containing the business logic, so a CLI could call the same service through a different adapter.
Why it matters: This separation lets you change how users reach the application without rewriting what the application does. - Clean endpoint performance warning: State why a clean-looking public endpoint is not, by itself, evidence of good database performance when an ORM backs it.
Why it matters: A clear API contract does not remove the need to examine what happens beneath the endpoint.
Key terms: Controller, Translator, Primary Adapter, Core, Service Interface, Port, Object-Relational Mappers (ORMs), public endpoints, interface contracts, database performance traps
6.8 The Hidden Costs of Abstraction
This section introduces the tradeoff that clean abstractions make an API easier for clients to use while potentially hiding costs on the server.
- Abstraction’s Hidden Tradeoff: Explain why a clean interface can simplify a client’s work while concealing performance problems or other complexity on the server.
Why it matters: A clean contract is valuable, but its convenience should not be mistaken for low server-side cost.
Key terms: Abstraction, Contracts, Client, Server
6.8.1 The Hidden Performance Trap: The N + 1 Problem
This section explains how N+1 database queries arise in REST and GraphQL implementations, how each can avoid them, and why API performance must be checked at the database level.
- N Plus One Query Pattern: Explain how one query for a list of parent items can lead to a separate child-data query for every item, producing N+1 database calls.
Why it matters: A screen that looks simple in code can generate many database calls as its list grows. - REST Lazy Loading Trap: Describe how accessing related data inside a loop can make an ORM issue a query for each item, and how eager loading avoids those separate queries.
Why it matters: An innocent-looking property access can hide repeated database work. - GraphQL Resolver Batching: Trace how independently resolved GraphQL fields can cause per-order user lookups, and explain how DataLoader batches those lookups.
Why it matters: GraphQL's flexible fields do not by themselves prevent excessive database calls. - Database Level Performance Checks: Explain why choosing REST or GraphQL and seeing good local performance do not establish that an API will perform well in production.
Why it matters: Checking actual database activity can reveal costs that neither an API style nor a code review makes obvious.
Key terms: N+1 Query Problem, parent items, child item, Object-Relational Mapper, ORM, lazy loading, eager loading, Include, JOIN, GraphQL
6.8.2 The Hidden Governance Trap: API Sprawl
This section explains how accumulating feature-specific API endpoints creates a hard-to-manage public contract and recommends generalization and pruning instead.
- API Sprawl and Its Cost: Explain how easily created, feature-specific endpoints accumulate into API sprawl and why that becomes a problem for the team.
Why it matters: Endpoint growth can make an API contract difficult for the team to manage. - Generalized Endpoint and Pruning: Describe the proposed fix: use one robust endpoint with filtering capabilities for related needs, and regularly prune the API.
Why it matters: A generalized, maintained API avoids needless growth in its public contract.
Key terms: API Sprawl, endpoints, Clean Contract, Generalization, filtering capabilities, prune
6.8.3 The Hidden Knowledge Trap: Debugging Hell
This subsection explains why database abstractions can create a debugging skill gap and why developers still need SQL fundamentals.
- Database Abstraction Skill Gap: Explain how relying entirely on a database abstraction can leave a developer unable to diagnose failures, and describe the SQL knowledge the section says developers need.
Why it matters: When a convenient database tool stops behaving as expected, understanding what it generates lets you investigate rather than treat the database as a black box.
Key terms: Skill Gap, Black Box, raw SQL, INDEX, JOIN, execution plans
6.8.4 The Hidden Availability Trap: Chained Dependencies
This section shows how a synchronous API call chain increases latency and makes order placement depend on every service, then illustrates moving noncritical shipping-label work to a queue.
- Synchronous call chain costs: Explain why having the Order API wait for Inventory, Payment, and Shipping creates a distributed monolith, increasing user wait time and making order placement depend on Shipping being available.
Why it matters: A seemingly simple sequence of API calls can make a slow or unavailable service affect the entire user-facing operation. - Asynchronous shipping label task: Describe the section's proposed split: check stock and charge the card synchronously, but put printing the shipping label in a queue for later processing because the user need not wait for it.
Why it matters: Separating work the user needs now from work that can happen later breaks a fragile dependency in the order flow.
Key terms: Coupling, Distributed Monolith, Latency Math, Availability Math, Synchronous, Asynchronous, Queue, Print Label
6.9 The Dork Side: The “Accidental Genius” Of REST
This section contrasts heavyweight late-1990s distributed-system protocols with the growing Web and explains that Roy Fielding described why the Web worked rather than inventing a new technology.
- REST’s Observational Origin: Explain why Fielding’s contribution is presented as an observation of the Web rather than an invention, against the backdrop of enterprise distributed-system protocols of the time.
Why it matters: It frames REST as an account of a working distributed system, not as a technology invented from scratch.
Key terms: SOAP, CORBA, World Wide Web, Roy Fielding
6.9.1 Dungeons and Dragons Trivia Time
This section introduces REST as Fielding’s architectural style for web applications and explains the resource model and constraints it uses.
- REST resource model: Explain that REST is an architectural style rather than a strict protocol, organizing an application around resources identified by URLs and acted on with standard web verbs.
Why it matters: This gives you the basic vocabulary for describing a REST API without mistaking REST for a protocol. - REST architectural constraints: Describe the four REST constraints named here and what each requires: client-server separation, stateless requests, explicitly cacheable responses, and a uniform interface.
Why it matters: These constraints explain what makes REST a consistent approach to client-server communication.
Key terms: REST, architectural style, Resources, URL, GET, POST, Client-Server, Statelessness, Cacheability, Uniform Interface
6.9.2 Why "State Transfer"?
This subsection explains “state transfer” as shifting responsibility for holding application state from the server to the client so the server can scale.
- Client-held application state: Explain why Fielding argued that the server should stop remembering what a client was doing and instead transfer that state to the client, usually in a JSON or HTML representation.
Why it matters: It explains the scalability idea behind the term “state transfer.”
Key terms: State, Server-Side State, Representation
6.9.3 The "Lost Ark" of REST: HATEOAS
Explains HATEOAS as a REST approach in which response links tell clients which actions are currently available.
- Response Links as Action Guides: Explain how HATEOAS puts links to valid next actions in an API response instead of requiring the client to hardcode the sequence of URLs. Describe how a frontend can use the presence or absence of a cancel link to decide whether to show a Cancel button.
Why it matters: Response links let the server communicate available actions without the frontend hardcoding every action URL.
Key terms: HATEOAS, Hypermedia, Application State, Client, Server
6.9.4 Leveling Up: The Richardson Maturity Model
Introduces the Richardson Maturity Model as a way to grade how RESTful an API is and contrasts strict Level 3 expectations with a pragmatic acceptance of Level 2.
- REST Maturity and Practicality: Explain that the Richardson Maturity Model grades how RESTful an API is across four levels, and distinguish the purist view of Level 3 from the section’s pragmatic view that Level 2 is usually sufficient.
Why it matters: It helps you separate an ideal of REST purity from a level the author considers practical.
Key terms: Richardson Maturity Model, RESTful, Level 2, Level 3
6.9.5 The Historical Takeaway
The section explains why REST’s design intent matters more than implementing every feature associated with it.
- Essential REST Design Constraints: Explain why an API need not implement full HATEOAS to be successful, but should respect statelessness and cacheability. Describe the resilience and scalability the section associates with those constraints.
Why it matters: It helps you prioritize the API constraints the section links to resilience and scale rather than treating every REST feature as mandatory.
Key terms: HATEOAS, Statelessness, Cacheability, resilience, scalability
6.10 "In-Action": Defining an API Contract
A to-do list scenario introduces the architectural choice to define an API contract before writing code.
- Contract-first feature planning: Explain why the architect starts with the contract rather than immediately coding a to-do list feature that lets users see and add tasks.
Why it matters: It frames the API contract as the starting point for turning a feature request into a design.
Key terms: Clarity Engineer, Contract, To-Do List
6.10.1 The "Function" Mindset (The Anti-Pattern)
This subsection critiques a function-style API whose verb-based URLs and string-only responses make operations redundant, ambiguous, and hard to extend without breaking clients.
- Function-style API contract pitfalls: Explain why the proposed GET /api/getMyThings and POST /api/saveThing endpoints are a poor API design, and why returning only strings creates problems for identifying and extending items.
Why it matters: An API response must let clients identify items and accommodate changes without unexpectedly breaking them.
Key terms: Function Thinker, verbs in URLs, ID, extensibility, breaking clients
6.10.2 Exercise: The Contract Challenge
This exercise asks the reader to turn a function-style UserProfile API into a resource-based contract, then notes that request-response communication still makes clients wait on servers.
- UserProfile RESTful contract: Apply the exercise’s review criteria to propose a resource-based UserProfile API: name the resource, use HTTP methods for reading and updating it, and return an extensible JSON object instead of a raw address string.
Why it matters: A resource-based contract is clearer to callers and can accommodate additional profile data. - Request-response waiting cost: Explain why a client can still have a poor experience with a well-designed REST or GraphQL API when a service in a synchronous request-response chain is slow or offline.
Why it matters: A clean API contract does not remove the availability cost of waiting for a response.
Key terms: UserProfile, RESTful Contract, Resource, HTTP method, JSON object, Function Mindset, Request-Response Boomerang, REST, GraphQL
6.11 Checklist
This checklist reviews key API-design ideas from the chapter, including public contracts, retry safety, and the controller’s role.
- API Public Contract: Explain that an API is a public contract that cannot be easily broken, and recognize breaking changes as a serious problem in API development.
Why it matters: Thinking of an API as a contract makes changes to its public interface consequential. - Retry Safety Through Idempotency: Explain that idempotency protects against duplicate actions during network retries, and distinguish the approaches named for REST and GraphQL.
Why it matters: Retries should not accidentally repeat an action. - Controller As Translator: Describe the controller as a translator that keeps logic out of the interface.
Why it matters: This distinction keeps the API-facing interface from becoming the place for logic.
Key terms: API, Public Contract, Breaking Changes, Idempotency, Safety Clause, network retries, PUT, DELETE, idempotencyKey, Controller
6.12 Recap
Recaps how client-server boundaries, reliable API contracts, and API design choices affect communication with human and AI consumers.
- Client Server Communication Boundary: Explain how clients and servers divide responsibilities, and why a synchronous API call can start asynchronous background work instead of making the caller wait through a blocking chain.
Why it matters: Separating the call from the work it starts helps prevent a slow service from freezing the whole chain. - Reliable Public API Contract: Explain why an API must be treated as a public contract, including how stateless requests, idempotent retries, and versioning address different reliability risks.
Why it matters: These safeguards make requests and API changes less likely to surprise or harm consumers. - API Choice And Consumer Clarity: Distinguish the situations the recap assigns to REST and GraphQL, and describe what makes an API easier for AI agents to use.
Why it matters: Choosing an API style and making its operations clear helps consumers request what they need.
Key terms: Client-Server Model, Network Boundary, Synchronous Communication, Asynchronous Flow, Blocking Chains, Statelessness, Idempotency, Public Contract, versioning, Idempotency Key
Where this is used later
- Designing for Failure & Resilience Patterns (chapter 10) · The distinction between a client making requests and a server receiving them.
- Introduction (chapter 7) · Provides a contrast for asynchronous communication.
- The Network Tax: The Hidden Costs of Distributed Architectures (chapter 12) · Provides context for the costs of chained dependencies.
- The Architectural Rule: Stateless Design (chapter 9) · Supports the later architectural rule of stateless design.
- Scaling Out (Horizontal Scaling) (chapter 10) · Introduces horizontal scaling as adding servers to handle load.
- Retries (The Second Chance) (chapter 10) · Understanding safe repeated requests helps explain the risks of retries.
- The API Gateway: The Single Chokepoint (chapter 11) · Develops the API gateway’s security role.
- The Architectural Footprint: Where does this code live? (chapter 7) · An API endpoint as an entry point for synchronous work.
Concepts explained in this chapter
- contractAn API contract specifies the operations, data, and behavioral expectations governing communication between an API and its clients.
- clientA software component that initiates communication with a server to request resources or operations.
- serverA server is a software component that receives client requests, performs the requested processing, and returns responses.
- GraphQLGraphQL is an API query language and execution system that lets clients request structured data through a typed schema.
- client-server architectureA distributed architecture that separates clients that initiate requests from servers that provide resources or processing.
- stateless systemAn architectural approach in which application servers avoid retaining state locally between requests, typically storing necessary state elsewhere.
- RESTRepresentational State Transfer is an architectural style for networked applications based on resources, a uniform interface, and stateless interactions.
- synchronous callA synchronous operation blocks the initiating participant until the requested processing completes and a result is available.
- endpointA public endpoint is an externally reachable interface through which clients can send requests to a system or service.
- cacheabilityCacheability is the property that a response can be stored and reused for equivalent subsequent requests according to explicit freshness and validity rules.
- idempotency keyA request identifier that lets a payment processor recognize repeated submissions as the same transaction rather than separate transactions.
- asynchronous flowAsynchronous flow is a processing model in which work continues independently after the initiating interaction has completed.
- payloadA payload is the data carried in a request or response, apart from the communication’s control information.
- rest apiA REST API is a web API designed around resources and the constraints of Representational State Transfer.
- blocking chainA blocking chain is a sequence of dependent operations in which delay or failure in one operation prevents subsequent operations from proceeding.
- idempotencyIdempotency is the property of an operation whose repeated application has the same effect as applying it once.
- backend-for-frontend patternA design pattern that provides a dedicated API tailored to a specific user interface or client.
- resourceA resource is a web-accessible entity identified by a uniform resource identifier and manipulated through standardized operations.
- controllerA controller is an application component that receives requests and coordinates processing between the user interface and application logic.
- versioningVersion control is the systematic management of changing files and their history so changes can be reviewed, reproduced, and restored.
- HTTP GETAn HTTP method that requests a representation of a resource without requesting a state change.
- HTTP PUT methodPUT is an HTTP method for creating or replacing the representation of a resource at a specified target URI.
- N + 1 query problemA database performance problem in which one query retrieves a collection and an additional query retrieves related data for each item.
- eager loadingEager loading is a data-access technique that retrieves an entity and its required related data in an intentionally combined operation.
- object-relational mapperAn object-relational mapper is a technique or software layer that represents relational database data as programming-language objects and translates operations between the two models.
- abstractionAn abstraction is an interface or simplified representation that exposes relevant behavior while hiding implementation details.
- temporal dependencyA dependency in which one software component must be available or synchronized at a particular time for another component to complete an operation.
- horizontal scalingIncreasing capacity by adding instances of a system component across multiple servers or processes.
- HTTP methodA standardized token specifying the action requested on an HTTP resource, such as GET, POST, or DELETE.
- business logicBusiness logic is the application code that implements domain-specific rules and coordinates the system's behavior.
- SQLSQL is a standardized language for defining, querying, and manipulating data in relational database systems.
- databaseA database is a software system that stores, organizes, and retrieves persistent data.
- database indexAn auxiliary database data structure that accelerates retrieval by organizing references to rows according to selected values.
- execution planAn execution plan is the database engine's strategy for executing a query, including the operations and access methods it will perform.
- joinA relational query operation that combines rows from tables according to a specified relationship or matching condition.
- asynchronous programmingAn execution model in which work is initiated without requiring the caller to wait for its completion.
- availabilityThe duration or proportion of time a system remains operational.
- couplingCoupling is the degree of dependency between software components, with tight coupling requiring extensive knowledge of another component's operations or internal structure.
- distributed monolithA distributed monolith is a system whose deployable units are separated across processes or machines but remain tightly coupled through shared data or synchronous call chains.
- latencyLatency is the elapsed time between a request or input and the corresponding response or observable result.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
