API Realization: REST Resources & Constraints, API Management, GraphQL Schemas
"Define a protocol that gives access to your subsystem as a set of services. Open the protocol so that all who need to integrate with you can use it." — Eric Evans, Domain-Driven Design Reference (2015), Open Host Service
Summary: A bounded context becomes usable by others when its model is turned into a published API: an Open Host Service whose resources, commands and error shapes form a Published Language that is smaller and steadier than the internal model. REST and GraphQL are two ways to realise the same language; neither is the language itself. Focus: what to expose and what to keep private, resources versus aggregates and tables, task-based endpoints, HTTP semantics as constraints (methods, idempotency, status codes, ETag, If-Match, RFC 9457), surfacing eventual consistency with 202 Accepted, pagination, versioning, contract-first OpenAPI, API management, GraphQL schema design (input types, payloads, connections, dataloader, federation), security at the edge, and contract tests, with the Sales context in Go and Laravel. Learning goal: Take the Sales context's Order aggregate and publish it twice, as a REST API and as a GraphQL schema, with task-based endpoints, Problem Details, conditional requests, a visible asynchronous cancellation, batched product lookups and tests, and say for each design choice which part of the model it protects.
This chapter belongs to group DD 03 (Data & APIs in Microservices). It assumes Bounded Context (where the line is), Aggregates & Factories (what lives behind it) and Context Maps & Integration Patterns (which relationship the API serves). It owns one question: how does a context turn its model into an API that others can depend on? The neighbours own the rest. The generic craft of HTTP API design is in REST API Design, GraphQL, gRPC & Protobuf and API Versioning; gateways, BFFs and meshes are in API Gateway, BFF & Service Mesh; how services talk is in Service Communication; the services behind the endpoints are in Domain, Application & Infrastructure Services; stored state is in Repositories; events are in Domain Events vs Integration Events and Outbox Pattern; keyset pagination is in Pagination; version columns are in Optimistic vs Pessimistic Locking.
Page map
| If you are looking for | Go to |
|---|---|
| The whole chapter in four tables | Everything in one minute |
| Why an API is more than a serialised model | Why it exists |
| Fielding, Evans, Richardson, RFC 9457, GraphQL | Where it comes from |
| What the API is in DDD terms | OHS and Published Language |
| A resource is not an aggregate and not a table | Resource vs aggregate |
POST /orders/{id}/placement vs PATCH status | Task-based vs CRUD |
| Methods, safe, idempotent, status codes | HTTP semantics |
ETag, If-Match, 304, 412, 428 | Conditional requests |
| Error bodies | Problem Details |
202 + Location + status resource | Eventual consistency in the API |
| Links, Richardson levels, JSON:API | Hypermedia |
| Cursors, filters, sort | Pagination, filtering, sorting |
Additive change, Sunset, Deprecation | Versioning the published language |
| OpenAPI, Spectral, generated clients | Contract-first |
| Keys, quotas, developer portal | API management |
| SDL, types from the model | GraphQL schema |
Mutations, input types, payloads, userErrors | GraphQL commands and errors |
| Relay connections | GraphQL pagination |
| N+1, dataloader, Lighthouse, gqlgen | N+1 and dataloader |
| Federation, BFF | Federation and BFF |
| gRPC, webhooks, AsyncAPI | Other realisations |
| authn, scopes, tenant isolation | Security at the edge |
| Contract tests, Spectral, CDC | Testing |
| Go and Laravel code | Go, Laravel |
| Per context and per service | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Open Host Service (OHS) | One open protocol for everybody who integrates with the context | Sales' HTTP API | A custom translator per consumer |
| Published Language (PL) | The documented model of that protocol, separate from the internal model | Order JSON, the OpenAPI file | The internal model leaks and freezes |
| Resource | A named thing you can address and fetch a representation of | /orders/o1 | Endpoints named after functions and tables |
| Representation | The bytes sent for a resource at a moment | the order JSON with ETag | Clients depend on storage columns |
| Task-based endpoint | A command named in the language of the business | POST /orders/o1/placement | PATCH status lets any client skip rules |
| Idempotent | Repeating the request has the same effect as sending it once | PUT, DELETE, POST with Idempotency-Key | A retry charges twice |
| Conditional request | A request that only succeeds if the client's copy is current | If-Match: W/"2" | Lost updates over HTTP |
| Problem Details | One machine-readable error shape | application/problem+json | Every endpoint invents its own errors |
| Eventual consistency, surfaced | The API says "accepted, not done" and gives a place to watch | 202 + Location | Clients believe a pending change is final |
| Keyset cursor | An opaque marker for the next page | nextCursor | Offset pages skip or repeat rows |
| Contract-first | The OpenAPI/SDL file is written and reviewed before the code | sales.openapi.yaml | The contract is whatever the code happens to do |
| API gateway | The front door: auth, quotas, routing, analytics | Kong, Apigee | Every service re-implements cross-cutting rules |
| GraphQL schema | The typed published language for GraphQL clients | type Order { ... } | Over- and under-fetching, or a schema that mirrors tables |
| Dataloader | Collects keys during one level of execution and fetches them in one call | Product lookups per line | N+1 calls to Catalog |
Two realisations of one language.
| Question | REST | GraphQL |
|---|---|---|
| Unit of the contract | A resource and a method | A field in the type graph |
| Who shapes the response | The server (representations) | The client (selection set) |
| A command looks like | POST /orders/{id}/placement | mutation { placeOrder(input: ...) } |
| Business failure | 409 / 422 with application/problem+json | userErrors in the payload, HTTP 200 |
| Caching | HTTP caches, ETag, 304 | Client cache by id, persisted queries, CDN is harder |
| Paging | limit + cursor | first + after connection |
| Best at | Few, stable consumers; commands; cacheable reads | Many clients, varied views, aggregation across contexts |
| Biggest trap | CRUD over tables | N+1 and unbounded queries |
The HTTP contract in one table (every row is unpacked in HTTP semantics and Mechanics).
| Situation | Status | Header or body to add |
|---|---|---|
| Created a draft | 201 Created | Location, ETag |
| Read, unchanged | 304 Not Modified | ETag |
| Command accepted, work continues | 202 Accepted | Location, Retry-After |
| Business rule says no, state conflict | 409 Conflict | Problem type |
| Input is well-formed but invalid | 422 Unprocessable Content | errors[].pointer |
| Stale copy | 412 Precondition Failed | Problem type |
| Conditional header missing | 428 Precondition Required | Problem type |
| Too many requests | 429 Too Many Requests | Retry-After |
Why it exists
A bounded context is private by design. Inside it the model is allowed to be rich, to change weekly and to use words nobody outside understands. Outside, other teams and other companies still need to ask questions and give commands. The API is the place where those two worlds meet, and the central design decision is how much of the inside to show.
| Show the model directly | Publish a language |
|---|---|
| Fast to build: serialise the entity | Needs a mapping layer and a contract file |
| Every refactor breaks a consumer | Refactors stay behind the mapping |
| Table and class names become public words | Public words come from the ubiquitous language |
Rules can be bypassed (PATCH status) | Rules sit behind named commands |
| One consumer's need shapes everyone's API | The language serves the whole set of consumers |
An analogy we reuse on this page: a restaurant. The kitchen (the context) has stations, recipes and stock rules. Guests never see them. They see a menu (the published language), a waiter (the API) and a few rules of the house ("the kitchen closes at ten"). A menu that lists the fridge shelves is a leaked model. A menu that says "ask the waiter for anything" is an unusable one. REST is a printed menu with fixed dishes; GraphQL is a build-your-own bowl with a fixed list of ingredients; the kitchen is the same.
Three common misunderstandings, up front
- "REST means CRUD over tables." Fielding's resource is "any information that can be named", not a row. A
placementor acancellation-requestis a perfectly good resource (see Resource vs aggregate). - "GraphQL replaces REST." GraphQL is a different realisation of the same published language, better at many-client reads and weaker at caching and at command-heavy surfaces (see Choosing).
- "The API is an implementation detail of the service." It is the most expensive thing to change in the whole system, because other people's code depends on it. That is why it is designed, reviewed and versioned like a product.
Where it comes from
| Year | Source | What it gave this chapter |
|---|---|---|
| 2000 | Roy Fielding, dissertation chapter 5, Representational State Transfer | The four interface constraints, resources and representations |
| 2003 | Eric Evans, Domain-Driven Design | Open Host Service, Published Language (summarised in the free 2015 DDD Reference) |
| 2010 | Martin Fowler, Richardson Maturity Model (18 March 2010) | Levels 0 to 3: resources, verbs, hypermedia |
| 2013 | Vaughn Vernon, Implementing DDD, chapter 4 | Architecture of a bounded context, RESTful integration of contexts (book, not fetched; nothing quoted) |
| 2012 / 2015 | GraphQL "originally created at Facebook in 2012"; "The development of this open standard started in 2015" (spec intro; October 2021 edition used here) | Typed, client-shaped queries |
| 2021 | OpenAPI Specification 3.1.0 (15 February 2021) | JSON Schema 2020-12 alignment, the contract format |
| 2023 | RFC 9457 Problem Details for HTTP APIs (July 2023; obsoletes RFC 7807) | One error format |
| ongoing | Zalando, Microsoft and Google API guidelines | Practical conventions: API first, long-running operations, custom methods |
Fielding names the constraint this chapter keeps returning to: "REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state." He also pays the bill honestly: "The trade-off, though, is that a uniform interface degrades efficiency, since information is transferred in a standardized form rather than one which is specific to an application's needs." GraphQL exists in large part to buy back that efficiency, and we will see what it costs.
Evans adds the DDD half. Of the Published Language: "If one is used as a data interchange language, it essentially becomes frozen and cannot respond to new development needs." That sentence is the reason this chapter exists: expose the domain model directly and you can never refactor it again.
Fowler's summary of the maturity model is deliberately modest; of level 2 he writes "Level 2 moves away from this, using the HTTP verbs as closely as possible to how they are used in HTTP itself." Of level 3 he notes it brings the "ugly acronym" HATEOAS. Level 3 is a tool, not a badge (see Hypermedia).
Vernon's chapter 4 is cited as background only; the text was not fetched and no sentence of it is quoted here.
What it is really about
An API is the runtime face of two context-map patterns (full definitions in Context Maps & Integration Patterns):
- Open Host Service: Sales offers one protocol, "a set of services", to every downstream, instead of a translator per consumer. Evans says that places the provider upstream, and "typically some of them will be conformist and some will build anticorruption layers".
- Published Language: the format of that protocol is documented and not the internal model. The OpenAPI file, the GraphQL SDL, the JSON Schemas of events, together, are the published language.
Three consequences drive every later section.
- The API is a model of its own. It has its own nouns, its own states and its own stability promises. It is derived from the domain model but is smaller and steadier; see Resource vs aggregate.
- The API is the aggregate's only door for outsiders. Every command goes through an application service and then the aggregate's methods (see Domain, Application & Infrastructure Services). An API that writes straight to tables bypasses invariants.
- There is more than one door. REST, GraphQL, gRPC, events and webhooks are realisations of one language. Naming, error codes and versions should stay consistent across them. In this chapter's code both REST and GraphQL call the same
Service.
| Layer | Owns | Changes when |
|---|---|---|
Domain model (Order) | Invariants, state machine | The business rule changes |
Application service (Service) | Use cases, transactions, ports | A use case changes |
| Published language (OpenAPI + SDL) | Resources, commands, errors, scopes | A consumer-visible promise changes (rare, versioned) |
| Realisation (handlers, resolvers) | HTTP and GraphQL mechanics | The transport changes |
| Gateway | Keys, quotas, routing, analytics | Policy changes |
The concept catalogue
Open Host Service and Published Language in practice Must-know
In plain words: Decide what the context promises the outside world, write it down in one document, and keep everything else private.
Common misunderstanding: "If a field exists on the aggregate, a consumer may want it, so expose it." Every exposed field is a promise. Expose what consumers need to know and can rely on; keep the rest (version counters, audit columns, internal pricing rules) inside.
Definition: The published language of a context is the set of resources, commands, events, error types and scopes that its API documents. A field belongs in it only if the ubiquitous language names it and the team is ready to keep it for the life of the version.
Decision per field of the Order aggregate
1 customer id -> published (consumers filter by it)
2 status -> published as a read-only state; changed only by commands
3 lines -> published as sub-resource and embedded summary
4 total -> published, derived on read, never accepted as input
5 version -> published as ETag, not as a field
6 internal discount rule, audit columns, row id -> privateReal scenario: Billing needs "how much is this order and who is it for". It does not need lines, discount codes or the picking status. Fulfilment needs lines and the shipping address but not the payment method. Web needs everything for a screen. One language, three needs: that is the argument for either narrow resources plus embedding rules (REST) or a client-chosen selection (GraphQL).
What provides it:
| Mechanism | Role | Where in this chapter |
|---|---|---|
| DTO / API Resource | The mapping layer, one class per published shape | OrderDTO in Go, OrderResource in Laravel |
| OpenAPI / SDL | The written contract | Contract-first |
| Errors catalogue | Stable problem types and codes | Problem Details |
| Scopes | Who may do what | Security at the edge |
| Versioning policy | What may change without a new version | Versioning |
Resource vs aggregate vs table Must-know
In plain words: A resource is a thing a client can name and ask about. An aggregate is a consistency boundary in your code. A table is how you store it. These three are related and different.
Common misunderstanding: "One table, one aggregate, one endpoint." The mapping is many to many: one aggregate can be several resources, several aggregates can make one resource, and some resources (a cancellation request, a report, a search) have no aggregate at all.
Definition: Fielding: "Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on." Google's AIP-121 adds the working rule: "The fundamental building blocks of an API are individually-named resources (nouns) and the relationships and hierarchy that exist between them."
Mapping for the Sales running example
Aggregate / record Resource (URI) Why a resource
Order (root) /orders/{id} the thing consumers name
OrderLine (inside) /orders/{id}/lines (sub-resource) add a line; no URI per line needed yet
Order.Place() (a command) /orders/{id}/placement a noun for an event-like command
(no aggregate: workflow) /cancellation-requests/{id} a status the client can poll
Order list (a query) /orders?status=placed&limit=20 a collection with filtersReal scenarios: (1) A Customer aggregate is exposed as /customers/{id} and /customers/{id}/addresses, because addresses are named separately by clients. (2) A reporting query "orders per day" is a resource /reports/daily-orders backed by a read model, not by the Order aggregate (see Data Patterns). (3) A batch import is a resource /imports/{id} with a state, not a long POST.
What goes in the representation: only data from inside the aggregate boundary and from the published model. Data from other contexts (a product name from Catalog) is either referenced by id with a link, or embedded by an explicit decision with a freshness note.
Fix / how to use it: one DTO per published shape. Never json.Marshal(order) or return $order from a controller.
package rest
import (
"fmt"
"strconv"
"strings"
"time"
"academy/api-realization-rest-graphql/sales"
)
// MoneyDTO is the published money shape: minor units plus currency.
type MoneyDTO struct {
AmountMinor int64 `json:"amountMinor"`
Currency string `json:"currency"`
}
// LineDTO is one line of the order representation.
type LineDTO struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
UnitPrice MoneyDTO `json:"unitPrice"`
}
// Link is a hypermedia control: where to go and which method to use.
type Link struct {
Href string `json:"href"`
Method string `json:"method,omitempty"`
}
// OrderDTO is the representation of the Order resource. It is shaped by the
// published language, not by the aggregate's fields.
type OrderDTO struct {
ID string `json:"id"`
CustomerID string `json:"customerId"`
Status string `json:"status"`
Lines []LineDTO `json:"lines"`
Total MoneyDTO `json:"total"`
PlacedAt *time.Time `json:"placedAt,omitempty"`
Links map[string]Link `json:"_links"`
}
// CancellationDTO is the status resource for a cancellation request.
type CancellationDTO struct {
ID string `json:"id"`
OrderID string `json:"orderId"`
State string `json:"state"`
Reason string `json:"reason"`
Detail string `json:"detail,omitempty"`
Links map[string]Link `json:"_links"`
}
// OrderPage is a keyset-paginated collection.
type OrderPage struct {
Items []OrderDTO `json:"items"`
NextCursor string `json:"nextCursor,omitempty"`
}
func toOrderDTO(o *sales.Order) OrderDTO {
id := string(o.ID())
d := OrderDTO{
ID: id, CustomerID: string(o.Customer()), Status: string(o.Status()),
Lines: []LineDTO{}, Total: MoneyDTO{o.Total().Minor, o.Total().Currency},
Links: map[string]Link{"self": {Href: "/orders/" + id}},
}
for _, l := range o.Lines() {
d.Lines = append(d.Lines, LineDTO{SKU: string(l.SKU), Quantity: l.Quantity,
UnitPrice: MoneyDTO{l.UnitPriceMinor, o.Currency()}})
}
if !o.PlacedAt().IsZero() {
t := o.PlacedAt()
d.PlacedAt = &t
}
// Links advertise only the transitions the state machine allows now.
switch o.Status() {
case sales.Draft:
d.Links["add-line"] = Link{Href: "/orders/" + id + "/lines", Method: "POST"}
d.Links["placement"] = Link{Href: "/orders/" + id + "/placement", Method: "POST"}
case sales.Placed:
d.Links["cancellation-requests"] = Link{Href: "/orders/" + id + "/cancellation-requests", Method: "POST"}
}
return d
}
func toCancellationDTO(r sales.CancellationRequest) CancellationDTO {
d := CancellationDTO{ID: r.ID, OrderID: string(r.OrderID), State: string(r.State), Reason: r.Reason, Detail: r.Detail,
Links: map[string]Link{"self": {Href: "/cancellation-requests/" + r.ID}}}
if r.State != sales.CancellationPending {
d.Links["order"] = Link{Href: "/orders/" + string(r.OrderID)}
}
return d
}
// etag is a weak validator derived from the aggregate version.
func etag(o *sales.Order) string { return fmt.Sprintf(`W/"%d"`, o.Version()) }
// parseETag turns W/"3" (or "3") into 3; ok is false when the header is malformed.
func parseETag(h string) (int, bool) {
h = strings.TrimPrefix(strings.TrimSpace(h), "W/")
n, err := strconv.Atoi(strings.Trim(h, `"`))
return n, err == nil && n > 0
}Task-based vs CRUD: commands as intents Must-know
In plain words: Name the action the way the business says it ("place the order", "request a cancellation") instead of "update the status field".
Common misunderstanding: "PATCH /orders/{id} with {"status":"placed"} is more RESTful." It is more generic, and generic is the problem: any client can now try any transition, the rule lives in every client's head, and the audit trail says "status changed" instead of "customer placed the order".
Definition: A task-based API exposes commands as intents. Google's AIP-136 gives the rationale: custom methods "provide a means for an API's vocabulary to adhere to user intent", and they "should only be used for functionality that can not be easily expressed via standard methods". In HTTP that usually means a POST to a noun that names the result or the process: /placement, /cancellation-requests, /refunds.
CRUD style (state is a free-for-all) Task-based style (state is a protocol)
1 PATCH /orders/o1 {"status":"placed"} 1 POST /orders/o1/lines {sku, qty}
2 PATCH /orders/o1 {"status":"draft"} <- 2 POST /orders/o1/placement If-Match: W/"2"
3 PATCH /orders/o1 {"total": 1} 3 POST /orders/o1/cancellation-requests
-- invariants live in every client -- invariants live in the aggregate| Aspect | CRUD over fields | Task-based |
|---|---|---|
| Rules | In clients or in a hidden validator | In the aggregate behind a named method |
| Audit | "status changed" | "order placed by customer c1" |
| Evolution | New states break every client | New command = new URI, old ones stay |
| Authorisation | Per field, awkward | Per command and scope: orders:write |
| Discoverability | Read the docs | Links advertise allowed commands (see Hypermedia) |
| Fit | Admin tools, settings, simple lookup data | Core subdomains with real rules |
Real scenarios: payment capture, order placement, shipment dispatch, role assignment, account closure. In a supporting subdomain (Catalog attributes, Identity profile) plain CRUD is fine and cheaper; the Domains & Subdomains classification tells you where task-based endpoints pay.
Fix: in the code, one handler per command, calling one application service method. The handler contains no rules.
HTTP semantics as constraints Must-know
In plain words: Methods and status codes are not decoration; proxies, browsers, retries and gateways act on them. Use them as they were defined.
Common misunderstanding: "POST is for anything that changes data and 200 OK for anything that worked." Retries, caches and clients treat methods differently; a wrong method silently disables safety nets.
Definition (RFC 9110): "A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent." POST is neither safe nor idempotent by default.
| Method | Safe | Idempotent | Cacheable | Typical use in this API |
|---|---|---|---|---|
GET | yes | yes | yes | read an order, list, poll status |
HEAD | yes | yes | yes | existence and ETag check |
PUT | no | yes | no | replace a whole representation (e.g. customer profile) |
DELETE | no | yes | no | remove a draft |
PATCH | no | not guaranteed | no | partial update of plain data, not state transitions |
POST | no | no | rarely | commands, creation; make it idempotent with a key |
Why idempotency matters: a retry after a timeout
1 client -> POST /orders/o1/cancellation-requests (Idempotency-Key: k1)
2 server stores request can_1, answers 202 ... response lost on the network
3 client times out, sends the same request again with Idempotency-Key: k1
4 server finds key k1 -> returns can_1 again (no second request, no second refund)Real scenario: a mobile client on a weak network retries POST /payments three times. Without a key, three charges. Stripe documents the same defence: "When creating or updating an object, use an idempotency key. Then, if a connection error occurs, you can safely repeat the request without risk of creating a second object or performing the update twice."
What provides it: Zalando's guidelines list Idempotency-Key as a MAY-consider header; Stripe makes it standard for all POSTs. Our code stores the key with the request (see Mechanics, and API Idempotency for the general treatment); the consumer side of the same idea is Idempotent Consumers & the Inbox Pattern.
Conditional requests: ETag, If-Match, 304, 412, 428 Must-know
In plain words: Hand the client a version tag with every read. For reads, "only send me the body if it changed". For commands, "only do this if my copy is still current".
Common misunderstanding: "Optimistic locking is a database feature, not an HTTP one." The version column in the aggregate is exactly what the ETag carries. HTTP gives the lost-update defence a standard name.
Definition: ETag is a validator for a representation. If-None-Match on GET makes a cheap revalidation (304 Not Modified). If-Match on a command makes it conditional; if the tag is stale the answer is 412 Precondition Failed. RFC 6585 adds 428 Precondition Required for servers that insist on it: "Its typical use is to avoid the "lost update" problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server".
T1 (clerk A) T2 (clerk B) server version
1 GET /orders/o1 -> ETag W/"2" GET /orders/o1 -> ETag W/"2" 2
2 POST .../lines (adds a mug) 2 -> 3
3 POST .../placement If-Match W/"2"
4 <- 412 Precondition Failed 3 (B re-reads, sees the mug)
5 GET -> W/"3"; POST ... If-Match W/"3" -> 200 3 -> 4| Header | Direction | Meaning | Our choice |
|---|---|---|---|
ETag: W/"3" | response | Weak validator = aggregate version | on every order representation |
If-None-Match | request on GET | Revalidate | 304 with no body |
If-Match | request on commands | Conditional command | optional on add-line, required on placement |
Cache-Control: private, max-age=0, must-revalidate | response | Force revalidation, never share | order reads contain personal data |
Fix / how to use it: return the tag from the repository's version; accept it in the application service as expected; map ErrVersionConflict to 412. In GraphQL there is no header: the same idea becomes an expectedVersion input field (see GraphQL commands).
Problem Details (RFC 9457) Must-know
In plain words: Every error has the same shape: a type URI, a short title, the HTTP status, and optional detail and extras.
Common misunderstanding: "The type is a page for humans, so any string will do." The type is the stable machine key. Clients branch on it; documentation can live behind it; the title and detail may change wording freely.
Definition: RFC 9457 "defines a "problem detail" to carry machine-readable details of errors in HTTP response content to avoid the need to define new error response formats for HTTP APIs." Media type application/problem+json. Members: type, title, status, detail, instance, plus extension members (we add errors[] with JSON Pointers).
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{ "type": "https://api.example.com/problems/validation-failed",
"title": "Your request is invalid", "status": 422,
"instance": "/orders",
"errors": [ {"pointer": "/customerId", "detail": "is required"},
{"pointer": "/currency", "detail": "must be a 3-letter ISO 4217 code"} ] }| Failure | Status | type suffix (published) | Source in the domain |
|---|---|---|---|
| Unknown id | 404 | not-found | ErrNotFound |
| Placed order edited | 409 | order-not-editable | ErrNotDraft |
| Place with no lines | 422 | order-empty | ErrEmptyOrder |
| Bad input | 422 | validation-failed | request validation |
Stale If-Match | 412 | stale-representation | ErrVersionConflict |
Missing If-Match | 428 | precondition-required | handler |
| Cancel a cancelled order | 409 | order-not-cancellable | ErrAlreadyCancelled |
| Anything else | 500 | about:blank | logged, never leaked |
Fix: one function maps domain errors to problems (fromError in Go, ProblemDetails::fromFailure in PHP). The internal error text is not forwarded unless it was written for clients.
// Package rest publishes the Sales context over HTTP. It owns the wire shapes
// (DTOs); it never serialises the aggregate itself.
package rest
import (
"encoding/json"
"errors"
"net/http"
"academy/api-realization-rest-graphql/sales"
)
const problemBase = "https://api.example.com/problems/"
// Problem is an RFC 9457 problem details object with two extension members.
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Errors []FieldError `json:"errors,omitempty"` // extension: validation failures
}
// FieldError points at one invalid input member (JSON Pointer).
type FieldError struct {
Pointer string `json:"pointer"`
Detail string `json:"detail"`
}
func writeProblem(w http.ResponseWriter, r *http.Request, p Problem) {
p.Instance = r.URL.Path
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(p.Status)
_ = json.NewEncoder(w).Encode(p)
}
// fromError maps a domain or application error to a stable problem type.
// The mapping is the single place where internal errors become public codes.
func fromError(err error) Problem {
switch {
case errors.Is(err, sales.ErrNotFound):
return Problem{Type: problemBase + "not-found", Title: "Resource not found", Status: http.StatusNotFound}
case errors.Is(err, sales.ErrVersionConflict):
return Problem{Type: problemBase + "stale-representation", Title: "The order changed since you read it", Status: http.StatusPreconditionFailed,
Detail: "Re-read the order and retry with the new ETag."}
case errors.Is(err, sales.ErrNotDraft):
return Problem{Type: problemBase + "order-not-editable", Title: "Order is not editable", Status: http.StatusConflict,
Detail: "Only a draft order can be changed."}
case errors.Is(err, sales.ErrEmptyOrder):
return Problem{Type: problemBase + "order-empty", Title: "Order has no lines", Status: http.StatusUnprocessableEntity}
case errors.Is(err, sales.ErrBadQuantity), errors.Is(err, sales.ErrUnknownProduct):
return Problem{Type: problemBase + "validation-failed", Title: "Your request is invalid", Status: http.StatusUnprocessableEntity,
Detail: err.Error()}
case errors.Is(err, sales.ErrAlreadyCancelled), errors.Is(err, sales.ErrNotCancellable):
return Problem{Type: problemBase + "order-not-cancellable", Title: "Order cannot be cancelled", Status: http.StatusConflict,
Detail: err.Error()}
}
// Never leak internals: log err on the server, return a generic problem.
return Problem{Type: "about:blank", Title: "Internal Server Error", Status: http.StatusInternalServerError}
}Surfacing eventual consistency: 202, Location and a status resource Must-know
In plain words: If the work will finish later, say so: "accepted, here is where to watch".
Common misunderstanding: "Return 200 with the new state; the client does not need to know it is asynchronous." The client then shows "cancelled" for an order Fulfilment has not released yet, and the user is told one thing while the warehouse does another.
Definition (RFC 9110): "The 202 (Accepted) status code indicates that the request has been accepted for processing, but the processing has not been completed. ... The representation sent with this response ought to describe the request's current status and point to (or embed) a status monitor that can provide the user with an estimate of when the request will be fulfilled." Microsoft's guidelines say the same for long-running operations: "DO return status code 202-Accepted ... when a PUT, POST, or DELETE method completes asynchronously."
Timeline: cancelling a placed order (the saga is in /messaging/saga-pattern)
1 client POST /orders/o1/cancellation-requests {"reason":"late"} Idempotency-Key: k1
2 api INSERT cancellation_request(can_1, pending) -- one local transaction
3 api -> 202 Accepted Location: /cancellation-requests/can_1 Retry-After: 1
4 worker Fulfilment.ReleaseStock(o1) -- may take seconds, may fail
5 worker order.Cancel(); request.state = completed (or rejected + detail)
6 client GET /cancellation-requests/can_1 -> pending ... then completed + link to /orders/o1| Way to tell the client | Good for | Cost |
|---|---|---|
| Poll the status resource | Simple clients, short waits | Wasted requests; honour Retry-After |
| Webhook to a client URL | Server-to-server, partners | Signing, retries, a delivery log (see Webhooks) |
| GraphQL subscription / SSE | Live UIs | A long-lived connection to operate |
| Synchronous wait up to N seconds, else 202 | Mostly-fast operations | Two code paths |
Real scenarios: refunds, KYC checks, report generation, video encoding, bank transfers, cancelling something already picked.
Fix: model the request as a record (CancellationRequest): it gives the client something to GET, gives the worker something to make idempotent, and gives support something to read.
Hypermedia and the Richardson levels Important
In plain words: The server's reply carries links to what you can do next, so the client follows links instead of building URLs.
Common misunderstanding: "An API is not REST unless it is level 3." Fielding's constraint list includes hypermedia, true; but most business APIs pay for level 2 and add links only where they help (state-dependent actions, pagination, related resources).
| Level (Fowler) | Idea | Example here |
|---|---|---|
| 0 | One endpoint, tunnelling (RPC over HTTP) | POST /api with an operation name |
| 1 | Resources | /orders/o1 |
| 2 | HTTP verbs and status codes | POST creates 201, conflict 409, GET cacheable |
| 3 | Hypermedia controls | _links.placement only when the order is a draft |
When links pay: (a) the allowed next commands depend on state, so the server tells the client (placement appears for a draft, cancellation-requests for a placed order); (b) pagination (next); (c) public APIs with many unknown clients; (d) API evolution, because clients that follow href survive URI moves.
When they do not: a private API with one generated client and a stable URL scheme; a fixed workflow already encoded in the SDK.
| Format | What it standardises | Use when |
|---|---|---|
Plain JSON + _links (this chapter) | Nothing, a local convention | Small, explicit needs |
| HAL | _links, _embedded | Link-heavy REST with tooling |
| JSON:API | Resource objects, relationships, include, sparse fieldsets, pagination links | You want a ready convention and clients such as Ember Data |
| Siren, Hydra | Actions and forms in the response | Fully hypermedia clients |
JSON:API is a specification (v1.1 at the time of writing) with application/vnd.api+json; Laravel 13's API resources docs also describe JSON:API resources, so the convention is available without extra packages.
Pagination, filtering and sorting Important
In plain words: Never return "all orders". Return a page and a marker for the next one.
Common misunderstanding: "?page=7&per_page=20 is enough." Offsets skip and repeat rows when data changes between requests, and they get slower as the offset grows (details in Pagination).
| Convention | Request | Response | Notes |
|---|---|---|---|
| Keyset cursor (ours) | ?limit=20&cursor=Mg | items, nextCursor | Opaque, stable under inserts |
Link header | same | Link: <...>; rel="next" | RFC 8288; good for generic clients |
| Offset | ?offset=40&limit=20 | items, total | Only for small, rarely-changing lists |
| GraphQL connection | first, after | edges { cursor node }, pageInfo | See GraphQL pagination |
| Parameter | Rule |
|---|---|
| Filters | Named after the ubiquitous language: status=placed, customerId=...; unknown filters are 400, not ignored |
| Sort | sort=-placedAt,id with a documented whitelist and a unique tiebreaker so cursors are stable |
| Limits | A default and a hard maximum (limit 20, max 100) in the contract |
| Cursor | Opaque to clients (base64 of the keyset); format may change without a version |
| Tenant | Applied by the server from the token, never from the query string |
-- The query behind GET /orders?status=placed&limit=20&cursor=...
SELECT id, customer_id, status, placed_at, seq
FROM orders
WHERE customer_id = $1 -- from the token, not from the client
AND status = 'placed'
AND seq > $2 -- decoded cursor
ORDER BY seq -- unique, indexed (customer_id, seq)
LIMIT 21; -- one extra row tells us whether a next page existsVersioning the published language Important
In plain words: Change the API in a way that old clients keep working; when you cannot, run old and new side by side and announce the end date.
Common misunderstanding: "Put /v2/ in the URL and you are done." A version in the URL is a label; the hard part is deciding which changes are additive and which break consumers, and running both for long enough.
| Change | Breaking? | Rule |
|---|---|---|
| New optional response field | no | Clients must ignore unknown fields (tolerant reader) |
| New optional request field | no | Default to old behaviour |
| New endpoint or command | no | Old ones stay |
| New enum value in a response | yes for strict clients | Document that enums are open; or add a new field |
| Remove or rename a field | yes | New version, or add the new name first and keep the old one |
| Tighten validation | yes | New version |
| Change meaning of a field | yes | Never reuse a name for a new meaning |
| New required request field | yes | New version |
| Style | Example | Pro | Con |
|---|---|---|---|
| URI | /v2/orders | Visible, easy to route at the gateway | Version is part of every link |
| Header | Sales-Version: 2026-11-01 | Clean URIs, date versions | Hidden; harder to try in a browser |
| Media type | Accept: application/vnd.sales.order.v2+json | Per-representation version | Tooling and caching complexity |
| None (GraphQL) | additive changes plus @deprecated | One graph | Needs discipline and usage analytics |
The deprecation lifecycle has two headers: Deprecation (the API is no longer recommended) and RFC 8594's Sunset, which "indicates that a URI is likely to become unresponsive at a specified point in the future". The RFC itself separates the two stages: deprecation first, decommissioning later. Full treatment in API Versioning; the DDD angle is that the published language is what is versioned, not the aggregate.
Timeline: retiring Order.v1 "customerId as int"
1 month 0 publish v2 (customerId: string); v1 still served; add Deprecation header to v1
2 month 1 gateway analytics: 12 consumers still on v1; email each owner (keys identify them)
3 month 4 add Sunset: Thu, 01 Jul 2027 00:00:00 GMT to every v1 response
4 month 7 v1 returns 410 Gone with a problem pointing to the migration guideContract-first with OpenAPI Must-know
In plain words: Write the API description first, review it with consumers, then build the code to match it, and have a machine check the match.
Common misunderstanding: "The OpenAPI file can be generated from the code at the end." Generated docs describe what the code does, bugs included. A contract written first describes what the API promises; the code is then held to it.
Definition: The OpenAPI Specification 3.1.0 (15 February 2021) describes an HTTP API in YAML or JSON: paths, operations, parameters, request bodies, responses, security schemes and reusable components, with JSON Schema for the data. Zalando's rule is the one to copy: "Microservices development begins with API specification outside the code and ideally involves ample peer-review feedback to achieve high-quality APIs."
| Step | What happens | Tool |
|---|---|---|
| 1 Design | Write sales.openapi.yaml from the published language | An editor, Stoplight, Swagger Editor |
| 2 Lint | Style and policy rules fail the build | Spectral with a team ruleset |
| 3 Review | Consumers and the platform team comment on the diff | Pull request |
| 4 Break check | Compare to the released contract; fail on breaking changes | oasdiff, openapi-diff |
| 5 Generate | Clients and server stubs/types from the file | openapi-generator, oapi-codegen (Go), Laravel packages |
| 6 Verify | Run the real server against the contract | Schemathesis, Dredd, Prism (mock) |
| 7 Publish | Docs on the developer portal | Redoc, Swagger UI |
# The core of the contract for the cancellation command (full file below).
/orders/{orderId}/cancellation-requests:
post:
operationId: requestOrderCancellation
security: [{ oauth2: ["orders:write"] }]
parameters:
- { name: Idempotency-Key, in: header, schema: { type: string, maxLength: 64 } }
responses:
'202':
description: Accepted; poll the Location resource
headers: { Location: { schema: { type: string } }, Retry-After: { schema: { type: integer } } }
'409': { $ref: '#/components/responses/Problem' }openapi: 3.1.0
info:
title: Sales API
version: 1.4.0
summary: The published language of the Sales context, over HTTP.
description: >
Open Host Service of the Sales bounded context. Resources follow the
ubiquitous language (order, line, placement, cancellation request).
contact: { name: Sales team, email: sales-api@example.com }
servers:
- url: https://api.example.com
security:
- oauth2: ["orders:read"]
tags:
- name: Orders
- name: Cancellation
paths:
/orders:
post:
operationId: createDraftOrder
tags: [Orders]
summary: Start a draft order
security: [{ oauth2: ["orders:write"] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/CreateOrder' }
responses:
'201':
description: Draft created
headers:
Location: { schema: { type: string, format: uri-reference } }
ETag: { $ref: '#/components/headers/ETag' }
content:
application/json:
schema: { $ref: '#/components/schemas/Order' }
'422': { $ref: '#/components/responses/Problem' }
get:
operationId: listOrders
tags: [Orders]
summary: List my orders (keyset pagination)
parameters:
- { name: status, in: query, schema: { $ref: '#/components/schemas/OrderStatus' } }
- { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
- { name: cursor, in: query, description: "Opaque; copy nextCursor from the previous page.", schema: { type: string } }
responses:
'200':
description: One page of orders
content:
application/json:
schema: { $ref: '#/components/schemas/OrderPage' }
/orders/{orderId}:
parameters:
- { name: orderId, in: path, required: true, schema: { type: string } }
get:
operationId: getOrder
tags: [Orders]
summary: Read one order
parameters:
- { name: If-None-Match, in: header, schema: { type: string } }
responses:
'200':
description: The order
headers:
ETag: { $ref: '#/components/headers/ETag' }
content:
application/json:
schema: { $ref: '#/components/schemas/Order' }
'304': { description: Not modified }
'404': { $ref: '#/components/responses/Problem' }
/orders/{orderId}/lines:
parameters:
- { name: orderId, in: path, required: true, schema: { type: string } }
post:
operationId: addOrderLine
tags: [Orders]
summary: Add a line (price is taken from Catalog)
security: [{ oauth2: ["orders:write"] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/AddLine' }
responses:
'201':
description: Line added; the updated order is returned
content:
application/json:
schema: { $ref: '#/components/schemas/Order' }
'409': { $ref: '#/components/responses/Problem' }
'422': { $ref: '#/components/responses/Problem' }
/orders/{orderId}/placement:
parameters:
- { name: orderId, in: path, required: true, schema: { type: string } }
post:
operationId: placeOrder
tags: [Orders]
summary: Place the order (a command, named as the business names it)
security: [{ oauth2: ["orders:write"] }]
parameters:
- { name: If-Match, in: header, required: true, schema: { type: string }, example: 'W/"2"' }
responses:
'200':
description: Placed
content:
application/json:
schema: { $ref: '#/components/schemas/Order' }
'412': { $ref: '#/components/responses/Problem' }
'422': { $ref: '#/components/responses/Problem' }
'428': { $ref: '#/components/responses/Problem' }
/orders/{orderId}/cancellation-requests:
parameters:
- { name: orderId, in: path, required: true, schema: { type: string } }
post:
operationId: requestOrderCancellation
tags: [Cancellation]
summary: Ask to cancel (accepted now, decided later)
security: [{ oauth2: ["orders:write"] }]
parameters:
- { name: Idempotency-Key, in: header, schema: { type: string, maxLength: 64 } }
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [reason]
properties: { reason: { type: string, maxLength: 500 } }
responses:
'202':
description: Accepted; poll the Location resource
headers:
Location: { schema: { type: string, format: uri-reference } }
Retry-After: { schema: { type: integer } }
content:
application/json:
schema: { $ref: '#/components/schemas/CancellationRequest' }
'409': { $ref: '#/components/responses/Problem' }
/cancellation-requests/{requestId}:
get:
operationId: getCancellationRequest
tags: [Cancellation]
summary: Status of a cancellation request
parameters:
- { name: requestId, in: path, required: true, schema: { type: string } }
responses:
'200':
description: Current state
content:
application/json:
schema: { $ref: '#/components/schemas/CancellationRequest' }
'404': { $ref: '#/components/responses/Problem' }
components:
securitySchemes:
oauth2:
type: oauth2
flows:
clientCredentials:
tokenUrl: https://id.example.com/oauth/token
scopes:
orders:read: Read orders
orders:write: Place and cancel orders
headers:
ETag:
description: Weak validator; send it back as If-Match on commands.
schema: { type: string }
responses:
Problem:
description: RFC 9457 problem details
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
schemas:
OrderStatus: { type: string, enum: [draft, placed, cancelled] }
Money:
type: object
required: [amountMinor, currency]
properties:
amountMinor: { type: integer, format: int64 }
currency: { type: string, pattern: '^[A-Z]{3}$' }
CreateOrder:
type: object
required: [customerId, currency]
additionalProperties: false
properties:
customerId: { type: string }
currency: { type: string, pattern: '^[A-Z]{3}$' }
AddLine:
type: object
required: [sku, quantity]
additionalProperties: false
properties:
sku: { type: string }
quantity: { type: integer, minimum: 1, maximum: 50 }
Line:
type: object
required: [sku, quantity, unitPrice]
properties:
sku: { type: string }
quantity: { type: integer }
unitPrice: { $ref: '#/components/schemas/Money' }
Link:
type: object
required: [href]
properties:
href: { type: string }
method: { type: string }
Order:
type: object
required: [id, customerId, status, lines, total, _links]
properties:
id: { type: string }
customerId: { type: string }
status: { $ref: '#/components/schemas/OrderStatus' }
lines: { type: array, items: { $ref: '#/components/schemas/Line' } }
total: { $ref: '#/components/schemas/Money' }
placedAt: { type: [string, 'null'], format: date-time }
_links: { type: object, additionalProperties: { $ref: '#/components/schemas/Link' } }
OrderPage:
type: object
required: [items]
properties:
items: { type: array, items: { $ref: '#/components/schemas/Order' } }
nextCursor: { type: string }
CancellationRequest:
type: object
required: [id, orderId, state, reason]
properties:
id: { type: string }
orderId: { type: string }
state: { type: string, enum: [pending, completed, rejected] }
reason: { type: string }
detail: { type: string }
_links: { type: object, additionalProperties: { $ref: '#/components/schemas/Link' } }
Problem:
type: object
required: [type, title, status]
properties:
type: { type: string, format: uri }
title: { type: string }
status: { type: integer }
detail: { type: string }
instance: { type: string }
errors:
type: array
items:
type: object
required: [pointer, detail]
properties: { pointer: { type: string }, detail: { type: string } }The team ruleset turns policy into a failing build: every 4xx and 5xx must reference the Problem response, every POST must name its scope, and paths must not contain verbs.
# Team ruleset: extends the built-in OpenAPI rules and adds our conventions.
extends: ["spectral:oas"]
rules:
sales-problem-on-errors:
description: 4xx and 5xx responses must be RFC 9457 problem details.
severity: error
given: "$.paths[*][*].responses[?(@property.match(/^[45]/))]"
then: { field: "$ref", function: pattern, functionOptions: { match: "#/components/responses/Problem$" } }
sales-no-verbs-in-paths:
description: Paths name resources, not verbs (task nouns such as /placement are fine).
severity: warn
given: "$.paths[*]~"
then: { function: pattern, functionOptions: { notMatch: "/(get|set|create|update|delete)[A-Z-]" } }
sales-commands-need-security:
description: Every POST must name its scope.
severity: error
given: "$.paths[*].post"
then: { field: security, function: truthy }Design-first vs code-first: design-first suits an Open Host Service because the contract is a promise; code-first is acceptable for internal APIs with one consumer if the generated file is still diffed in review. A wrong hybrid is writing the file after the fact and never running it against the server.
API management Important
In plain words: The gateway and portal around your API: who may call, how often, who called, and how they sign up.
Common misunderstanding: "The API gateway is where business rules go." A gateway does cross-cutting policy; the rules that define Sales stay in Sales. Kong describes its gateway as "a reverse proxy that lets you manage, configure, and route requests to your APIs".
| Capability | What it does | Products |
|---|---|---|
| Authentication | API keys, OAuth 2.0 / OIDC token validation, mTLS | Kong plugins, Apigee policies, AWS API Gateway authorizers |
| Quotas and rate limits | Per key, per plan, per route | Kong Rate Limiting, Apigee Quota, Laravel RateLimiter at the app |
| Routing and transformation | Path and version routing, header rewriting | Kong routes, Apigee proxies, Envoy |
| Analytics | Who calls what, error rates, latency | Kong Konnect, Apigee Analytics |
| Developer portal | Docs, sign-up, key issuing | Kong Dev Portal, Apigee integrated portal |
| Monetisation | Plans, billing per call | Apigee monetisation, plan-based quotas |
| Lifecycle | Deprecation notices, version retirement | Portal plus analytics |
Where it sits relative to the context. In front. The context owns the contract (OpenAPI) and the rules; the gateway enforces policy from the contract (scopes, quotas) and gives each consumer an identity. The app still authorises per resource, because a gateway does not know that order o1 belongs to customer c1. Edge patterns, BFFs and meshes: API Gateway, BFF & Service Mesh.
| Where | Right | Wrong |
|---|---|---|
| Gateway | Key check, coarse scope, quota, TLS, request size, routing by version | Computing totals, state transitions |
| Context | Ownership checks, invariants, idempotency, error semantics | Per-plan billing logic |
| Both | Rate limit (coarse at the edge, fine in the app, as in RateLimiting.php) | Only one layer |
Timeline: one call through the stack
1 client POST /orders/o1/placement Authorization: Bearer <token>
2 gateway verify token, check scope orders:write, check plan quota, add X-Consumer-Id
3 gateway route /v1/orders/* to the Sales upstream
4 sales authenticate, authorise per resource (order belongs to this customer?)
5 sales If-Match check, Service.Place, map result to JSON or problem+json
6 gateway log status and latency per consumer, emit metricsGraphQL: the schema is the published language Must-know
In plain words: The GraphQL schema is a typed menu of everything a client may ask for; the client picks the fields it wants.
Common misunderstanding: "Generate the schema from the database and you are done." A schema that mirrors tables has the same flaw as json.Marshal(row): it publishes storage. GraphQL's own guidance is to "Model your business domain as a graph" and to "Design and evolve a type system over time without versions", and notes that the spec "is intentionally silent" on network, authorisation and pagination, so those are design work.
Definition: The schema (SDL) defines types, fields, enums, input types and the root types Query, Mutation and (optionally) Subscription. Every field has a resolver. The October 2021 spec edition says a mutation's top-level selection set "should be executed serially"; query fields may run in parallel.
| Rule | Why | In our schema |
|---|---|---|
| Types come from the published model | The schema survives storage changes | Order, OrderLine, Money, not orders_row |
| Value objects become types | Money is {amountMinor, currency}, never a bare float | type Money |
| Enums for states | Clients cannot invent states | OrderStatus, CancellationState |
| Cross-context data is a type owned by that context | Catalog owns Product | OrderLine.product resolved by loader |
| Nullable by intent | Non-null where the contract guarantees it, nullable where absence is normal | placedAt: DateTime |
| Documentation strings | The schema is the docs | """...""" on every type |
| Deprecate, do not delete | Evolve without versions | @deprecated(reason: "...") |
The full SDL (gqlgen flavour; Lighthouse's has the same types with directives):
"""An ISO 8601 date-time such as 2026-11-25T09:30:00Z."""
scalar DateTime
"""Money in minor units (cents) plus the ISO 4217 currency."""
type Money {
amountMinor: Int!
currency: String!
}
enum OrderStatus {
DRAFT
PLACED
CANCELLED
}
enum CancellationState {
PENDING
COMPLETED
REJECTED
}
"""Catalog's product, resolved through a batched loader."""
type Product {
sku: ID!
name: String!
}
type OrderLine {
sku: ID!
quantity: Int!
unitPrice: Money!
product: Product!
}
type Order {
id: ID!
customerId: ID!
status: OrderStatus!
lines: [OrderLine!]!
total: Money!
placedAt: DateTime
"""Bumped on every change; pass it back as expectedVersion."""
version: Int!
}
type OrderEdge {
cursor: String!
node: Order!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
type OrderConnection {
edges: [OrderEdge!]!
pageInfo: PageInfo!
}
type CancellationRequest {
id: ID!
orderId: ID!
state: CancellationState!
reason: String!
detail: String
}
"""A business problem the client can show; not a transport error."""
type UserError {
code: String!
message: String!
field: String
}
type Query {
order(id: ID!): Order
orders(customerId: ID!, status: OrderStatus, first: Int = 20, after: String): OrderConnection!
cancellationRequest(id: ID!): CancellationRequest
}
input CreateDraftOrderInput {
customerId: ID!
currency: String!
}
input AddOrderLineInput {
orderId: ID!
sku: ID!
quantity: Int!
expectedVersion: Int
}
input PlaceOrderInput {
orderId: ID!
expectedVersion: Int!
}
input RequestOrderCancellationInput {
orderId: ID!
reason: String!
"""Replay-safe: the same key returns the same request."""
idempotencyKey: String
}
type CreateDraftOrderPayload {
order: Order
userErrors: [UserError!]!
}
type AddOrderLinePayload {
order: Order
userErrors: [UserError!]!
}
type PlaceOrderPayload {
order: Order
userErrors: [UserError!]!
}
type RequestOrderCancellationPayload {
request: CancellationRequest
userErrors: [UserError!]!
}
type Mutation {
createDraftOrder(input: CreateDraftOrderInput!): CreateDraftOrderPayload!
addOrderLine(input: AddOrderLineInput!): AddOrderLinePayload!
placeOrder(input: PlaceOrderInput!): PlaceOrderPayload!
requestOrderCancellation(input: RequestOrderCancellationInput!): RequestOrderCancellationPayload!
}Real scenario: the web order page needs lines with product names; the mobile list needs id, status and total; Billing's back office needs customer and total only. All three send different queries to one schema, and the server does not change.
GraphQL commands, input types, payloads and errors Must-know
In plain words: A mutation is a command. It takes one input object and returns a payload that holds either the result or a list of business problems.
Common misunderstanding: "Errors go in the top-level errors array." That array is for failures of the request (syntax, validation, crash). A rule such as "the order is already placed" is a normal outcome the UI must render; model it in the payload as userErrors.
| Design rule | Reason |
|---|---|
Name mutations after commands: placeOrder, requestOrderCancellation | Same task-based vocabulary as REST |
One input argument of an input type | Evolvable: add optional fields without breaking |
Return a payload type (PlaceOrderPayload) | Room for order, userErrors, later more |
Business failures in userErrors { code message field } | Codes are the machine key, like Problem type |
| Unexpected failures as GraphQL errors | They are bugs or outages, not outcomes |
Concurrency token as input: expectedVersion | GraphQL has no If-Match; the idea is the same |
Idempotency as input: idempotencyKey | There is no Idempotency-Key header convention |
null for a missing node on queries | order(id) returns null, not an error |
Timeline: placeOrder with a stale version
1 client mutation { placeOrder(input:{orderId:"o1", expectedVersion:1}) { order{id} userErrors{code} } }
2 server Service.Place -> ErrVersionConflict (the order is at version 2)
3 server HTTP 200 {"data":{"placeOrder":{"order":null,"userErrors":[{"code":"STALE_VERSION"}]}}}
4 client re-reads the order, shows "the order changed", retries with version 2Fix: a small userError(err) mapper next to the resolvers (Go) or in a Presenter (PHP) that turns domain errors into codes, with unknown errors left to propagate. The REST problem catalogue and the GraphQL error codes should list the same business failures under different spellings (order-not-editable and ORDER_NOT_EDITABLE).
Pagination with Relay connections Important
In plain words: A list field returns edges (each with a cursor and a node) and pageInfo, and the client asks for first: 20, after: "cursor".
Common misunderstanding: "Connections are over-engineering; return a list." A bare list cannot carry a cursor, and adding pageInfo later breaks every client. GraphQL's pagination guide says cursor-based pagination "is the most powerful of those designed" because offset or id pagination "can be implemented using cursor-based pagination", and recommends opaque cursors: "we suggest base64 encoding them".
| Piece | Meaning | Source |
|---|---|---|
first, after | Slice forward: first N after this cursor | Cursor Connections Specification |
edges { cursor node } | The cursor belongs to the edge, not the node | same |
pageInfo { hasNextPage endCursor } | Tells the client when to stop | same |
| Opaque cursor | Format may change | same |
Our resolver fetches limit + 1 rows to compute hasNextPage, and encodes the sequence number as the cursor; the same keyset query serves REST and GraphQL.
N+1 and the dataloader Must-know
In plain words: When 20 orders each ask for their products, a naive server calls Catalog 20 times. A dataloader waits until all 20 have asked, then calls Catalog once.
Common misunderstanding: "The N+1 problem is a database problem." It happens at any boundary: SQL, an HTTP call to Catalog, a cache. In a distributed system each extra call is also a network failure waiting to happen.
Definition: gqlgen's docs: "Dataloaders consolidate the retrieval of information into fewer, batched calls." Lighthouse's docs describe the same trap: "Following a naive execution strategy, Lighthouse would first query a list of posts, then loop over that list and resolve the individual fields. The associated author for each post would be lazily loaded, querying the database once per post."
Without a loader With a loader (one request)
1 orders(first:3) -> 3 orders, 6 lines 1 orders(first:3) -> 3 orders, 6 lines
2 line1.product -> Catalog.Products([A]) 2 line1..6 product -> loader.Load(sku) x 6 (queued)
3 line2.product -> Catalog.Products([B]) 3 after ~2 ms or when the level ends:
4 ... six calls, serial 4 Catalog.Products([A,B]) once -> results fanned out| Stack | Mechanism | Per-request scope |
|---|---|---|
| Go gqlgen | dataloadgen.Loader created in HTTP middleware, WithWait(2ms) | Middleware puts a new Loaders in the context |
| Laravel Lighthouse (Eloquent relations) | @belongsTo, @hasMany, @with batch relation queries | Built in |
| Laravel Lighthouse (external data) | BatchLoaderRegistry::instance($info->path, ...) returning GraphQL\Deferred | One instance per query path in the request |
Three rules: (1) a loader is created per request, never global, or its cache leaks between users; (2) the batch function returns results in key order with one entry per key; (3) a missing key returns a placeholder or an error for that key, not for the whole batch. The test in the Go snippet asserts "six product fields cost one Catalog call".
package graph
import (
"context"
"net/http"
"time"
"github.com/vikstrous/dataloadgen"
"academy/api-realization-rest-graphql/graph/model"
"academy/api-realization-rest-graphql/sales"
)
type loadersKey struct{}
// Loaders holds one batching loader per request. A loader must never be
// shared across requests: its cache would leak data between callers.
type Loaders struct {
Product *dataloadgen.Loader[string, *model.Product]
}
// NewLoaders builds the per-request loaders. All Product lookups requested
// within the wait window become one Catalog.Products call.
func NewLoaders(cat sales.Catalog) *Loaders {
fetch := func(ctx context.Context, skus []string) ([]*model.Product, []error) {
keys := make([]sales.SKU, len(skus))
for i, s := range skus {
keys[i] = sales.SKU(s)
}
found, err := cat.Products(ctx, keys)
out := make([]*model.Product, len(skus))
errs := make([]error, len(skus))
for i, s := range skus {
switch p, ok := found[sales.SKU(s)]; {
case err != nil:
errs[i] = err
case ok:
out[i] = &model.Product{Sku: s, Name: p.Name}
default:
// Unknown SKU: return a placeholder rather than failing the whole order.
out[i] = &model.Product{Sku: s, Name: "(unavailable)"}
}
}
return out, errs
}
return &Loaders{Product: dataloadgen.NewLoader(fetch, dataloadgen.WithWait(2*time.Millisecond))}
}
// Middleware attaches fresh loaders to every incoming request.
func Middleware(cat sales.Catalog, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), loadersKey{}, NewLoaders(cat))
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// For returns the loaders of the current request.
func For(ctx context.Context) *Loaders { return ctx.Value(loadersKey{}).(*Loaders) }Federation, stitching and the BFF Important
In plain words: Each context owns its part of the graph; something above them presents one graph to clients.
Common misunderstanding: "One GraphQL server for the whole company is the goal." A single graph server owned by nobody becomes the new shared database. Ownership stays with the context; composition is a job for a router or a BFF.
| Approach | Idea | Fit |
|---|---|---|
| Schema stitching | A gateway merges remote schemas with hand-written links | Small, few schemas; you own the glue |
| Apollo Federation | Subgraphs declare entities and keys; a router composes a supergraph | Many teams, each owning types. Apollo: "When combining multiple GraphQL APIs, the single, federated graph is called a supergraph." |
| Backend for Frontend (BFF) | One API per client type, owned by that client's team, calling context APIs | Web and mobile need different aggregates; keeps GraphQL out of the contexts |
| Direct per-context schemas | Each context exposes its own GraphQL; clients call several | Few clients, simple needs |
Mapped to DDD: each subgraph is an Open Host Service of one context (Sales owns Order, Catalog owns Product, Identity owns Customer); a federation entity key (@key(fields: "sku") in Apollo's directive) lets Sales' OrderLine.product point to Catalog's Product without Sales importing Catalog's model. The BFF is a consumer and can be an anticorruption layer. Details of routers and BFFs are in API Gateway, BFF & Service Mesh.
gRPC, webhooks and AsyncAPI Good to know
In plain words: The same published language can also be a protobuf service, a webhook, or an event stream.
| Realisation | Fits | Contract format | Pointer |
|---|---|---|---|
| gRPC | Service-to-service calls with strict types, streaming, low latency | .proto | gRPC & Protobuf |
| Webhook | Telling an external system that something happened | JSON Schema + signature scheme | below |
| Message / event | Async integration, fan-out | AsyncAPI, JSON Schema, Avro/Protobuf | Domain Events vs Integration Events, Outbox Pattern |
| Server-Sent Events / GraphQL subscription | Live UIs | SDL / event stream | GraphQL |
A webhook is an event you push over HTTP. The rules: sign the body (HMAC with a shared secret, include a timestamp), retry with backoff and give each delivery an id, let the receiver acknowledge with 2xx quickly and process later, keep a delivery log the consumer can inspect, and publish the event's schema like any other part of the language. AsyncAPI is the OpenAPI of event-driven APIs: a document describing channels, messages and schemas (see the AsyncAPI concepts page). The reliable way to emit the webhook from Sales is the outbox: write the sales.order.cancelled.v1 event in the same transaction as the cancellation, and let a relay deliver it (Outbox Pattern, Designing for Failure & Reliable Messaging).
Security at the API edge Must-know
In plain words: Know who is calling, what they may do, and whose data they may touch, and enforce all three on the server.
Common misunderstanding: "The gateway checks the token, so the service need not check anything." A valid token proves who, not which order. Without a per-resource check, any authenticated customer can read any order by changing the id (broken object-level authorization).
| Question | Mechanism | Example |
|---|---|---|
| Who is calling? | OAuth 2.0 / OIDC access token, Sanctum token, mTLS for service-to-service | auth:sanctum |
| What may they do? | Scopes / abilities on the token | abilities:orders:write; Sanctum: tokens "may be granted abilities / scopes which specify which actions the tokens are allowed to perform" |
| Whose data? | Ownership or tenant check on every resource | owned() in the controller returns 404 for others' orders |
| How much? | Rate limiting per token and per route | RateLimiter::for('api', ...), throttle:api, Lighthouse @throttle |
| What shape? | Body size limits, strict JSON (DisallowUnknownFields), max query depth/complexity in GraphQL | http.MaxBytesReader, Lighthouse depth/complexity limits |
Rules that save real incidents:
- Tenant from the token, not from the request.
GET /orders?customerId=c9must not letc1readc9's orders; the Laravel list ignores any client-supplied customer, and the GraphQLcreateDraftOrdertakes the customer from the token. 404, not403, for other people's resources, unless existence is public information.- Scopes per command, not per endpoint family:
orders:readandorders:write. - GraphQL has one endpoint, so authorisation moves to fields and resolvers. Lighthouse's
@guard"does not log in users" by itself: add theAttemptAuthenticationmiddleware, then guard fields or whole root types. - Never return stack traces; the problem
typeis enough (see Problem Details). - Limit what a query may cost in GraphQL: depth, complexity, persisted queries for public clients.
Deeper identity and token design is outside this chapter: see Authentication and Authorization: RBAC, ABAC & Zero Trust; in our running example the Identity context issues the tokens and Sales only validates them and checks ownership.
Testing the published language Important
In plain words: Tests that fail when you break a promise to a consumer, not only when you break your own code.
Common misunderstanding: "Unit tests of handlers are enough." They pass while the contract drifts. You need tests about the contract.
| Layer | What it checks | Tool here |
|---|---|---|
| Handler test | Status, headers, body, problem type for each rule | Go httptest, Laravel postJson |
| Contract lint | The OpenAPI file follows house rules | Spectral ruleset |
| Breaking-change check | New file vs released file | oasdiff in CI |
| Provider verification | Real server responses conform to the file | Schemathesis, Dredd, Prism |
| Consumer-driven contract | Each consumer states what it uses; provider must satisfy all | Pact |
| Schema checks (GraphQL) | Operations in use still validate against the new schema | GraphQL Inspector, Apollo schema checks |
| Load and abuse | Rate limits answer 429, big bodies are refused | k6, Vegeta |
The Go tests in the snippets walk the lifecycle (create, empty place 422, add line, missing If-Match 428, stale 412, fresh 200, 304, conflict 409, 202 with idempotency replay, status polling, keyset pagination) and assert problem types, not messages. The GraphQL test asserts that six product fields cost one Catalog call and that a business failure is data (userErrors) with no errors key.
A consumer-driven contract (Pact) is the evidence a team needs to remove a field: if no consumer's pact mentions it, it can go.
Mechanics
Request lifecycle for one command Must-know
Timeline: POST /orders/o1/placement in the Go server
1 ServeMux matches "POST /orders/{id}/placement" and sets r.PathValue("id")
2 place(): parse If-Match -> 428 problem when absent or malformed
3 Service.Place(ctx, id, expected): load order, compare version -> ErrVersionConflict
4 order.Place(now): invariants (draft, at least one line) -> ErrNotDraft / ErrEmptyOrder
5 Repository.Save: compare-and-set on version, version++
6 sendOrder: ETag = W/"<new version>", JSON from OrderDTO
7 any error -> fromError(err) -> Problem -> application/problem+jsonStatus code and header reference Must-know
| Code | Name | When this API sends it | Retry? |
|---|---|---|---|
| 200 | OK | Read, command that finished | n/a |
| 201 | Created | Draft or line created; Location set | no |
| 202 | Accepted | Cancellation request recorded | poll Location |
| 204 | No Content | Delete of a draft (not used in the snippet) | no |
| 304 | Not Modified | If-None-Match matched | n/a |
| 400 | Bad Request | Malformed JSON, unknown field, bad cursor | no, fix the request |
| 401 | Unauthorized | Missing or invalid token | after re-auth |
| 403 | Forbidden | Token lacks the scope | no |
| 404 | Not Found | Unknown id, or somebody else's resource | no |
| 409 | Conflict | State does not allow the command | after the state changes |
| 412 | Precondition Failed | Stale If-Match | re-read, then retry |
| 422 | Unprocessable Content | Well-formed but invalid, or business rule on content | no, fix the data |
| 428 | Precondition Required | If-Match missing on placement | add the header |
| 429 | Too Many Requests | Rate limit; Retry-After | yes, after the delay |
| 500 | Internal Server Error | Bug; logged, problem about:blank | with backoff, idempotent only |
| 503 | Service Unavailable | Overload or dependency down; Retry-After | with backoff |
RFC 6585 on 429: the response "MAY include a Retry-After header indicating how long to wait before making a new request".
Idempotency keys in storage Must-know
-- One row per accepted key. The unique constraint makes concurrent duplicates safe.
CREATE TABLE cancellation_requests (
id text PRIMARY KEY,
order_id text NOT NULL,
reason text NOT NULL,
state text NOT NULL DEFAULT 'pending',
detail text,
idem_key text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX cancellation_requests_idem
ON cancellation_requests (order_id, idem_key) WHERE idem_key IS NOT NULL;
-- The handler does: INSERT ... ON CONFLICT (order_id, idem_key) DO NOTHING RETURNING id;
-- no row returned -> SELECT the existing request and answer with it (same 202 body).Scope the key to the caller (here the order; in general the consumer id plus the key), expire keys after a window (Stripe documents keys up to 255 characters), and store enough of the first response to repeat it. A different body under the same key should be an error, not a silent replay.
How GraphQL travels over HTTP Important
| Aspect | Rule |
|---|---|
| Endpoint | One path, /graphql, usually POST with {"query", "variables", "operationName"} |
| Status | 200 even for field errors; 400 for unparsable or invalid documents; 401/403 from the transport |
| Execution | Fields of a query may resolve in parallel; top-level mutation fields run serially |
| Batching | A loader batches inside one operation; request batching merges operations (avoid unless needed) |
| Caching | POST is not cached by HTTP caches; use persisted queries with GET or a client cache keyed by id |
| Introspection | Convenient in development; restrict in production for public APIs |
| Limits | Depth, complexity, timeouts, pagination caps on every list |
Go
One module academy/api-realization-rest-graphql (gofmt and go vet clean, go test ./... passes). Layers: sales is the context (aggregate, application Service, ports, in-memory adapters); rest and graph are two realisations of the same language; cmd/server runs both.
The domain and the application service
Order has private fields; the service is the only thing both realisations call; the ports (Catalog, Fulfilment, Repository, Cancellations) are interfaces defined next to it.
// Package sales is the Sales bounded context. Order is the aggregate root;
// the REST and GraphQL layers never see its fields, only what it exposes.
package sales
import (
"errors"
"fmt"
"time"
)
// MaxQuantityPerLine is the Sales invariant shared by every chapter: 1..50
// units of one SKU per order line. The REST and GraphQL edges repeat it as
// shape validation; the aggregate is the authority.
const MaxQuantityPerLine = 50
type (
// OrderID is the identity of the Order aggregate.
OrderID string
// CustomerID references the Identity context's customer by id only.
CustomerID string
// SKU references a Catalog product by id only.
SKU string
)
// Status is the order state machine.
type Status string
const (
Draft Status = "draft"
Placed Status = "placed"
Cancelled Status = "cancelled"
)
var (
ErrNotFound = errors.New("not found")
ErrNotDraft = errors.New("only a draft order can be edited")
ErrEmptyOrder = errors.New("an order needs at least one line")
ErrBadQuantity = fmt.Errorf("quantity must be between 1 and %d", MaxQuantityPerLine)
ErrUnknownProduct = errors.New("unknown product")
ErrVersionConflict = errors.New("order changed since you read it")
ErrNotCancellable = errors.New("order cannot be cancelled in its current state")
ErrAlreadyCancelled = errors.New("order is already cancelled")
)
// Money is a value object in minor units.
type Money struct {
Minor int64
Currency string
}
// Line is a read-only view of one order line.
type Line struct {
SKU SKU
Quantity int
UnitPriceMinor int64
}
// Order is the aggregate root. Fields are private: only methods change state.
type Order struct {
id OrderID
customer CustomerID
currency string
status Status
lines []Line
placedAt time.Time
version int
seq int64 // creation order, used as the keyset cursor
}
// NewOrder starts a draft order.
func NewOrder(id OrderID, customer CustomerID, currency string) *Order {
return &Order{id: id, customer: customer, currency: currency, status: Draft}
}
// AddLine adds or merges a line while the order is a draft.
func (o *Order) AddLine(sku SKU, qty int, unitPriceMinor int64) error {
if o.status != Draft {
return ErrNotDraft
}
if qty < 1 || qty > MaxQuantityPerLine {
return ErrBadQuantity
}
for i := range o.lines {
if o.lines[i].SKU == sku {
if o.lines[i].Quantity+qty > MaxQuantityPerLine {
return ErrBadQuantity
}
o.lines[i].Quantity += qty
return nil
}
}
o.lines = append(o.lines, Line{SKU: sku, Quantity: qty, UnitPriceMinor: unitPriceMinor})
return nil
}
// Place commits the order.
func (o *Order) Place(now time.Time) error {
if o.status != Draft {
return ErrNotDraft
}
if len(o.lines) == 0 {
return ErrEmptyOrder
}
o.status = Placed
o.placedAt = now
return nil
}
// Cancel moves a draft or placed order to cancelled.
func (o *Order) Cancel() error {
switch o.status {
case Cancelled:
return ErrAlreadyCancelled
case Draft, Placed:
o.status = Cancelled
return nil
}
return ErrNotCancellable
}
// Total is derived from the lines.
func (o *Order) Total() Money {
var t int64
for _, l := range o.lines {
t += l.UnitPriceMinor * int64(l.Quantity)
}
return Money{Minor: t, Currency: o.currency}
}
func (o *Order) ID() OrderID { return o.id }
func (o *Order) Customer() CustomerID { return o.customer }
func (o *Order) Currency() string { return o.currency }
func (o *Order) Status() Status { return o.status }
func (o *Order) Version() int { return o.version }
func (o *Order) PlacedAt() time.Time { return o.placedAt }
func (o *Order) Seq() int64 { return o.seq }
// Lines returns a copy of the lines.
func (o *Order) Lines() []Line { return append([]Line(nil), o.lines...) }package sales
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"time"
)
// Product is Catalog's published view of a product (an ACL-friendly shape).
type Product struct {
SKU SKU
Name string
UnitPriceMinor int64
}
// Catalog is the port to the Catalog context. Batch lookup exists so that
// GraphQL can avoid N+1 calls.
type Catalog interface {
Products(ctx context.Context, skus []SKU) (map[SKU]Product, error)
}
// Fulfilment is the port to the Fulfilment context.
type Fulfilment interface {
// ReleaseStock asks Fulfilment to release reservations for an order.
ReleaseStock(ctx context.Context, id OrderID) error
}
// Repository loads and saves whole aggregates.
type Repository interface {
Get(ctx context.Context, id OrderID) (*Order, error)
// Save inserts (version 0) or updates with a compare-and-set on version.
Save(ctx context.Context, o *Order) error
// List returns orders in creation order after the cursor sequence.
List(ctx context.Context, q ListQuery) ([]*Order, error)
}
// ListQuery is a keyset query: filters, the last seen sequence, and a limit.
type ListQuery struct {
Customer CustomerID
Status Status // empty means any
After int64
Limit int
}
// CancellationState is the lifecycle of a cancellation request resource.
type CancellationState string
const (
CancellationPending CancellationState = "pending"
CancellationCompleted CancellationState = "completed"
CancellationRejected CancellationState = "rejected"
)
// CancellationRequest is a first-class record of the intent to cancel.
// It exists because cancelling needs Fulfilment, so the answer is not instant.
type CancellationRequest struct {
ID string
OrderID OrderID
Reason string
State CancellationState
Detail string
}
// Cancellations stores requests and remembers idempotency keys.
type Cancellations interface {
Create(ctx context.Context, key string, r CancellationRequest) (CancellationRequest, bool, error)
Get(ctx context.Context, id string) (CancellationRequest, error)
Update(ctx context.Context, r CancellationRequest) error
}
// Service is the application layer: one method per use case.
type Service struct {
Orders Repository
Cancels Cancellations
Catalog Catalog
Fulfilment Fulfilment
Now func() time.Time
NewID func() string
}
func (s *Service) id(prefix string) string {
if s.NewID != nil {
return prefix + s.NewID()
}
b := make([]byte, 8)
_, _ = rand.Read(b)
return prefix + hex.EncodeToString(b)
}
func (s *Service) now() time.Time {
if s.Now != nil {
return s.Now()
}
return time.Now().UTC()
}
// CreateDraft opens a new draft order.
func (s *Service) CreateDraft(ctx context.Context, c CustomerID, currency string) (*Order, error) {
o := NewOrder(OrderID(s.id("ord_")), c, currency)
if err := s.Orders.Save(ctx, o); err != nil {
return nil, err
}
return s.Orders.Get(ctx, o.ID())
}
// load reads the order and enforces the caller's expected version (0 = skip).
func (s *Service) load(ctx context.Context, id OrderID, expected int) (*Order, error) {
o, err := s.Orders.Get(ctx, id)
if err != nil {
return nil, err
}
if expected != 0 && o.Version() != expected {
return nil, ErrVersionConflict
}
return o, nil
}
// AddLine prices the line from Catalog, never from the client.
func (s *Service) AddLine(ctx context.Context, id OrderID, sku SKU, qty, expected int) (*Order, error) {
o, err := s.load(ctx, id, expected)
if err != nil {
return nil, err
}
ps, err := s.Catalog.Products(ctx, []SKU{sku})
if err != nil {
return nil, err
}
p, ok := ps[sku]
if !ok {
return nil, fmt.Errorf("%w: %s", ErrUnknownProduct, sku)
}
if err := o.AddLine(sku, qty, p.UnitPriceMinor); err != nil {
return nil, err
}
if err := s.Orders.Save(ctx, o); err != nil {
return nil, err
}
return s.Orders.Get(ctx, id)
}
// Place is the "place order" command.
func (s *Service) Place(ctx context.Context, id OrderID, expected int) (*Order, error) {
o, err := s.load(ctx, id, expected)
if err != nil {
return nil, err
}
if err := o.Place(s.now()); err != nil {
return nil, err
}
if err := s.Orders.Save(ctx, o); err != nil {
return nil, err
}
return s.Orders.Get(ctx, id)
}
// RequestCancellation records the intent and returns at once. Replaying the
// same key returns the same request instead of creating a second one.
func (s *Service) RequestCancellation(ctx context.Context, id OrderID, reason, key string) (CancellationRequest, error) {
o, err := s.Orders.Get(ctx, id)
if err != nil {
return CancellationRequest{}, err
}
if o.Status() == Cancelled {
return CancellationRequest{}, ErrAlreadyCancelled
}
r, _, err := s.Cancels.Create(ctx, key, CancellationRequest{
ID: s.id("can_"), OrderID: id, Reason: reason, State: CancellationPending,
})
return r, err
}
// ProcessCancellation is the background step: it asks Fulfilment to release
// stock, then cancels the aggregate, then closes the request.
func (s *Service) ProcessCancellation(ctx context.Context, reqID string) error {
r, err := s.Cancels.Get(ctx, reqID)
if err != nil {
return err
}
if r.State != CancellationPending {
return nil // already handled: processing is idempotent
}
if err := s.Fulfilment.ReleaseStock(ctx, r.OrderID); err != nil {
r.State, r.Detail = CancellationRejected, err.Error()
return s.Cancels.Update(ctx, r)
}
o, err := s.Orders.Get(ctx, r.OrderID)
if err != nil {
return err
}
if err := o.Cancel(); err != nil {
r.State, r.Detail = CancellationRejected, err.Error()
return s.Cancels.Update(ctx, r)
}
if err := s.Orders.Save(ctx, o); err != nil {
return err
}
r.State = CancellationCompleted
return s.Cancels.Update(ctx, r)
}
// GetCancellation reads the status resource.
func (s *Service) GetCancellation(ctx context.Context, id string) (CancellationRequest, error) {
return s.Cancels.Get(ctx, id)
}
// GetOrder reads one order.
func (s *Service) GetOrder(ctx context.Context, id OrderID) (*Order, error) {
return s.Orders.Get(ctx, id)
}
// ListOrders runs a keyset query.
func (s *Service) ListOrders(ctx context.Context, q ListQuery) ([]*Order, error) {
return s.Orders.List(ctx, q)
}REST: DTOs, Problem Details and handlers
The DTOs and problems were shown above. The handlers use Go 1.22 ServeMux method-and-wildcard patterns ("POST /orders/{id}/placement"); with chi the same routes read r.Post("/orders/{id}/placement", h) and chi.URLParam(r, "id").
package rest
import (
"encoding/base64"
"encoding/json"
"net/http"
"strconv"
"academy/api-realization-rest-graphql/sales"
)
// Server wires the use cases to HTTP. Go 1.22+ ServeMux patterns are enough;
// chi.Router works the same way (r.Post("/orders/{id}/placement", ...)).
type Server struct{ Svc *sales.Service }
// Handler returns the routed http.Handler.
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /orders", s.createOrder)
mux.HandleFunc("GET /orders", s.listOrders)
mux.HandleFunc("GET /orders/{id}", s.getOrder)
mux.HandleFunc("POST /orders/{id}/lines", s.addLine)
mux.HandleFunc("POST /orders/{id}/placement", s.place)
mux.HandleFunc("POST /orders/{id}/cancellation-requests", s.requestCancellation)
mux.HandleFunc("GET /cancellation-requests/{id}", s.getCancellation)
return mux
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func decode(w http.ResponseWriter, r *http.Request, v any) bool {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
dec.DisallowUnknownFields()
if err := dec.Decode(v); err != nil {
writeProblem(w, r, Problem{Type: problemBase + "malformed-body", Title: "Malformed request body",
Status: http.StatusBadRequest, Detail: err.Error()})
return false
}
return true
}
func sendOrder(w http.ResponseWriter, status int, o *sales.Order) {
w.Header().Set("ETag", etag(o))
writeJSON(w, status, toOrderDTO(o))
}
func (s *Server) createOrder(w http.ResponseWriter, r *http.Request) {
var in struct {
CustomerID string `json:"customerId"`
Currency string `json:"currency"`
}
if !decode(w, r, &in) {
return
}
var errs []FieldError
if in.CustomerID == "" {
errs = append(errs, FieldError{"/customerId", "is required"})
}
if len(in.Currency) != 3 {
errs = append(errs, FieldError{"/currency", "must be a 3-letter ISO 4217 code"})
}
if errs != nil {
writeProblem(w, r, Problem{Type: problemBase + "validation-failed", Title: "Your request is invalid",
Status: http.StatusUnprocessableEntity, Errors: errs})
return
}
o, err := s.Svc.CreateDraft(r.Context(), sales.CustomerID(in.CustomerID), in.Currency)
if err != nil {
writeProblem(w, r, fromError(err))
return
}
w.Header().Set("Location", "/orders/"+string(o.ID()))
sendOrder(w, http.StatusCreated, o)
}
func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
o, err := s.Svc.GetOrder(r.Context(), sales.OrderID(r.PathValue("id")))
if err != nil {
writeProblem(w, r, fromError(err))
return
}
if inm := r.Header.Get("If-None-Match"); inm != "" && inm == etag(o) {
w.Header().Set("ETag", etag(o))
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("Cache-Control", "private, max-age=0, must-revalidate")
sendOrder(w, http.StatusOK, o)
}
func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
limit, _ := strconv.Atoi(q.Get("limit"))
if limit < 1 || limit > 100 {
limit = 20
}
var after int64
if c := q.Get("cursor"); c != "" {
raw, err := base64.RawURLEncoding.DecodeString(c)
if err == nil {
after, err = strconv.ParseInt(string(raw), 10, 64)
}
if err != nil {
writeProblem(w, r, Problem{Type: problemBase + "validation-failed", Title: "Your request is invalid",
Status: http.StatusBadRequest, Detail: "cursor is not valid"})
return
}
}
orders, err := s.Svc.ListOrders(r.Context(), sales.ListQuery{
Customer: sales.CustomerID(q.Get("customerId")), Status: sales.Status(q.Get("status")),
After: after, Limit: limit + 1, // one extra row tells us whether a next page exists
})
if err != nil {
writeProblem(w, r, fromError(err))
return
}
page := OrderPage{Items: []OrderDTO{}}
for i, o := range orders {
if i == limit {
last := orders[limit-1].Seq()
page.NextCursor = base64.RawURLEncoding.EncodeToString([]byte(strconv.FormatInt(last, 10)))
break
}
page.Items = append(page.Items, toOrderDTO(o))
}
writeJSON(w, http.StatusOK, page)
}
func (s *Server) addLine(w http.ResponseWriter, r *http.Request) {
var in struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
}
if !decode(w, r, &in) {
return
}
expected, _ := parseETag(r.Header.Get("If-Match")) // optional here
o, err := s.Svc.AddLine(r.Context(), sales.OrderID(r.PathValue("id")), sales.SKU(in.SKU), in.Quantity, expected)
if err != nil {
writeProblem(w, r, fromError(err))
return
}
w.Header().Set("Location", "/orders/"+string(o.ID())+"/lines/"+in.SKU)
sendOrder(w, http.StatusCreated, o)
}
// place requires If-Match: money-moving commands must not run on a stale view.
func (s *Server) place(w http.ResponseWriter, r *http.Request) {
expected, ok := parseETag(r.Header.Get("If-Match"))
if !ok {
writeProblem(w, r, Problem{Type: problemBase + "precondition-required", Title: "If-Match header is required",
Status: http.StatusPreconditionRequired})
return
}
o, err := s.Svc.Place(r.Context(), sales.OrderID(r.PathValue("id")), expected)
if err != nil {
writeProblem(w, r, fromError(err))
return
}
sendOrder(w, http.StatusOK, o)
}
// requestCancellation answers 202: the request is accepted, not yet done.
func (s *Server) requestCancellation(w http.ResponseWriter, r *http.Request) {
var in struct {
Reason string `json:"reason"`
}
if !decode(w, r, &in) {
return
}
req, err := s.Svc.RequestCancellation(r.Context(), sales.OrderID(r.PathValue("id")), in.Reason, r.Header.Get("Idempotency-Key"))
if err != nil {
writeProblem(w, r, fromError(err))
return
}
w.Header().Set("Location", "/cancellation-requests/"+req.ID)
w.Header().Set("Retry-After", "1")
writeJSON(w, http.StatusAccepted, toCancellationDTO(req))
}
func (s *Server) getCancellation(w http.ResponseWriter, r *http.Request) {
req, err := s.Svc.GetCancellation(r.Context(), r.PathValue("id"))
if err != nil {
writeProblem(w, r, fromError(err))
return
}
writeJSON(w, http.StatusOK, toCancellationDTO(req))
}The test walks the whole contract:
package rest_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/api-realization-rest-graphql/rest"
"academy/api-realization-rest-graphql/sales"
)
func newServer(t *testing.T) (*httptest.Server, *sales.Service) {
t.Helper()
n := 0
svc := &sales.Service{
Orders: sales.NewMemoryOrders(),
Cancels: sales.NewMemoryCancellations(),
Catalog: &sales.StaticCatalog{Items: map[sales.SKU]sales.Product{
"SKU-1": {SKU: "SKU-1", Name: "Mug", UnitPriceMinor: 1250},
}},
Fulfilment: sales.NoopFulfilment{},
NewID: func() string { n++; return fmt.Sprint(n) },
}
ts := httptest.NewServer((&rest.Server{Svc: svc}).Handler())
t.Cleanup(ts.Close)
return ts, svc
}
func do(t *testing.T, method, url, body string, hdr map[string]string) *http.Response {
t.Helper()
req, _ := http.NewRequest(method, url, strings.NewReader(body))
for k, v := range hdr {
req.Header.Set(k, v)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { res.Body.Close() })
return res
}
func decode[T any](t *testing.T, res *http.Response) T {
t.Helper()
var v T
if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
t.Fatal(err)
}
return v
}
func TestOrderLifecycleOverHTTP(t *testing.T) {
ts, svc := newServer(t)
res := do(t, "POST", ts.URL+"/orders", `{"customerId":"c1","currency":"EUR"}`, nil)
if res.StatusCode != 201 || res.Header.Get("Location") != "/orders/ord_1" {
t.Fatalf("create: %d %q", res.StatusCode, res.Header.Get("Location"))
}
etag := res.Header.Get("ETag")
// Placing an empty order is a business-rule problem, not a 500.
res = do(t, "POST", ts.URL+"/orders/ord_1/placement", "", map[string]string{"If-Match": etag})
p := decode[rest.Problem](t, res)
if res.StatusCode != 422 || p.Type != "https://api.example.com/problems/order-empty" ||
res.Header.Get("Content-Type") != "application/problem+json" {
t.Fatalf("empty place: %d %+v", res.StatusCode, p)
}
res = do(t, "POST", ts.URL+"/orders/ord_1/lines", `{"sku":"SKU-1","quantity":2}`, nil)
o := decode[rest.OrderDTO](t, res)
if res.StatusCode != 201 || o.Total.AmountMinor != 2500 {
t.Fatalf("add line: %d %+v", res.StatusCode, o)
}
if _, ok := o.Links["placement"]; !ok {
t.Fatal("draft order must advertise the placement link")
}
// Missing If-Match: 428. Stale If-Match: 412. Fresh: 200.
if res = do(t, "POST", ts.URL+"/orders/ord_1/placement", "", nil); res.StatusCode != 428 {
t.Fatalf("missing If-Match: %d", res.StatusCode)
}
if res = do(t, "POST", ts.URL+"/orders/ord_1/placement", "", map[string]string{"If-Match": etag}); res.StatusCode != 412 {
t.Fatalf("stale If-Match: %d", res.StatusCode)
}
fresh := do(t, "GET", ts.URL+"/orders/ord_1", "", nil).Header.Get("ETag")
res = do(t, "POST", ts.URL+"/orders/ord_1/placement", "", map[string]string{"If-Match": fresh})
if o = decode[rest.OrderDTO](t, res); res.StatusCode != 200 || o.Status != "placed" {
t.Fatalf("place: %d %+v", res.StatusCode, o)
}
// Conditional GET: 304 when nothing changed.
cur := res.Header.Get("ETag")
if res = do(t, "GET", ts.URL+"/orders/ord_1", "", map[string]string{"If-None-Match": cur}); res.StatusCode != 304 {
t.Fatalf("conditional GET: %d", res.StatusCode)
}
// A placed order can no longer take lines: 409 with a stable problem type.
res = do(t, "POST", ts.URL+"/orders/ord_1/lines", `{"sku":"SKU-1","quantity":1}`, nil)
if p = decode[rest.Problem](t, res); res.StatusCode != 409 || !strings.HasSuffix(p.Type, "order-not-editable") {
t.Fatalf("edit placed: %d %+v", res.StatusCode, p)
}
// Eventual consistency made visible: 202 + Location, then poll.
hdr := map[string]string{"Idempotency-Key": "k-1"}
res = do(t, "POST", ts.URL+"/orders/ord_1/cancellation-requests", `{"reason":"changed my mind"}`, hdr)
c := decode[rest.CancellationDTO](t, res)
if res.StatusCode != 202 || res.Header.Get("Location") != "/cancellation-requests/can_2" || c.State != "pending" {
t.Fatalf("cancel: %d %+v", res.StatusCode, c)
}
// The same key returns the same request, not a second one.
res = do(t, "POST", ts.URL+"/orders/ord_1/cancellation-requests", `{"reason":"changed my mind"}`, hdr)
if res.Header.Get("Location") != "/cancellation-requests/can_2" {
t.Fatalf("replay created a new request: %q", res.Header.Get("Location"))
}
if c = decode[rest.CancellationDTO](t, do(t, "GET", ts.URL+"/cancellation-requests/can_2", "", nil)); c.State != "pending" {
t.Fatalf("before worker: %s", c.State)
}
if err := svc.ProcessCancellation(context.Background(), "can_2"); err != nil {
t.Fatal(err)
}
c = decode[rest.CancellationDTO](t, do(t, "GET", ts.URL+"/cancellation-requests/can_2", "", nil))
o = decode[rest.OrderDTO](t, do(t, "GET", ts.URL+"/orders/ord_1", "", nil))
if c.State != "completed" || o.Status != "cancelled" {
t.Fatalf("after worker: %s / %s", c.State, o.Status)
}
}
func TestValidationAndKeysetPagination(t *testing.T) {
ts, _ := newServer(t)
res := do(t, "POST", ts.URL+"/orders", `{"currency":"EU"}`, nil)
p := decode[rest.Problem](t, res)
if res.StatusCode != 422 || len(p.Errors) != 2 || p.Errors[0].Pointer != "/customerId" {
t.Fatalf("validation: %d %+v", res.StatusCode, p)
}
for range 3 {
do(t, "POST", ts.URL+"/orders", `{"customerId":"c9","currency":"EUR"}`, nil)
}
page := decode[rest.OrderPage](t, do(t, "GET", ts.URL+"/orders?customerId=c9&limit=2", "", nil))
if len(page.Items) != 2 || page.NextCursor == "" {
t.Fatalf("page 1: %+v", page)
}
page2 := decode[rest.OrderPage](t, do(t, "GET", ts.URL+"/orders?customerId=c9&limit=2&cursor="+page.NextCursor, "", nil))
if len(page2.Items) != 1 || page2.NextCursor != "" {
t.Fatalf("page 2: %+v", page2)
}
if res = do(t, "GET", ts.URL+"/orders/nope", "", nil); res.StatusCode != 404 {
t.Fatalf("404: %d", res.StatusCode)
}
}GraphQL with gqlgen
gqlgen generate reads gqlgen.yml and the SDL and writes generated.go and model/models_gen.go; the hand-written parts are the resolvers and the loader. OrderLine.product is configured as a resolver field, which is how the dataloader is attached.
schema:
- graph/*.graphql
exec:
filename: graph/generated.go
package: graph
model:
filename: graph/model/models_gen.go
package: model
resolver:
layout: follow-schema
dir: graph
package: graph
filename_template: "{name}.resolvers.go"
autobind: []
models:
ID:
model: github.com/99designs/gqlgen/graphql.String
DateTime:
model: github.com/99designs/gqlgen/graphql.Time
OrderLine:
fields:
product:
resolver: truepackage graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98
import (
"academy/api-realization-rest-graphql/graph/model"
"academy/api-realization-rest-graphql/sales"
"context"
"encoding/base64"
"errors"
"strconv"
)
// CreateDraftOrder is the resolver for the createDraftOrder field.
func (r *mutationResolver) CreateDraftOrder(ctx context.Context, input model.CreateDraftOrderInput) (*model.CreateDraftOrderPayload, error) {
o, err := r.Svc.CreateDraft(ctx, sales.CustomerID(input.CustomerID), input.Currency)
if ue, ok := userError(err); ok {
return &model.CreateDraftOrderPayload{UserErrors: []*model.UserError{ue}}, nil
} else if err != nil {
return nil, err
}
return &model.CreateDraftOrderPayload{Order: toOrder(o), UserErrors: []*model.UserError{}}, nil
}
// AddOrderLine is the resolver for the addOrderLine field.
func (r *mutationResolver) AddOrderLine(ctx context.Context, input model.AddOrderLineInput) (*model.AddOrderLinePayload, error) {
expected := 0
if input.ExpectedVersion != nil {
expected = *input.ExpectedVersion
}
o, err := r.Svc.AddLine(ctx, sales.OrderID(input.OrderID), sales.SKU(input.Sku), input.Quantity, expected)
if ue, ok := userError(err); ok {
return &model.AddOrderLinePayload{UserErrors: []*model.UserError{ue}}, nil
} else if err != nil {
return nil, err
}
return &model.AddOrderLinePayload{Order: toOrder(o), UserErrors: []*model.UserError{}}, nil
}
// PlaceOrder is the resolver for the placeOrder field.
func (r *mutationResolver) PlaceOrder(ctx context.Context, input model.PlaceOrderInput) (*model.PlaceOrderPayload, error) {
o, err := r.Svc.Place(ctx, sales.OrderID(input.OrderID), input.ExpectedVersion)
if ue, ok := userError(err); ok {
return &model.PlaceOrderPayload{UserErrors: []*model.UserError{ue}}, nil
} else if err != nil {
return nil, err
}
return &model.PlaceOrderPayload{Order: toOrder(o), UserErrors: []*model.UserError{}}, nil
}
// RequestOrderCancellation is the resolver for the requestOrderCancellation field.
func (r *mutationResolver) RequestOrderCancellation(ctx context.Context, input model.RequestOrderCancellationInput) (*model.RequestOrderCancellationPayload, error) {
key := ""
if input.IdempotencyKey != nil {
key = *input.IdempotencyKey
}
req, err := r.Svc.RequestCancellation(ctx, sales.OrderID(input.OrderID), input.Reason, key)
if ue, ok := userError(err); ok {
return &model.RequestOrderCancellationPayload{UserErrors: []*model.UserError{ue}}, nil
} else if err != nil {
return nil, err
}
return &model.RequestOrderCancellationPayload{Request: toRequest(req), UserErrors: []*model.UserError{}}, nil
}
// Product is the resolver for the product field. It never calls Catalog
// directly: the loader batches every product requested in this operation.
func (r *orderLineResolver) Product(ctx context.Context, obj *model.OrderLine) (*model.Product, error) {
return For(ctx).Product.Load(ctx, obj.Sku)
}
// Order is the resolver for the order field.
func (r *queryResolver) Order(ctx context.Context, id string) (*model.Order, error) {
o, err := r.Svc.GetOrder(ctx, sales.OrderID(id))
if errors.Is(err, sales.ErrNotFound) {
return nil, nil // a missing node is null, not an error
}
if err != nil {
return nil, err
}
return toOrder(o), nil
}
// Orders is the resolver for the orders field (Relay-style connection).
func (r *queryResolver) Orders(ctx context.Context, customerID string, status *model.OrderStatus, first *int, after *string) (*model.OrderConnection, error) {
limit := 20
if first != nil && *first > 0 && *first <= 100 {
limit = *first
}
var cursor int64
if after != nil {
raw, err := base64.RawURLEncoding.DecodeString(*after)
if err == nil {
cursor, err = strconv.ParseInt(string(raw), 10, 64)
}
if err != nil {
return nil, errors.New("invalid cursor")
}
}
q := sales.ListQuery{Customer: sales.CustomerID(customerID), After: cursor, Limit: limit + 1}
if status != nil {
q.Status = sales.Status(lower(string(*status)))
}
rows, err := r.Svc.ListOrders(ctx, q)
if err != nil {
return nil, err
}
conn := &model.OrderConnection{Edges: []*model.OrderEdge{}, PageInfo: &model.PageInfo{}}
for i, o := range rows {
if i == limit {
conn.PageInfo.HasNextPage = true
break
}
c := base64.RawURLEncoding.EncodeToString([]byte(strconv.FormatInt(o.Seq(), 10)))
conn.Edges = append(conn.Edges, &model.OrderEdge{Cursor: c, Node: toOrder(o)})
conn.PageInfo.EndCursor = &c
}
return conn, nil
}
// CancellationRequest is the resolver for the cancellationRequest field.
func (r *queryResolver) CancellationRequest(ctx context.Context, id string) (*model.CancellationRequest, error) {
req, err := r.Svc.GetCancellation(ctx, id)
if errors.Is(err, sales.ErrNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return toRequest(req), nil
}
// Mutation returns MutationResolver implementation.
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }
// OrderLine returns OrderLineResolver implementation.
func (r *Resolver) OrderLine() OrderLineResolver { return &orderLineResolver{r} }
// Query returns QueryResolver implementation.
func (r *Resolver) Query() QueryResolver { return &queryResolver{r} }
type (
mutationResolver struct{ *Resolver }
orderLineResolver struct{ *Resolver }
queryResolver struct{ *Resolver }
)package graph
import (
"errors"
"academy/api-realization-rest-graphql/graph/model"
"academy/api-realization-rest-graphql/sales"
)
// toOrder maps the aggregate to the GraphQL type. Types come from the
// published model, not from table columns.
func toOrder(o *sales.Order) *model.Order {
out := &model.Order{
ID: string(o.ID()), CustomerID: string(o.Customer()), Version: o.Version(),
Status: model.OrderStatus(upper(string(o.Status()))),
Total: &model.Money{AmountMinor: int(o.Total().Minor), Currency: o.Total().Currency},
}
if !o.PlacedAt().IsZero() {
t := o.PlacedAt()
out.PlacedAt = &t
}
for _, l := range o.Lines() {
out.Lines = append(out.Lines, &model.OrderLine{
Sku: string(l.SKU), Quantity: l.Quantity,
UnitPrice: &model.Money{AmountMinor: int(l.UnitPriceMinor), Currency: o.Currency()},
})
}
return out
}
func toRequest(r sales.CancellationRequest) *model.CancellationRequest {
out := &model.CancellationRequest{
ID: r.ID, OrderID: string(r.OrderID), Reason: r.Reason,
State: model.CancellationState(upper(string(r.State))),
}
if r.Detail != "" {
out.Detail = &r.Detail
}
return out
}
// userError turns a business failure into data the client can render.
// Anything unexpected is returned as a real GraphQL error instead.
func userError(err error) (*model.UserError, bool) {
codes := map[error]string{
sales.ErrNotDraft: "ORDER_NOT_EDITABLE", sales.ErrEmptyOrder: "ORDER_EMPTY",
sales.ErrBadQuantity: "INVALID_QUANTITY", sales.ErrUnknownProduct: "UNKNOWN_PRODUCT",
sales.ErrVersionConflict: "STALE_VERSION", sales.ErrNotFound: "NOT_FOUND",
sales.ErrAlreadyCancelled: "ALREADY_CANCELLED", sales.ErrNotCancellable: "NOT_CANCELLABLE",
}
for target, code := range codes {
if errors.Is(err, target) {
return &model.UserError{Code: code, Message: err.Error()}, true
}
}
return nil, false
}
func upper(s string) string {
b := []byte(s)
for i, c := range b {
if c >= 'a' && c <= 'z' {
b[i] = c - 32
}
}
return string(b)
}
func lower(s string) string {
b := []byte(s)
for i, c := range b {
if c >= 'A' && c <= 'Z' {
b[i] = c + 32
}
}
return string(b)
}package graph_test
import (
"fmt"
"testing"
"github.com/99designs/gqlgen/client"
"github.com/99designs/gqlgen/graphql/handler"
"academy/api-realization-rest-graphql/graph"
"academy/api-realization-rest-graphql/sales"
)
func setup(t *testing.T) (*client.Client, *sales.StaticCatalog) {
t.Helper()
n := 0
cat := &sales.StaticCatalog{Items: map[sales.SKU]sales.Product{
"SKU-1": {SKU: "SKU-1", Name: "Mug", UnitPriceMinor: 1250},
"SKU-2": {SKU: "SKU-2", Name: "Plate", UnitPriceMinor: 900},
}}
svc := &sales.Service{Orders: sales.NewMemoryOrders(), Cancels: sales.NewMemoryCancellations(),
Catalog: cat, Fulfilment: sales.NoopFulfilment{}, NewID: func() string { n++; return fmt.Sprint(n) }}
srv := handler.NewDefaultServer(graph.NewExecutableSchema(graph.Config{Resolvers: &graph.Resolver{Svc: svc}}))
return client.New(graph.Middleware(cat, srv)), cat
}
func TestOrdersWithProductsUseOneCatalogBatch(t *testing.T) {
c, cat := setup(t)
var created struct {
CreateDraftOrder struct{ Order struct{ ID string } }
}
var added struct {
AddOrderLine struct{ UserErrors []struct{ Code string } }
}
for range 3 {
c.MustPost(`mutation { createDraftOrder(input:{customerId:"c1", currency:"EUR"}) { order { id } } }`, &created)
for _, sku := range []string{"SKU-1", "SKU-2"} {
q := fmt.Sprintf(`mutation { addOrderLine(input:{orderId:%q, sku:%q, quantity:1}) { userErrors { code } } }`,
created.CreateDraftOrder.Order.ID, sku)
c.MustPost(q, &added)
}
}
cat.Calls = 0 // count only the read below (the writes priced lines already)
var resp struct {
Orders struct {
Edges []struct {
Node struct {
Lines []struct{ Product struct{ Name string } }
}
}
PageInfo struct{ HasNextPage bool }
}
}
c.MustPost(`{ orders(customerId:"c1", first:10) { edges { node { lines { product { name } } } } pageInfo { hasNextPage } } }`, &resp)
if len(resp.Orders.Edges) != 3 {
t.Fatalf("want 3 orders, got %d", len(resp.Orders.Edges))
}
if got := resp.Orders.Edges[0].Node.Lines[1].Product.Name; got != "Plate" {
t.Fatalf("product name %q", got)
}
if cat.Calls != 1 {
t.Fatalf("6 product fields must cost 1 catalog call, got %d", cat.Calls)
}
}
func TestBusinessFailureIsDataNotError(t *testing.T) {
c, _ := setup(t)
var created struct {
CreateDraftOrder struct{ Order struct{ ID string } }
}
c.MustPost(`mutation { createDraftOrder(input:{customerId:"c1", currency:"EUR"}) { order { id } } }`, &created)
var placed struct {
PlaceOrder struct {
Order *struct{ ID string }
UserErrors []struct{ Code, Message string }
}
}
q := fmt.Sprintf(`mutation { placeOrder(input:{orderId:%q, expectedVersion:1}) { order { id } userErrors { code message } } }`,
created.CreateDraftOrder.Order.ID)
if err := c.Post(q, &placed); err != nil {
t.Fatalf("a business rule must not be a GraphQL error: %v", err)
}
if placed.PlaceOrder.Order != nil || len(placed.PlaceOrder.UserErrors) != 1 || placed.PlaceOrder.UserErrors[0].Code != "ORDER_EMPTY" {
t.Fatalf("%+v", placed.PlaceOrder)
}
}The Go angle
net/httpplusServeMuxpatterns cover routing for most services; chi adds middleware groups andURLParam; both give youhttp.Handler.encoding/jsonwithDisallowUnknownFieldsandhttp.MaxBytesReaderis a one-line defence against sloppy clients and huge bodies.- Errors are values:
errors.Isagainst sentinel errors is the natural mapping layer to problem types. context.Contextcarries the per-request loaders and the caller's identity; nothing global.- Generated code (gqlgen, oapi-codegen) is checked in or generated in CI; the contract file is the input, and a drift fails the build.
Laravel
Laravel 13 / PHP 8.4. The controllers and resolvers depend on an OrderApplication interface (the same use cases as the Go Service); the real implementation behind it uses the repository from Repositories. Every PHP file was syntax-checked with php -l; the Laravel pieces were reviewed against the 13.x documentation, not run in an application.
Routes, scopes and exceptions
Sanctum token abilities act as scopes: the docs say tokens "may be granted abilities / scopes". The abilities middleware alias must be registered in bootstrap/app.php, where the exception rendering for Problem Details also lives (withExceptions with $exceptions->render(...)).
<?php
use App\Sales\Http\Controllers\CancellationRequestController;
use App\Sales\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;
// Every route needs a Sanctum token; scopes are the token abilities.
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function (): void {
Route::middleware('abilities:orders:read')->group(function (): void {
Route::get('/orders', [OrderController::class, 'index']);
Route::get('/orders/{order}', [OrderController::class, 'show']);
Route::get('/cancellation-requests/{id}', [CancellationRequestController::class, 'show']);
});
Route::middleware('abilities:orders:write')->group(function (): void {
Route::post('/orders', [OrderController::class, 'store']);
// Task-based endpoints: each command is a noun the business already uses.
Route::post('/orders/{order}/lines', [OrderController::class, 'addLine']);
Route::post('/orders/{order}/placement', [OrderController::class, 'place']);
Route::post('/orders/{order}/cancellation-requests', [CancellationRequestController::class, 'store']);
});
});<?php
use App\Sales\Application\SalesException;
use App\Sales\Http\ProblemDetails;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(api: __DIR__ . '/../routes/api.php')
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'abilities' => CheckAbilities::class,
'ability' => CheckForAnyAbility::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
// Every failure on /api becomes application/problem+json (RFC 9457).
$exceptions->render(fn (SalesException $e, Request $r) => ProblemDetails::fromFailure($e->failure, $r, $e->getMessage()));
$exceptions->render(fn (ValidationException $e, Request $r) => ProblemDetails::validation($e, $r));
})
->create();<?php
declare(strict_types=1);
namespace App\Sales\Http;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
/** Called from AppServiceProvider::boot(). Quotas per token, with a lower tier for writes. */
final class RateLimiting
{
public static function register(): void
{
RateLimiter::for('api', function (Request $request) {
$key = $request->user()?->currentAccessToken()?->id ?? $request->ip();
return $request->isMethodSafe()
? Limit::perMinute(600)->by("r:{$key}")
: Limit::perMinute(60)->by("w:{$key}");
});
}
}Resources, requests and controllers
An API resource is the DTO: OrderResource maps an OrderView (not an Eloquent model) to the published shape and adds the ETag in withResponse. Form requests validate input; ProblemDetails renders both domain failures and validation failures as application/problem+json.
<?php
declare(strict_types=1);
namespace App\Sales\Http\Resources;
use App\Sales\Application\OrderView;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @property OrderView $resource */
final class OrderResource extends JsonResource
{
public static $wrap = null; // no "data" envelope: the order IS the body
public function toArray(Request $request): array
{
$o = $this->resource;
$links = ['self' => ['href' => "/orders/{$o->id}"]];
// Links advertise only the transitions the state machine allows now.
if ($o->status === 'draft') {
$links['add-line'] = ['href' => "/orders/{$o->id}/lines", 'method' => 'POST'];
$links['placement'] = ['href' => "/orders/{$o->id}/placement", 'method' => 'POST'];
} elseif ($o->status === 'placed') {
$links['cancellation-requests'] = ['href' => "/orders/{$o->id}/cancellation-requests", 'method' => 'POST'];
}
return [
'id' => $o->id,
'customerId' => $o->customerId,
'status' => $o->status,
'lines' => array_map(fn ($l) => [
'sku' => $l->sku,
'quantity' => $l->quantity,
'unitPrice' => ['amountMinor' => $l->unitPriceMinor, 'currency' => $o->currency],
], $o->lines),
'total' => ['amountMinor' => $o->totalMinor, 'currency' => $o->currency],
'placedAt' => $o->placedAt?->format(DATE_ATOM),
'_links' => $links,
];
}
/** Weak ETag from the aggregate version; used for If-Match / If-None-Match. */
public function withResponse(Request $request, $response): void
{
$response->header('ETag', 'W/"' . $this->resource->version . '"');
}
}<?php
declare(strict_types=1);
namespace App\Sales\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
final class AddLineRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
// The client sends WHAT it wants; the price comes from Catalog, never from the client.
return [
'sku' => ['required', 'string'],
'quantity' => ['required', 'integer', 'min:1', 'max:50'],
];
}
}<?php
declare(strict_types=1);
namespace App\Sales\Http;
use App\Sales\Application\SalesFailure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
/** Builds RFC 9457 responses. The only place internal failures get public codes. */
final class ProblemDetails
{
private const BASE = 'https://api.example.com/problems/';
public static function fromFailure(SalesFailure $failure, Request $request, string $detail = ''): JsonResponse
{
[$status, $title] = match ($failure) {
SalesFailure::NotFound => [404, 'Resource not found'],
SalesFailure::OrderNotEditable => [409, 'Order is not editable'],
SalesFailure::OrderEmpty => [422, 'Order has no lines'],
SalesFailure::StaleVersion => [412, 'The order changed since you read it'],
SalesFailure::AlreadyCancelled => [409, 'Order cannot be cancelled'],
SalesFailure::UnknownProduct => [422, 'Your request is invalid'],
};
return self::make($request, $failure->value, $title, $status, $detail);
}
public static function validation(ValidationException $e, Request $request): JsonResponse
{
$errors = [];
foreach ($e->errors() as $field => $messages) {
foreach ($messages as $message) {
$errors[] = ['pointer' => '/' . str_replace('.', '/', $field), 'detail' => $message];
}
}
return self::make($request, 'validation-failed', 'Your request is invalid', 422, '', ['errors' => $errors]);
}
public static function make(
Request $request,
string $type,
string $title,
int $status,
string $detail = '',
array $extensions = [],
): JsonResponse {
$body = ['type' => self::BASE . $type, 'title' => $title, 'status' => $status];
if ($detail !== '') {
$body['detail'] = $detail;
}
$body['instance'] = '/' . ltrim($request->path(), '/');
return response()->json($body + $extensions, $status, ['Content-Type' => 'application/problem+json']);
}
}<?php
declare(strict_types=1);
namespace App\Sales\Http\Controllers;
use App\Sales\Application\OrderApplication;
use App\Sales\Application\OrderView;
use App\Sales\Application\SalesException;
use App\Sales\Application\SalesFailure;
use App\Sales\Http\ProblemDetails;
use App\Sales\Http\Requests\AddLineRequest;
use App\Sales\Http\Requests\CreateOrderRequest;
use App\Sales\Http\Resources\OrderResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
final class OrderController
{
public function __construct(private readonly OrderApplication $orders) {}
public function store(CreateOrderRequest $request): JsonResponse
{
$order = $this->orders->createDraft($request->string('customerId')->value(), $request->string('currency')->value());
return (new OrderResource($order))->response()->setStatusCode(201)->header('Location', "/orders/{$order->id}");
}
public function show(Request $request, string $order): JsonResponse|Response
{
$view = $this->owned($request, $order);
$etag = 'W/"' . $view->version . '"';
if ($request->header('If-None-Match') === $etag) {
return response('', 304)->header('ETag', $etag);
}
return (new OrderResource($view))->response()->header('Cache-Control', 'private, max-age=0, must-revalidate');
}
public function index(Request $request): JsonResponse
{
$limit = min(max((int) $request->query('limit', 20), 1), 100);
$after = $request->query('cursor') ? (int) base64_decode((string) $request->query('cursor'), true) : 0;
// Tenant isolation: the customer comes from the token, never from the query string.
$rows = $this->orders->list($request->user()->customer_id, $request->query('status'), $after, $limit + 1);
$more = count($rows) > $limit;
$rows = array_slice($rows, 0, $limit);
return response()->json(array_filter([
'items' => OrderResource::collection($rows)->resolve($request),
'nextCursor' => $more ? rtrim(strtr(base64_encode((string) end($rows)->seq), '+/', '-_'), '=') : null,
], fn ($v) => $v !== null));
}
public function addLine(AddLineRequest $request, string $order): JsonResponse
{
$this->owned($request, $order);
$expected = $this->version($request->header('If-Match'));
$view = $this->orders->addLine($order, $request->string('sku')->value(), $request->integer('quantity'), $expected);
return (new OrderResource($view))->response()->setStatusCode(201)
->header('Location', "/orders/{$order}/lines/" . $request->string('sku')->value());
}
/** Placement moves money: If-Match is mandatory (428 when missing). */
public function place(Request $request, string $order): JsonResponse
{
$this->owned($request, $order);
$expected = $this->version($request->header('If-Match'));
if ($expected === 0) {
return ProblemDetails::make($request, 'precondition-required', 'If-Match header is required', 428);
}
return (new OrderResource($this->orders->place($order, $expected)))->response();
}
/** 404, not 403: do not reveal that someone else's order exists. */
private function owned(Request $request, string $id): OrderView
{
$view = $this->orders->get($id);
if ($view->customerId !== $request->user()->customer_id) {
throw new SalesException(SalesFailure::NotFound);
}
return $view;
}
private function version(?string $header): int
{
return (int) trim(str_replace('W/', '', (string) $header), '" ');
}
}<?php
declare(strict_types=1);
namespace App\Sales\Http\Controllers;
use App\Sales\Application\OrderApplication;
use App\Sales\Application\SalesException;
use App\Sales\Application\SalesFailure;
use App\Sales\Http\Requests\RequestCancellationRequest;
use App\Sales\Http\Resources\CancellationRequestResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class CancellationRequestController
{
public function __construct(private readonly OrderApplication $orders) {}
/** 202 Accepted: the request is recorded; Fulfilment decides later. */
public function store(RequestCancellationRequest $request, string $order): JsonResponse
{
$this->assertOwner($request, $order);
$view = $this->orders->requestCancellation($order, $request->string('reason')->value(), $request->header('Idempotency-Key'));
return (new CancellationRequestResource($view))->response()->setStatusCode(202)
->header('Location', "/cancellation-requests/{$view->id}")
->header('Retry-After', '1');
}
public function show(Request $request, string $id): JsonResponse
{
$view = $this->orders->cancellation($id);
$this->assertOwner($request, $view->orderId);
return (new CancellationRequestResource($view))->response();
}
private function assertOwner(Request $request, string $orderId): void
{
if ($this->orders->get($orderId)->customerId !== $request->user()->customer_id) {
throw new SalesException(SalesFailure::NotFound);
}
}
}The application-layer contract the controllers use:
<?php
declare(strict_types=1);
namespace App\Sales\Application;
/**
* The use cases the API may call. Controllers and GraphQL resolvers depend on
* this interface only; they never touch the aggregate or Eloquent.
* Every method throws SalesException for a business failure.
*/
interface OrderApplication
{
public function createDraft(string $customerId, string $currency): OrderView;
public function get(string $orderId): OrderView;
/** @return list<OrderView> ordered by creation, strictly after $afterSeq */
public function list(string $customerId, ?string $status, int $afterSeq, int $limit): array;
/** $expectedVersion 0 means "do not check". */
public function addLine(string $orderId, string $sku, int $quantity, int $expectedVersion = 0): OrderView;
public function place(string $orderId, int $expectedVersion): OrderView;
/** Replaying the same $idempotencyKey returns the same request. */
public function requestCancellation(string $orderId, string $reason, ?string $idempotencyKey): CancellationView;
public function cancellation(string $requestId): CancellationView;
}GraphQL with Lighthouse
Lighthouse resolves Query.order to App\GraphQL\Queries\Order and Mutation.placeOrder to App\GraphQL\Mutations\PlaceOrder by naming convention, and calls __invoke. Directives add guards, throttles and validation to the schema.
"An ISO 8601 date-time such as 2026-11-25T09:30:00Z."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")
type Money {
amountMinor: Int!
currency: String!
}
enum OrderStatus { DRAFT PLACED CANCELLED }
enum CancellationState { PENDING COMPLETED REJECTED }
"Catalog's product, resolved through a batch loader."
type Product {
sku: ID!
name: String!
}
type OrderLine {
sku: ID!
quantity: Int!
unitPrice: Money!
product: Product! @field(resolver: "App\\GraphQL\\Resolvers\\OrderLineProduct")
}
type Order {
id: ID!
customerId: ID!
status: OrderStatus!
lines: [OrderLine!]!
total: Money!
placedAt: DateTime
"Bumped on every change; pass it back as expectedVersion."
version: Int!
}
type OrderEdge { cursor: String! node: Order! }
type PageInfo { hasNextPage: Boolean! endCursor: String }
type OrderConnection { edges: [OrderEdge!]! pageInfo: PageInfo! }
type CancellationRequest {
id: ID!
orderId: ID!
state: CancellationState!
reason: String!
detail: String
}
"A business problem the client can show; not a transport error."
type UserError { code: String! message: String! field: String }
type Query {
order(id: ID!): Order @guard(with: ["sanctum"])
orders(status: OrderStatus, first: Int = 20, after: String): OrderConnection! @guard(with: ["sanctum"])
cancellationRequest(id: ID!): CancellationRequest @guard(with: ["sanctum"])
}
input CreateDraftOrderInput { currency: String! @rules(apply: ["size:3"]) }
input AddOrderLineInput {
orderId: ID!
sku: ID!
quantity: Int! @rules(apply: ["min:1", "max:50"])
expectedVersion: Int
}
input PlaceOrderInput { orderId: ID! expectedVersion: Int! }
input RequestOrderCancellationInput {
orderId: ID!
reason: String!
idempotencyKey: String
}
type CreateDraftOrderPayload { order: Order userErrors: [UserError!]! }
type AddOrderLinePayload { order: Order userErrors: [UserError!]! }
type PlaceOrderPayload { order: Order userErrors: [UserError!]! }
type RequestOrderCancellationPayload { request: CancellationRequest userErrors: [UserError!]! }
type Mutation {
createDraftOrder(input: CreateDraftOrderInput!): CreateDraftOrderPayload! @guard(with: ["sanctum"]) @throttle(name: "api")
addOrderLine(input: AddOrderLineInput!): AddOrderLinePayload! @guard(with: ["sanctum"]) @throttle(name: "api")
placeOrder(input: PlaceOrderInput!): PlaceOrderPayload! @guard(with: ["sanctum"]) @throttle(name: "api")
requestOrderCancellation(input: RequestOrderCancellationInput!): RequestOrderCancellationPayload! @guard(with: ["sanctum"]) @throttle(name: "api")
}<?php
declare(strict_types=1);
namespace App\GraphQL\Mutations;
use App\GraphQL\Support\Presenter;
use App\Sales\Application\OrderApplication;
use App\Sales\Application\SalesException;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
final class PlaceOrder
{
public function __construct(private readonly OrderApplication $orders) {}
public function __invoke(null $root, array $args, GraphQLContext $context): array
{
$in = $args['input'];
try {
$order = $this->orders->place($in['orderId'], $in['expectedVersion']);
} catch (SalesException $e) {
return ['order' => null, 'userErrors' => [Presenter::userError($e)]];
}
return ['order' => Presenter::order($order), 'userErrors' => []];
}
}<?php
declare(strict_types=1);
namespace App\GraphQL\Queries;
use App\GraphQL\Support\Presenter;
use App\Sales\Application\OrderApplication;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
/** Relay-style connection, keyset-backed; the cursor is an opaque base64 sequence number. */
final class Orders
{
public function __construct(private readonly OrderApplication $orders) {}
public function __invoke(null $root, array $args, GraphQLContext $context): array
{
$first = min(max((int) ($args['first'] ?? 20), 1), 100);
$after = isset($args['after']) ? (int) base64_decode($args['after'], true) : 0;
$status = isset($args['status']) ? strtolower($args['status']) : null;
$rows = $this->orders->list($context->user()->customer_id, $status, $after, $first + 1);
$hasNext = count($rows) > $first;
$rows = array_slice($rows, 0, $first);
$edges = array_map(fn ($o) => ['cursor' => base64_encode((string) $o->seq), 'node' => Presenter::order($o)], $rows);
return [
'edges' => $edges,
'pageInfo' => ['hasNextPage' => $hasNext, 'endCursor' => $edges === [] ? null : end($edges)['cursor']],
];
}
}<?php
declare(strict_types=1);
namespace App\GraphQL\Resolvers;
use App\GraphQL\Loaders\ProductBatchLoader;
use GraphQL\Deferred;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Execution\BatchLoader\BatchLoaderRegistry;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
final class OrderLineProduct
{
/** @param array{sku: string} $line */
public function __invoke(array $line, array $args, GraphQLContext $context, ResolveInfo $info): Deferred
{
// Always returns the same loader for this path in this request.
$loader = BatchLoaderRegistry::instance(
$info->path,
fn (): ProductBatchLoader => app(ProductBatchLoader::class),
);
return $loader->load($line['sku']);
}
}<?php
declare(strict_types=1);
namespace App\GraphQL\Loaders;
use App\Catalog\ProductCatalog;
use GraphQL\Deferred;
/**
* Collects every SKU requested while one level of the query is resolved,
* then asks Catalog once. Lighthouse keeps one instance per query path
* (see BatchLoaderRegistry), and the registry is per request.
*/
final class ProductBatchLoader
{
/** @var array<string, true> */
private array $skus = [];
/** @var array<string, array{sku: string, name: string}>|null */
private ?array $results = null;
public function __construct(private readonly ProductCatalog $catalog) {}
public function load(string $sku): Deferred
{
$this->skus[$sku] = true;
return new Deferred(function () use ($sku): array {
// Runs after load() was called for every line in the response.
$this->results ??= $this->catalog->products(array_keys($this->skus));
return $this->results[$sku] ?? ['sku' => $sku, 'name' => '(unavailable)'];
});
}
}Tests
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Sales\Application\OrderApplication;
use App\Models\User;
use Laravel\Sanctum\Sanctum;
use Tests\Support\InMemoryOrderApplication;
use Tests\TestCase;
final class OrderApiTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$this->app->instance(OrderApplication::class, new InMemoryOrderApplication());
Sanctum::actingAs(new User(['customer_id' => 'c1']), ['orders:read', 'orders:write']);
}
public function test_lifecycle_uses_task_endpoints_and_problem_details(): void
{
$created = $this->postJson('/api/orders', ['customerId' => 'c1', 'currency' => 'EUR'])
->assertCreated()
->assertHeader('Location', '/orders/ord_1')
->assertHeader('ETag', 'W/"1"');
// Business rule: an empty order cannot be placed (422 problem+json, stable type).
$this->postJson('/api/orders/ord_1/placement', headers: ['If-Match' => 'W/"1"'])
->assertStatus(422)
->assertHeader('Content-Type', 'application/problem+json')
->assertJsonPath('type', 'https://api.example.com/problems/order-empty');
$this->postJson('/api/orders/ord_1/lines', ['sku' => 'SKU-1', 'quantity' => 2])
->assertCreated()
->assertJsonPath('total.amountMinor', 2500)
->assertJsonPath('_links.placement.method', 'POST');
$this->postJson('/api/orders/ord_1/placement')->assertStatus(428);
$this->postJson('/api/orders/ord_1/placement', headers: ['If-Match' => 'W/"1"'])->assertStatus(412);
$this->postJson('/api/orders/ord_1/placement', headers: ['If-Match' => 'W/"2"'])
->assertOk()
->assertJsonPath('status', 'placed');
$this->getJson('/api/orders/ord_1', ['If-None-Match' => 'W/"3"'])->assertStatus(304);
$this->postJson('/api/orders/ord_1/lines', ['sku' => 'SKU-1', 'quantity' => 1])
->assertStatus(409)
->assertJsonPath('type', 'https://api.example.com/problems/order-not-editable');
}
public function test_cancellation_is_accepted_not_done_and_idempotent(): void
{
$this->postJson('/api/orders', ['customerId' => 'c1', 'currency' => 'EUR']);
$first = $this->postJson('/api/orders/ord_1/cancellation-requests', ['reason' => 'late'], ['Idempotency-Key' => 'k1'])
->assertStatus(202)
->assertHeader('Retry-After', '1')
->assertJsonPath('state', 'pending');
$again = $this->postJson('/api/orders/ord_1/cancellation-requests', ['reason' => 'late'], ['Idempotency-Key' => 'k1']);
$this->assertSame($first->headers->get('Location'), $again->headers->get('Location'));
}
public function test_validation_failures_list_json_pointers(): void
{
$this->postJson('/api/orders', ['currency' => 'EU'])
->assertStatus(422)
->assertJsonPath('errors.0.pointer', '/customerId')
->assertJsonPath('errors.1.pointer', '/currency');
}
public function test_someone_elses_order_is_a_404(): void
{
$app = $this->app->make(OrderApplication::class);
$app->createDraft('someone-else', 'EUR');
$this->getJson('/api/orders/ord_1')->assertNotFound();
}
public function test_token_without_write_scope_is_forbidden(): void
{
Sanctum::actingAs(new User(['customer_id' => 'c1']), ['orders:read']);
$this->postJson('/api/orders', ['customerId' => 'c1', 'currency' => 'EUR'])->assertForbidden();
}
}<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Catalog\ProductCatalog;
use App\Models\User;
use App\Sales\Application\OrderApplication;
use Laravel\Sanctum\Sanctum;
use Nuwave\Lighthouse\Testing\MakesGraphQLRequests;
use Tests\Support\InMemoryOrderApplication;
use Tests\TestCase;
final class OrderGraphQlTest extends TestCase
{
use MakesGraphQLRequests;
public function test_six_product_fields_cost_one_catalog_call(): void
{
$catalog = new class implements ProductCatalog {
public int $calls = 0;
public function products(array $skus): array
{
$this->calls++;
return array_combine($skus, array_map(fn ($s) => ['sku' => $s, 'name' => "name of {$s}"], $skus));
}
};
$orders = new InMemoryOrderApplication(['SKU-1' => 1250, 'SKU-2' => 900]);
foreach (range(1, 3) as $i) {
$o = $orders->createDraft('c1', 'EUR');
$orders->addLine($o->id, 'SKU-1', 1);
$orders->addLine($o->id, 'SKU-2', 1);
}
$this->app->instance(OrderApplication::class, $orders);
$this->app->instance(ProductCatalog::class, $catalog);
Sanctum::actingAs(new User(['customer_id' => 'c1']), ['orders:read']);
$this->graphQL(/** @lang GraphQL */ '
{ orders(first: 10) { edges { node { lines { product { name } } } } pageInfo { hasNextPage } } }
')->assertJsonCount(3, 'data.orders.edges');
$this->assertSame(1, $catalog->calls);
}
public function test_business_failure_is_user_error_data(): void
{
$this->app->instance(OrderApplication::class, $orders = new InMemoryOrderApplication());
$orders->createDraft('c1', 'EUR');
Sanctum::actingAs(new User(['customer_id' => 'c1']), ['orders:write']);
$this->graphQL(/** @lang GraphQL */ '
mutation { placeOrder(input: {orderId: "ord_1", expectedVersion: 1}) { order { id } userErrors { code } } }
')->assertJsonPath('data.placeOrder.userErrors.0.code', 'ORDER_EMPTY')
->assertJsonMissingPath('errors');
}
}The Laravel angle
- API Resources (
JsonResource) are a ready-made DTO layer; keep them fed with application views, not with models, or the table leaks back in. - Form Requests validate and authorise before the controller runs; return Problem Details by rendering
ValidationExceptioninwithExceptions. - Sanctum tokens with abilities give scopes; per-resource ownership is still your code.
- Rate limiting is
RateLimiter::forplusthrottle:name; Lighthouse reuses the named limiter with@throttle(name: "api"). - Lighthouse is schema-first: directives generate most Eloquent resolvers, and custom resolvers are invokable classes. For non-Eloquent data, use
BatchLoaderRegistryand returnGraphQL\Deferred. - Versioning conventions are yours: route groups (
/v1), a header read in middleware, or none for GraphQL.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| Internal model leaks and freezes | DTO / API Resource per published shape | Map in one place; never serialise the aggregate | Refactor freely | A mapping layer to maintain |
| Clients skip business rules | Task-based commands | POST .../placement calls Order.Place | Rules in one place, better audit | More endpoints |
| Retry causes a second effect | Idempotency key | Unique (order_id, idem_key); replay the stored answer | Safe retries | Storage and expiry |
| Two users overwrite each other | ETag + If-Match, 428 on risky commands | Version from the aggregate | Standard lost-update defence | Clients must send the header |
| The answer is not ready | 202 + status resource | CancellationRequest record + worker | Honest, pollable, idempotent | Two-step client flow |
| Error handling differs per endpoint | RFC 9457 and one mapper | fromError / ProblemDetails | One client error handler | Type catalogue to govern |
| Offset pages skip rows | Keyset cursors | seq > $cursor ORDER BY seq LIMIT n+1 | Stable, fast | No random page jump |
| Breaking change needed | Additive first, then versions with Deprecation/Sunset | Run old and new, track usage | Planned retirement | Two code paths for a while |
| Contract drifts from code | Contract-first, lint, break check, provider tests | Spectral + oasdiff + Schemathesis in CI | Drift fails the build | CI time, rule upkeep |
| N+1 in GraphQL | Dataloader / eager loading | dataloadgen, BatchLoaderRegistry, @with | Constant calls per level | Per-request state |
| Someone reads another tenant's data | Ownership check, tenant from token | owned(), token claims | Closes the common hole | A check on every path |
| Unbounded GraphQL cost | Depth/complexity limits, pagination caps, persisted queries | Server config | Predictable load | Some queries refused |
| Many consumers need different shapes | GraphQL or BFF | Schema per context, composed above | Fewer endpoints | New operational surface |
Moving from table-shaped CRUD to a published language, step by step
Timeline: refactoring GET/PATCH /orders (a table gateway) into task-based endpoints
1 freeze write the current behaviour as an OpenAPI file; add contract tests that pin it
2 add POST /orders/{id}/placement next to PATCH status; both call Service.Place
3 guard PATCH status for placed now returns 409 order-not-editable (rule is in the aggregate)
4 announce mark PATCH status deprecated in the file; add Deprecation header; tell owners via keys
5 measure gateway analytics: callers of PATCH status per week
6 sunset add Sunset header; after the date answer 410 with a problem linking the migration guide
7 clean delete the PATCH route and the status field from the request schemaChoosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Few stable consumers, command-heavy, rules matter | REST, task-based | OpenAPI, ETag/If-Match, Problem Details | Commands and caching fit HTTP |
| Many clients with different views, mobile on slow links | GraphQL for reads (and thin mutations) | Dataloader, persisted queries, complexity limits | Client-shaped responses |
| Aggregating several contexts for one screen | BFF, optionally GraphQL or federation | Each context keeps its own OHS | Ownership stays with contexts |
| Internal service-to-service, strict types, streaming | gRPC | Protobuf with buf breaking checks | Compact, typed |
| Telling partners that something happened | Webhooks | HMAC signature, retries, delivery log | Push without polling |
| Integration between contexts that need decoupling | Events | Outbox, schema registry | Temporal decoupling |
| Public, cacheable catalogue data | REST + CDN | Cache-Control, ETag, Vary | HTTP caching works |
| Admin or settings screens, supporting subdomain | Plain CRUD | Generated from the contract | Cheap beats clever |
| Money, stock, identity | Task-based + idempotency + conditional | Scopes per command | One mistake costs more than the design time |
| Unknown future consumers | Published language first, additive changes only | Tolerant reader, open enums | Do not freeze the model |
| When GraphQL fits | When it does not |
|---|---|
| Many different clients and views | One or two consumers with fixed needs |
| Read-mostly with deep object graphs | Command-heavy, workflow-driven surface |
| Fast front-end iteration | Heavy HTTP caching and CDN needs |
| A BFF or router team that can own it | No capacity to operate query limits and tooling |
| Already have typed contexts to compose | Simple CRUD over a few tables |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One Laravel app (or one Go binary): routes, controllers, application services, aggregates, one database. The published language still exists: OrderResource and OrderView are the DTO layer, sales.openapi.yaml is the contract, and controllers never return $order. REST and GraphQL are two entry points that call the same Service, as cmd/server/main.go shows. Everyday example: the shop's own web and mobile apps call /orders and /graphql on the same host. The simplest correct usage: task-based endpoints, ETag on reads, Problem Details, keyset pagination, a contract test per rule.
Modular monolith and multiple databases
Each module (Sales, Fulfilment, Billing, Catalog, Identity) has a public interface and DTOs: the in-process Open Host Service and Published Language (Modular Monolith). Billing calls OrderApplication::get() and receives an OrderView, never Sales' entities. The HTTP API is a thin layer that composes module interfaces; with several databases, each module owns its schema and the API never joins across them (Data Ownership). The in-process contract is checked by architecture tests (deptrac in PHP, go vet import rules and internal packages in Go). The day a module is extracted, its interface becomes an HTTP or gRPC contract with the same shapes.
Microservices: one OHS per service
Sales, Fulfilment and Billing each publish their own API and their own events; every API has its own OpenAPI file, its own scopes and its own versioning policy. Billing is a conformist downstream of Sales' language, or builds an anticorruption layer where Sales' words do not fit (Context Maps). A gateway handles keys, quotas and routing; a web BFF aggregates Order from Sales and Product from Catalog.
Timeline: customer cancels a placed order (three services, one saga; see /messaging/saga-pattern)
1 web BFF POST sales/orders/o1/cancellation-requests (Idempotency-Key k1) -> 202 can_1
2 sales tx: insert can_1(pending) + outbox row OrderCancellationRequested
3 relay publishes OrderCancellationRequested
4 fulfilment consumes (inbox dedupe), releases picks -> publishes StockReleased | ReleaseRefused
5 billing consumes StockReleased -> refunds -> publishes RefundIssued
6 sales consumes RefundIssued -> order.Cancel(); can_1 = completed
7 web BFF GET sales/cancellation-requests/can_1 (poll) or receives webhook sales.order.cancelled.v1The client sees one 202 and one status resource; the saga, the outbox and the inboxes stay behind it (Saga, Outbox, Inbox).
Production examples. (1) Stripe's API documentation is a public example of idempotency as part of the contract: idempotency keys on POST requests, and "retries with the same key return the saved response". (2) Zalando publishes its API guidelines with "API First" as a principle, and its guidelines mention Problem JSON (RFC 9457) and the optional Idempotency-Key header. (3) Apollo documents federation as the way to compose subgraphs owned by different teams into one supergraph. These are documented facts about those sources; how any company applies them internally is not claimed here.
Distributed data: replicas, caches and multi-region
| Where it breaks | What the client sees | Defence in the API |
|---|---|---|
| Read replica lag | POST /orders returns 201, then GET /orders/o1 returns 404 | Return the full representation from the command; send reads that follow a write to the primary for a short window; or carry a "read-after" token (position) in a header |
| HTTP/CDN cache | A placed order still shows as draft | Cache-Control: private, max-age=0, must-revalidate plus ETag; Vary: Authorization on shared caches; never cache personal data publicly |
| GraphQL client cache | Two views of one order disagree | Global id, refetch the mutation payload's order, consistent version |
| Multi-region writes | Duplicate commands in two regions | Route each aggregate to one home region; idempotency keys in a store both can see |
| Webhook retries and reordering | The receiver sees sales.order.cancelled.v1 twice, or before sales.order.placed.v1 | Event ids, timestamps and sequence, idempotent receivers |
| Eventually consistent view across contexts | Order says placed, Billing says unpaid | Name it in the API (paymentStatus with a documented lag), or hide it behind a status resource |
See Replication, Read Replicas & Failover for the mechanics behind the first row, and Data Patterns for read-side replication.
Scaling path: 1x, 10x, 100x
| Load | Design | What changes |
|---|---|---|
| 1x: one team, a few clients | REST or GraphQL in the monolith, contract file in the repo | Lint and break-check in CI |
| 10x: many clients, partners | Gateway with keys and quotas, developer portal, conditional requests, CDN for public reads | Usage analytics per key; deprecation policy; webhooks with a delivery log |
| 100x: many teams, many contexts | Per-context OHS, BFFs per client type, federation or a router, schema registry and contract checks, regional gateways | Governance: ownership per type, review per change, SLOs per operation, cost limits on queries |
Lab: publish the Sales context twice
The commands run one Go process on the host: no Docker, no database. Output below was captured from a real run of cmd/server with ADDR=127.0.0.1:18080 (order and request ids are random; yours differ). The Laravel and tooling steps (7 to 9) are expected, not run.
# 0 from docs/snippets/ddd/api-realization-rest-graphql/go
go vet ./... && go test ./...
# expected: ok academy/api-realization-rest-graphql/graph, ok .../rest
ADDR=127.0.0.1:18080 go run ./cmd/server &
B=http://127.0.0.1:18080
# 1 create a draft: 201, Location and a weak ETag
curl -si -X POST $B/orders -d '{"customerId":"c1","currency":"EUR"}'
# HTTP/1.1 201 Created
# Etag: W/"1"
# Location: /orders/ord_040ed068dc188bad
# {"id":"ord_040e...","status":"draft","lines":[],"total":{"amountMinor":0,"currency":"EUR"},
# "_links":{"add-line":{...},"placement":{...},"self":{...}}}
ID=ord_040ed068dc188bad # use the id you got
# 2 add a line: price comes from Catalog; the version moves to 2
curl -si -X POST $B/orders/$ID/lines -d '{"sku":"SKU-1","quantity":2}'
# HTTP/1.1 201 Created Etag: W/"2" Location: /orders/ord_040e.../lines/SKU-1
# 3 place without the precondition, then with a stale one
curl -si -X POST $B/orders/$ID/placement
# HTTP/1.1 428 Precondition Required
# {"type":"https://api.example.com/problems/precondition-required","title":"If-Match header is required","status":428,...}
curl -si -X POST -H 'If-Match: W/"1"' $B/orders/$ID/placement
# HTTP/1.1 412 Precondition Failed
# {"type":".../problems/stale-representation","title":"The order changed since you read it","status":412,
# "detail":"Re-read the order and retry with the new ETag.",...}
# 4 place with the fresh tag
curl -si -X POST -H 'If-Match: W/"2"' $B/orders/$ID/placement
# HTTP/1.1 200 OK Etag: W/"3"
# 5 ask to cancel: 202 now, the worker finishes within about two seconds
curl -si -X POST -H 'Idempotency-Key: k1' $B/orders/$ID/cancellation-requests -d '{"reason":"changed my mind"}'
# HTTP/1.1 202 Accepted
# Location: /cancellation-requests/can_bf1e710e676cb50f
# Retry-After: 1
# {"id":"can_bf1e...","orderId":"ord_040e...","state":"pending","reason":"changed my mind",...}
# repeat with the same key: the same can_... is returned (replay, no second request)
# poll: GET $B/cancellation-requests/can_... -> "state":"pending", later "completed"
# 6 the same use cases through GraphQL
curl -s $B/graphql -H 'Content-Type: application/json' \
-d '{"query":"{ order(id:\"'$ID'\") { status version lines { product { name } } } }"}'
# {"data":{"order":{"status":"CANCELLED","version":4,"lines":[{"product":{"name":"Mug"}}]}}}
curl -s $B/graphql -H 'Content-Type: application/json' \
-d '{"query":"mutation { placeOrder(input:{orderId:\"'$ID'\", expectedVersion:1}) { order { id } userErrors { code message } } }"}'
# {"data":{"placeOrder":{"order":null,"userErrors":[{"code":"STALE_VERSION","message":"order changed since you read it"}]}}}
# 7 (expected, not run) Laravel: php artisan test --filter=OrderApiTest
# the five tests in OrderApiTest.php pass with the in-memory OrderApplication
# 8 (expected, not run) lint the contract
# npx @stoplight/spectral-cli lint openapi/sales.openapi.yaml --ruleset openapi/.spectral.yaml
# expected: no errors; delete the 'security' of one POST and the sales-commands-need-security rule fails
# 9 (expected, not run) breaking-change check
# oasdiff breaking old.yaml openapi/sales.openapi.yaml
# expected: adding a new required property to CreateOrder is reported as breaking; adding an optional one is notThings to notice: step 3 shows two preconditions refused with different statuses (428, 412) and stable type values; step 5 returns before the work is done; step 6 shows that the GraphQL business failure is a 200 with data, while the REST equivalent is a 412. The server is one process with in-memory stores, so there is no replication lag to observe: that part of Distributed data is explained, not run.
Common misconceptions
| Belief | Reality |
|---|---|
| REST means CRUD over tables | A resource is anything nameable; placement and cancellation-requests are resources |
| The API should mirror the aggregate | It mirrors the published language, which is smaller and steadier |
PATCH status is the RESTful way to change state | It hides the business intent and lets clients skip rules; commands as nouns keep the rules in the aggregate |
POST is always safe to retry | It is not idempotent by default; add an Idempotency-Key |
200 is fine for everything that worked | 201, 202, 204, 304 carry meaning that caches and clients act on |
The error type is just text | It is the machine key; messages may change, types may not |
| Level 3 hypermedia is mandatory | It pays when allowed actions depend on state or clients are unknown; otherwise level 2 is enough |
/v2/ solves versioning | Additive evolution and a retirement plan solve it; the URL is a label |
| GraphQL has no versions, so nothing can break | Removing or retyping a field breaks clients; use @deprecated and usage analytics |
GraphQL errors always go in errors | Business outcomes belong in the payload (userErrors); errors is for failures of the request |
| A dataloader fixes N+1 everywhere | It batches within one level of one request; you still need limits, caching and good batch queries |
| The gateway makes the service secure | It proves identity and enforces coarse policy; per-resource authorisation is the service's job |
| The generated OpenAPI file is the contract | Only a reviewed, linted, break-checked file is a contract |
| Federation gives every team one shared model | It composes models each context still owns |
| Webhooks are just POSTs | They need signatures, retries, ids, ordering rules and a delivery log |
Cheat sheet
| Topic | What to remember |
|---|---|
| API in DDD terms | Open Host Service plus Published Language of one context |
| What to expose | What consumers need and you can keep promising; not the aggregate |
| Resource | Any nameable thing; one aggregate may be several resources |
| Commands | Nouns for intents: /placement, /cancellation-requests, never PATCH status |
| Methods | GET safe; PUT/DELETE idempotent; POST needs a key |
| Concurrency | ETag on reads, If-Match on commands, 412 stale, 428 required |
| Errors | RFC 9457, stable type, errors[].pointer for validation |
| Async | 202 + Location + Retry-After + a status resource |
| Pagination | Keyset cursor, opaque, limit + 1 to know if there is a next page |
| Versioning | Add, do not change; Deprecation then Sunset; track consumers |
| Contract | OpenAPI first; Spectral lint; breaking-change check; provider tests |
| API management | Gateway for keys, quotas, routing, analytics; context for rules and ownership |
| GraphQL | Schema from the published model; input + payload + userErrors; connections |
| N+1 | Dataloader per request; results in key order; per-key errors |
| Security | Identity, scope, ownership, rate limit; tenant from the token; 404 not 403 |
| Tests | Handler tests, contract lint, break check, provider verification, consumer-driven contracts |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — In DDD terms, what are an Open Host Service and a Published Language, and how do they relate to your OpenAPI file? Important
Answer
Answer: The OHS is the open protocol a context offers to all consumers; the Published Language is the documented model of that protocol, kept separate from the internal model. The OpenAPI file (and GraphQL SDL, event schemas) is the written form of the published language.
2 — Why is json.Marshal(order) from a handler a design error even when the JSON looks right? Must-know
Answer
Answer: It publishes the aggregate's fields, so every refactor becomes a breaking change and private data can leak. Evans: an internal model used for interchange "essentially becomes frozen". Use a DTO per published shape.
3 — Give two reasons to prefer POST /orders/{id}/placement over PATCH /orders/{id} with a status field. Important
Answer
Answer: The rule lives in the aggregate behind a named command (clients cannot skip states); the audit and the authorisation (orders:write per command) speak the business language; new commands do not break old clients.
4 — A client's POST times out and it retries. How do you prevent a second cancellation request? Must-know
Answer
Answer: An Idempotency-Key stored with a unique constraint; the retry finds the key and returns the original 202 and Location.
5 — What do ETag, If-Match, 412 and 428 give you, and where do they map in the aggregate? Important
Answer
Answer: A lost-update defence over HTTP. The ETag carries the aggregate's version; If-Match makes the command conditional; 412 means the copy was stale; 428 means the server requires the header. The repository's compare-and-set on version is the same idea.
6 — When do you return 202 Accepted and what must the response contain? Must-know
Answer
Answer: When the work finishes later (Fulfilment must release stock). It should carry a Location to a status resource, a current status in the body, and ideally Retry-After. The client polls or receives a webhook.
7 — Why are keyset cursors preferred over ?page=7, and what does limit + 1 do? Important
Answer
Answer: Offsets skip or repeat rows under concurrent inserts and slow down for large offsets; keyset is stable and index-friendly. Fetching one extra row tells you whether a next page exists without a count query.
8 — Name three changes that are additive and three that break consumers. Must-know
Answer
Answer: Additive: new optional response field, new endpoint, new optional request field. Breaking: removing or renaming a field, tightening validation, adding a required request field (also changing a field's meaning).
9 — In GraphQL, where do you report "the order is already placed" and why? Important
Answer
Answer: In the mutation payload as userErrors { code message } with HTTP 200, because it is an expected business outcome the UI renders. The top-level errors array is for failures of the request itself.
10 — Six OrderLine.product fields are requested in one query. How many Catalog calls should happen, and what makes it so? Important
Answer
Answer: One. A per-request dataloader collects the keys and calls Catalog.Products once (dataloadgen in Go; BatchLoaderRegistry with Deferred in Lighthouse). The loader must be per request and return results in key order.
11 — What can an API gateway enforce, and what must the Sales service still check itself? Must-know
Answer
Answer: Gateway: keys, token validity, coarse scopes, quotas, routing, analytics. Service: that this order belongs to this customer, the aggregate's invariants, idempotency and error semantics.
12 — Which tests make breaking a promise to a consumer fail the build? Important
Answer
Answer: A Spectral lint of the contract, a breaking-change diff against the released contract, provider verification of the running server against the file, and consumer-driven contracts.
Glossary
| Term | Meaning |
|---|---|
| Open Host Service (OHS) | A context offers one open protocol to all consumers instead of per-consumer translators |
| Published Language (PL) | The documented, shared exchange model of that protocol, separate from the internal model |
| API | The runtime interface through which other software uses a context |
| Resource | A nameable piece of information with an identifier (URI) |
| Representation | The bytes that stand for a resource's state at a moment, in a media type |
| Aggregate | A consistency boundary in the domain model, protected by its root |
| DTO | Data transfer object: a shape made for the wire, not the domain |
| API Resource (Laravel) | A JsonResource class that maps data to the published JSON shape |
| Task-based API | Endpoints named after business commands rather than field updates |
| CRUD | Create, read, update, delete over data, without domain commands |
| Command | A request to change state, named as an intent |
| Safe method | A method that does not change state (GET, HEAD) |
| Idempotent | Repeating gives the same effect as one request |
| Idempotency-Key | A client-chosen key a server uses to recognise a retry of a POST |
| Status code | The HTTP result class and meaning (201, 202, 409, 412, 422, 428, 429) |
| ETag | A validator for a representation; here the aggregate version as a weak tag |
| If-Match | Request header making a command conditional on the current ETag |
| If-None-Match | Request header for revalidation; 304 if unchanged |
| 412 Precondition Failed | The condition (If-Match) did not hold |
| 428 Precondition Required | The server requires a conditional request |
| 202 Accepted | Received, not yet processed |
| Location | Header pointing to a created or monitoring resource |
| Retry-After | Header telling the client when to try again |
| Problem Details | RFC 9457 error format, application/problem+json |
| Problem type | The stable URI that names an error kind |
| JSON Pointer | A path into a JSON document, used in errors[].pointer |
| HATEOAS | Hypermedia as the engine of application state |
| Richardson Maturity Model | Fowler's four levels: tunnel, resources, verbs, hypermedia |
| HAL | A hypermedia JSON convention with _links and _embedded |
| JSON:API | A specification for resource objects, relationships, inclusion and paging |
| Keyset (cursor) pagination | Paging by "after this key" instead of by offset |
| Opaque cursor | A marker whose format clients must not parse |
| Link header | RFC 8288 header carrying rel="next" and other relations |
| Tolerant reader | A client that ignores unknown fields and values |
| Deprecation header | Signals that an API or version is no longer recommended |
| Sunset header | RFC 8594 header with the date a URI is likely to stop responding |
| Contract-first | Writing and reviewing the API description before the code |
| OpenAPI | The specification for describing HTTP APIs (3.1.0 used here) |
| Spectral | A linter that applies rulesets to OpenAPI and AsyncAPI files |
| oasdiff | A tool that compares OpenAPI files and reports breaking changes |
| Consumer-driven contract | Consumers state what they use; the provider must keep satisfying it (Pact) |
| API gateway | A reverse proxy in front of APIs that applies policy (Kong, Apigee) |
| Kong | An API gateway with plugins and a developer portal |
| Apigee | Google Cloud's API management platform |
| Developer portal | A site where consumers read docs and obtain keys |
| Quota / rate limit | A cap on calls per key and period; exceeded gives 429 |
| Sanctum | Laravel's token and SPA authentication package; tokens carry abilities |
| Scope / ability | A named permission carried by a token (orders:write) |
| Tenant isolation | Making sure a caller can reach only its own data |
| BOLA | Broken object-level authorization: reading others' objects by id |
| GraphQL | A typed query language and runtime for APIs |
| SDL | Schema definition language for GraphQL |
| Resolver | The function that produces one field's value |
| Input type | A GraphQL type used for arguments |
| Payload type | A mutation's return type, holding result and userErrors |
| userErrors | The payload field carrying business failures as data |
| Relay connection | edges, node, cursor, pageInfo pagination model |
| N+1 problem | One query for a list, then one more per item |
| Dataloader | A per-request batcher and cache for key lookups |
| Lighthouse | A schema-first GraphQL package for Laravel |
| gqlgen | A schema-first GraphQL code generator for Go |
| Federation | Composing subgraphs owned by different teams into a supergraph |
| Supergraph | The single composed graph of a federation |
| Schema stitching | Merging remote schemas at a gateway with explicit links |
| BFF | Backend for Frontend: an API owned by one client type |
| gRPC | A typed RPC framework over HTTP/2 with Protobuf contracts |
| Webhook | An HTTP callback an API sends to a consumer's URL |
| HMAC signature | A keyed hash proving a webhook came from the sender |
| AsyncAPI | The OpenAPI-like specification for event-driven APIs |
| Outbox | Storing events in the same transaction, delivered later by a relay |
References
All fetched with curl, saved under /private/tmp/claude-501/-Users-m-negahi-Projects-academy/da531b0a-541e-4005-be7e-84d5726fa12b/scratchpad/sources/api-realization-rest-graphql/, status 200 unless noted.
- Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures, chapter 5: REST, 2000. Saved:
fielding.txt - Martin Fowler, Richardson Maturity Model, 18 March 2010. Saved:
fowler-rmm.txt - Eric Evans, Domain-Driven Design Reference, 2015: Open Host Service, Published Language. Saved:
evans.txt - Vaughn Vernon, Implementing Domain-Driven Design, chapter 4 (architecture, RESTful integration): background only, not fetched, nothing quoted
- Zalando, RESTful API Guidelines: API First,
Idempotency-Key, Problem JSON. Saved:zalando.txt - Microsoft, Azure REST API Guidelines: long-running operations,
202-Accepted. Saved:msft.txt. (The older general guideline file now only redirects; saved asmsft-rest.txt.) - Google, AIP-121 Resource-oriented design, AIP-136 Custom methods, AIP-151 Long-running operations. Saved:
aip121.txt,aip136.txt,aip151.txt - OpenAPI Specification 3.1.0, 15 February 2021. Saved:
openapi31.txt - JSON:API v1.1. Saved:
jsonapi.txt - IETF, RFC 9457 Problem Details for HTTP APIs, July 2023; RFC 9110 HTTP Semantics (methods, 202, 422); RFC 6585 (428, 429); RFC 8594 The Sunset HTTP Header Field. Saved:
rfc9457.txt,rfc9110.txt,rfc6585.txt,rfc8594.txt. RFC 8288 (Linkheader) cited from knowledge, not fetched. - GraphQL specification, October 2021 edition; graphql.org Best Practices, Pagination, Schemas and Types; Relay Cursor Connections Specification. Saved:
graphql-spec.txt,gql-best.txt,gql-pagination.txt,gql-schema.txt,relay-conn.txt - Lighthouse docs on GitHub: N+1, Fields, Directives. Saved:
lighthouse-nplus1.txt,lighthouse-fields.txt,lighthouse-directives.txt - gqlgen, Dataloaders (v0.17.98 shown on the page). Saved:
gqlgen-dl.txt - Apollo, Federation overview. Saved:
apollo-fed.txt - Laravel 13 docs: Eloquent API Resources, Rate limiting, Sanctum, Error handling. Saved:
laravel-res.txt,laravel-rate.txt,laravel-sanctum.txt,laravel-errors.txt. The routing page was fetched but is a JavaScript shell (laravel-routing.txt, near-empty); no routing claim relies on it beyondRoute::middleware/groupusage. - Kong, Gateway documentation. Saved:
kong.txt. Apigee's documentation page returned 403 tocurl(apigee.txt, empty), so Apigee capabilities are listed from general product knowledge and nothing is quoted. - Stripe, Idempotent requests. Saved:
stripe-idem.txt - AsyncAPI concepts (page is JavaScript-heavy;
asyncapi.txtis a short extract) and Spectral docs (spectral.txt, JavaScript-rendered, near-empty): the ruleset syntax was written from knowledge of Spectral and not run. - Code in this chapter:
docs/snippets/ddd/api-realization-rest-graphql/(Go:go vetandgo testpass; PHP:php -lclean, Laravel and Lighthouse code reviewed, not run).