Skip to content

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 forGo to
The whole chapter in four tablesEverything in one minute
Why an API is more than a serialised modelWhy it exists
Fielding, Evans, Richardson, RFC 9457, GraphQLWhere it comes from
What the API is in DDD termsOHS and Published Language
A resource is not an aggregate and not a tableResource vs aggregate
POST /orders/{id}/placement vs PATCH statusTask-based vs CRUD
Methods, safe, idempotent, status codesHTTP semantics
ETag, If-Match, 304, 412, 428Conditional requests
Error bodiesProblem Details
202 + Location + status resourceEventual consistency in the API
Links, Richardson levels, JSON:APIHypermedia
Cursors, filters, sortPagination, filtering, sorting
Additive change, Sunset, DeprecationVersioning the published language
OpenAPI, Spectral, generated clientsContract-first
Keys, quotas, developer portalAPI management
SDL, types from the modelGraphQL schema
Mutations, input types, payloads, userErrorsGraphQL commands and errors
Relay connectionsGraphQL pagination
N+1, dataloader, Lighthouse, gqlgenN+1 and dataloader
Federation, BFFFederation and BFF
gRPC, webhooks, AsyncAPIOther realisations
authn, scopes, tenant isolationSecurity at the edge
Contract tests, Spectral, CDCTesting
Go and Laravel codeGo, Laravel
Per context and per serviceIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concept catalogue.

TermIn plain wordsTiny exampleWhat goes wrong without it
Open Host Service (OHS)One open protocol for everybody who integrates with the contextSales' HTTP APIA custom translator per consumer
Published Language (PL)The documented model of that protocol, separate from the internal modelOrder JSON, the OpenAPI fileThe internal model leaks and freezes
ResourceA named thing you can address and fetch a representation of/orders/o1Endpoints named after functions and tables
RepresentationThe bytes sent for a resource at a momentthe order JSON with ETagClients depend on storage columns
Task-based endpointA command named in the language of the businessPOST /orders/o1/placementPATCH status lets any client skip rules
IdempotentRepeating the request has the same effect as sending it oncePUT, DELETE, POST with Idempotency-KeyA retry charges twice
Conditional requestA request that only succeeds if the client's copy is currentIf-Match: W/"2"Lost updates over HTTP
Problem DetailsOne machine-readable error shapeapplication/problem+jsonEvery endpoint invents its own errors
Eventual consistency, surfacedThe API says "accepted, not done" and gives a place to watch202 + LocationClients believe a pending change is final
Keyset cursorAn opaque marker for the next pagenextCursorOffset pages skip or repeat rows
Contract-firstThe OpenAPI/SDL file is written and reviewed before the codesales.openapi.yamlThe contract is whatever the code happens to do
API gatewayThe front door: auth, quotas, routing, analyticsKong, ApigeeEvery service re-implements cross-cutting rules
GraphQL schemaThe typed published language for GraphQL clientstype Order { ... }Over- and under-fetching, or a schema that mirrors tables
DataloaderCollects keys during one level of execution and fetches them in one callProduct lookups per lineN+1 calls to Catalog

Two realisations of one language.

QuestionRESTGraphQL
Unit of the contractA resource and a methodA field in the type graph
Who shapes the responseThe server (representations)The client (selection set)
A command looks likePOST /orders/{id}/placementmutation { placeOrder(input: ...) }
Business failure409 / 422 with application/problem+jsonuserErrors in the payload, HTTP 200
CachingHTTP caches, ETag, 304Client cache by id, persisted queries, CDN is harder
Paginglimit + cursorfirst + after connection
Best atFew, stable consumers; commands; cacheable readsMany clients, varied views, aggregation across contexts
Biggest trapCRUD over tablesN+1 and unbounded queries

The HTTP contract in one table (every row is unpacked in HTTP semantics and Mechanics).

SituationStatusHeader or body to add
Created a draft201 CreatedLocation, ETag
Read, unchanged304 Not ModifiedETag
Command accepted, work continues202 AcceptedLocation, Retry-After
Business rule says no, state conflict409 ConflictProblem type
Input is well-formed but invalid422 Unprocessable Contenterrors[].pointer
Stale copy412 Precondition FailedProblem type
Conditional header missing428 Precondition RequiredProblem type
Too many requests429 Too Many RequestsRetry-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 directlyPublish a language
Fast to build: serialise the entityNeeds a mapping layer and a contract file
Every refactor breaks a consumerRefactors stay behind the mapping
Table and class names become public wordsPublic words come from the ubiquitous language
Rules can be bypassed (PATCH status)Rules sit behind named commands
One consumer's need shapes everyone's APIThe 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 ​

  1. "REST means CRUD over tables." Fielding's resource is "any information that can be named", not a row. A placement or a cancellation-request is a perfectly good resource (see Resource vs aggregate).
  2. "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).
  3. "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 ​

YearSourceWhat it gave this chapter
2000Roy Fielding, dissertation chapter 5, Representational State TransferThe four interface constraints, resources and representations
2003Eric Evans, Domain-Driven DesignOpen Host Service, Published Language (summarised in the free 2015 DDD Reference)
2010Martin Fowler, Richardson Maturity Model (18 March 2010)Levels 0 to 3: resources, verbs, hypermedia
2013Vaughn Vernon, Implementing DDD, chapter 4Architecture of a bounded context, RESTful integration of contexts (book, not fetched; nothing quoted)
2012 / 2015GraphQL "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
2021OpenAPI Specification 3.1.0 (15 February 2021)JSON Schema 2020-12 alignment, the contract format
2023RFC 9457 Problem Details for HTTP APIs (July 2023; obsoletes RFC 7807)One error format
ongoingZalando, Microsoft and Google API guidelinesPractical 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.
Sales context (private)Order aggregateinvariants, state machineApplication servicesplace, cancel, add lineTables, ORM, eventsfree to change weeklyPublished languagesmaller than the model, stableResources + commandsorder, line, placementContract documentsOpenAPI, SDL, schemasOpen Host Service owns it,semantic versioningREST APIresources, HTTP verbsETag, 202, Problemcacheable readsGraphQL APIone schema, many viewspayload + userErrorsdataloader batchingAPI gatewayauth, quotas, keysrouting, analyticsConsumersweb, mobile, partnersBilling, Fulfilment(if they call at all)translaterealiserealiseThe API is shaped by what consumers need to know, not by how Sales stores it.

Three consequences drive every later section.

  1. 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.
  2. 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.
  3. 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.
LayerOwnsChanges when
Domain model (Order)Invariants, state machineThe business rule changes
Application service (Service)Use cases, transactions, portsA use case changes
Published language (OpenAPI + SDL)Resources, commands, errors, scopesA consumer-visible promise changes (rare, versioned)
Realisation (handlers, resolvers)HTTP and GraphQL mechanicsThe transport changes
GatewayKeys, quotas, routing, analyticsPolicy 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 -> private

Real 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:

MechanismRoleWhere in this chapter
DTO / API ResourceThe mapping layer, one class per published shapeOrderDTO in Go, OrderResource in Laravel
OpenAPI / SDLThe written contractContract-first
Errors catalogueStable problem types and codesProblem Details
ScopesWho may do whatSecurity at the edge
Versioning policyWhat may change without a new versionVersioning

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."

Aggregate (inside Sales)Order (root)status, customer, currencyOrderLine (entity)Never publishedpricing rule, row version, auditResources (the published language)GET /orders/{id}a representation of the order, with ETagPOST /orders/{id}/linessub-resource collection, price from CatalogPOST /orders/{id}/placementa command named as a noun; If-Match requiredPOST /orders/{id}/cancellation-requestscreates a status resource, answers 202GET /cancellation-requests/{id}no aggregate behind it: a workflow recordOne aggregate, several resources.Some resources have no aggregate.Nothing here is a table name.
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 filters

Real 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.

go
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
AspectCRUD over fieldsTask-based
RulesIn clients or in a hidden validatorIn the aggregate behind a named method
Audit"status changed""order placed by customer c1"
EvolutionNew states break every clientNew command = new URI, old ones stay
AuthorisationPer field, awkwardPer command and scope: orders:write
DiscoverabilityRead the docsLinks advertise allowed commands (see Hypermedia)
FitAdmin tools, settings, simple lookup dataCore 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.

MethodSafeIdempotentCacheableTypical use in this API
GETyesyesyesread an order, list, poll status
HEADyesyesyesexistence and ETag check
PUTnoyesnoreplace a whole representation (e.g. customer profile)
DELETEnoyesnoremove a draft
PATCHnonot guaranteednopartial update of plain data, not state transitions
POSTnonorarelycommands, 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
HeaderDirectionMeaningOur choice
ETag: W/"3"responseWeak validator = aggregate versionon every order representation
If-None-Matchrequest on GETRevalidate304 with no body
If-Matchrequest on commandsConditional commandoptional on add-line, required on placement
Cache-Control: private, max-age=0, must-revalidateresponseForce revalidation, never shareorder 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"} ] }
FailureStatustype suffix (published)Source in the domain
Unknown id404not-foundErrNotFound
Placed order edited409order-not-editableErrNotDraft
Place with no lines422order-emptyErrEmptyOrder
Bad input422validation-failedrequest validation
Stale If-Match412stale-representationErrVersionConflict
Missing If-Match428precondition-requiredhandler
Cancel a cancelled order409order-not-cancellableErrAlreadyCancelled
Anything else500about:blanklogged, 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.

go
// 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."

ClientSales APIWorkerFulfilmentPOST /orders/o1/cancellation-requestsIdempotency-Key: k1202 Accepted, Location, Retry-After: 1state: pendingenqueuerelease stockreleasedcancel order, request completedGET /cancellation-requests/can_1200 pending (not yet)state change visibleGET /cancellation-requests/can_1200 completed, link to orderAlternative to polling: webhook sales.order.cancelled.v1 to the client's endpoint.
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 clientGood forCost
Poll the status resourceSimple clients, short waitsWasted requests; honour Retry-After
Webhook to a client URLServer-to-server, partnersSigning, retries, a delivery log (see Webhooks)
GraphQL subscription / SSELive UIsA long-lived connection to operate
Synchronous wait up to N seconds, else 202Mostly-fast operationsTwo 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)IdeaExample here
0One endpoint, tunnelling (RPC over HTTP)POST /api with an operation name
1Resources/orders/o1
2HTTP verbs and status codesPOST creates 201, conflict 409, GET cacheable
3Hypermedia 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.

FormatWhat it standardisesUse when
Plain JSON + _links (this chapter)Nothing, a local conventionSmall, explicit needs
HAL_links, _embeddedLink-heavy REST with tooling
JSON:APIResource objects, relationships, include, sparse fieldsets, pagination linksYou want a ready convention and clients such as Ember Data
Siren, HydraActions and forms in the responseFully 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).

ConventionRequestResponseNotes
Keyset cursor (ours)?limit=20&cursor=Mgitems, nextCursorOpaque, stable under inserts
Link headersameLink: <...>; rel="next"RFC 8288; good for generic clients
Offset?offset=40&limit=20items, totalOnly for small, rarely-changing lists
GraphQL connectionfirst, afteredges { cursor node }, pageInfoSee GraphQL pagination
ParameterRule
FiltersNamed after the ubiquitous language: status=placed, customerId=...; unknown filters are 400, not ignored
Sortsort=-placedAt,id with a documented whitelist and a unique tiebreaker so cursors are stable
LimitsA default and a hard maximum (limit 20, max 100) in the contract
CursorOpaque to clients (base64 of the keyset); format may change without a version
TenantApplied by the server from the token, never from the query string
sql
-- 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 exists

Versioning 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.

ChangeBreaking?Rule
New optional response fieldnoClients must ignore unknown fields (tolerant reader)
New optional request fieldnoDefault to old behaviour
New endpoint or commandnoOld ones stay
New enum value in a responseyes for strict clientsDocument that enums are open; or add a new field
Remove or rename a fieldyesNew version, or add the new name first and keep the old one
Tighten validationyesNew version
Change meaning of a fieldyesNever reuse a name for a new meaning
New required request fieldyesNew version
StyleExampleProCon
URI/v2/ordersVisible, easy to route at the gatewayVersion is part of every link
HeaderSales-Version: 2026-11-01Clean URIs, date versionsHidden; harder to try in a browser
Media typeAccept: application/vnd.sales.order.v2+jsonPer-representation versionTooling and caching complexity
None (GraphQL)additive changes plus @deprecatedOne graphNeeds 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 guide

Contract-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."

StepWhat happensTool
1 DesignWrite sales.openapi.yaml from the published languageAn editor, Stoplight, Swagger Editor
2 LintStyle and policy rules fail the buildSpectral with a team ruleset
3 ReviewConsumers and the platform team comment on the diffPull request
4 Break checkCompare to the released contract; fail on breaking changesoasdiff, openapi-diff
5 GenerateClients and server stubs/types from the fileopenapi-generator, oapi-codegen (Go), Laravel packages
6 VerifyRun the real server against the contractSchemathesis, Dredd, Prism (mock)
7 PublishDocs on the developer portalRedoc, Swagger UI
yaml
# 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' }
yaml
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.

yaml
# 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".

CapabilityWhat it doesProducts
AuthenticationAPI keys, OAuth 2.0 / OIDC token validation, mTLSKong plugins, Apigee policies, AWS API Gateway authorizers
Quotas and rate limitsPer key, per plan, per routeKong Rate Limiting, Apigee Quota, Laravel RateLimiter at the app
Routing and transformationPath and version routing, header rewritingKong routes, Apigee proxies, Envoy
AnalyticsWho calls what, error rates, latencyKong Konnect, Apigee Analytics
Developer portalDocs, sign-up, key issuingKong Dev Portal, Apigee integrated portal
MonetisationPlans, billing per callApigee monetisation, plan-based quotas
LifecycleDeprecation notices, version retirementPortal 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.

WhereRightWrong
GatewayKey check, coarse scope, quota, TLS, request size, routing by versionComputing totals, state transitions
ContextOwnership checks, invariants, idempotency, error semanticsPer-plan billing logic
BothRate 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 metrics

GraphQL: 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.

RuleWhyIn our schema
Types come from the published modelThe schema survives storage changesOrder, OrderLine, Money, not orders_row
Value objects become typesMoney is {amountMinor, currency}, never a bare floattype Money
Enums for statesClients cannot invent statesOrderStatus, CancellationState
Cross-context data is a type owned by that contextCatalog owns ProductOrderLine.product resolved by loader
Nullable by intentNon-null where the contract guarantees it, nullable where absence is normalplacedAt: DateTime
Documentation stringsThe schema is the docs"""...""" on every type
Deprecate, do not deleteEvolve without versions@deprecated(reason: "...")

The full SDL (gqlgen flavour; Lighthouse's has the same types with directives):

graphql
"""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 ruleReason
Name mutations after commands: placeOrder, requestOrderCancellationSame task-based vocabulary as REST
One input argument of an input typeEvolvable: 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 errorsThey are bugs or outages, not outcomes
Concurrency token as input: expectedVersionGraphQL has no If-Match; the idea is the same
Idempotency as input: idempotencyKeyThere is no Idempotency-Key header convention
null for a missing node on queriesorder(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 2

Fix: 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".

PieceMeaningSource
first, afterSlice forward: first N after this cursorCursor Connections Specification
edges { cursor node }The cursor belongs to the edge, not the nodesame
pageInfo { hasNextPage endCursor }Tells the client when to stopsame
Opaque cursorFormat may changesame

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
StackMechanismPer-request scope
Go gqlgendataloadgen.Loader created in HTTP middleware, WithWait(2ms)Middleware puts a new Loaders in the context
Laravel Lighthouse (Eloquent relations)@belongsTo, @hasMany, @with batch relation queriesBuilt in
Laravel Lighthouse (external data)BatchLoaderRegistry::instance($info->path, ...) returning GraphQL\DeferredOne 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".

go
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.

ApproachIdeaFit
Schema stitchingA gateway merges remote schemas with hand-written linksSmall, few schemas; you own the glue
Apollo FederationSubgraphs declare entities and keys; a router composes a supergraphMany 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 APIsWeb and mobile need different aggregates; keeps GraphQL out of the contexts
Direct per-context schemasEach context exposes its own GraphQL; clients call severalFew 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.

RealisationFitsContract formatPointer
gRPCService-to-service calls with strict types, streaming, low latency.protogRPC & Protobuf
WebhookTelling an external system that something happenedJSON Schema + signature schemebelow
Message / eventAsync integration, fan-outAsyncAPI, JSON Schema, Avro/ProtobufDomain Events vs Integration Events, Outbox Pattern
Server-Sent Events / GraphQL subscriptionLive UIsSDL / event streamGraphQL

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).

QuestionMechanismExample
Who is calling?OAuth 2.0 / OIDC access token, Sanctum token, mTLS for service-to-serviceauth:sanctum
What may they do?Scopes / abilities on the tokenabilities: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 resourceowned() in the controller returns 404 for others' orders
How much?Rate limiting per token and per routeRateLimiter::for('api', ...), throttle:api, Lighthouse @throttle
What shape?Body size limits, strict JSON (DisallowUnknownFields), max query depth/complexity in GraphQLhttp.MaxBytesReader, Lighthouse depth/complexity limits

Rules that save real incidents:

  1. Tenant from the token, not from the request. GET /orders?customerId=c9 must not let c1 read c9's orders; the Laravel list ignores any client-supplied customer, and the GraphQL createDraftOrder takes the customer from the token.
  2. 404, not 403, for other people's resources, unless existence is public information.
  3. Scopes per command, not per endpoint family: orders:read and orders:write.
  4. GraphQL has one endpoint, so authorisation moves to fields and resolvers. Lighthouse's @guard "does not log in users" by itself: add the AttemptAuthentication middleware, then guard fields or whole root types.
  5. Never return stack traces; the problem type is enough (see Problem Details).
  6. 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.

LayerWhat it checksTool here
Handler testStatus, headers, body, problem type for each ruleGo httptest, Laravel postJson
Contract lintThe OpenAPI file follows house rulesSpectral ruleset
Breaking-change checkNew file vs released fileoasdiff in CI
Provider verificationReal server responses conform to the fileSchemathesis, Dredd, Prism
Consumer-driven contractEach consumer states what it uses; provider must satisfy allPact
Schema checks (GraphQL)Operations in use still validate against the new schemaGraphQL Inspector, Apollo schema checks
Load and abuseRate limits answer 429, big bodies are refusedk6, 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+json

Status code and header reference Must-know ​

CodeNameWhen this API sends itRetry?
200OKRead, command that finishedn/a
201CreatedDraft or line created; Location setno
202AcceptedCancellation request recordedpoll Location
204No ContentDelete of a draft (not used in the snippet)no
304Not ModifiedIf-None-Match matchedn/a
400Bad RequestMalformed JSON, unknown field, bad cursorno, fix the request
401UnauthorizedMissing or invalid tokenafter re-auth
403ForbiddenToken lacks the scopeno
404Not FoundUnknown id, or somebody else's resourceno
409ConflictState does not allow the commandafter the state changes
412Precondition FailedStale If-Matchre-read, then retry
422Unprocessable ContentWell-formed but invalid, or business rule on contentno, fix the data
428Precondition RequiredIf-Match missing on placementadd the header
429Too Many RequestsRate limit; Retry-Afteryes, after the delay
500Internal Server ErrorBug; logged, problem about:blankwith backoff, idempotent only
503Service UnavailableOverload or dependency down; Retry-Afterwith 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 ​

sql
-- 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 ​

AspectRule
EndpointOne path, /graphql, usually POST with {"query", "variables", "operationName"}
Status200 even for field errors; 400 for unparsable or invalid documents; 401/403 from the transport
ExecutionFields of a query may resolve in parallel; top-level mutation fields run serially
BatchingA loader batches inside one operation; request batching merges operations (avoid unless needed)
CachingPOST is not cached by HTTP caches; use persisted queries with GET or a client cache keyed by id
IntrospectionConvenient in development; restrict in production for public APIs
LimitsDepth, 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.

go
// 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...) }
go
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").

go
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:

go
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.

yml
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: true
go
package 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 }
)
go
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)
}
go
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/http plus ServeMux patterns cover routing for most services; chi adds middleware groups and URLParam; both give you http.Handler.
  • encoding/json with DisallowUnknownFields and http.MaxBytesReader is a one-line defence against sloppy clients and huge bodies.
  • Errors are values: errors.Is against sentinel errors is the natural mapping layer to problem types.
  • context.Context carries 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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.

graphql
"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
<?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
<?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
<?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
<?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
<?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
<?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 ValidationException in withExceptions.
  • Sanctum tokens with abilities give scopes; per-resource ownership is still your code.
  • Rate limiting is RateLimiter::for plus throttle: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 BatchLoaderRegistry and return GraphQL\Deferred.
  • Versioning conventions are yours: route groups (/v1), a header read in middleware, or none for GraphQL.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limit
Internal model leaks and freezesDTO / API Resource per published shapeMap in one place; never serialise the aggregateRefactor freelyA mapping layer to maintain
Clients skip business rulesTask-based commandsPOST .../placement calls Order.PlaceRules in one place, better auditMore endpoints
Retry causes a second effectIdempotency keyUnique (order_id, idem_key); replay the stored answerSafe retriesStorage and expiry
Two users overwrite each otherETag + If-Match, 428 on risky commandsVersion from the aggregateStandard lost-update defenceClients must send the header
The answer is not ready202 + status resourceCancellationRequest record + workerHonest, pollable, idempotentTwo-step client flow
Error handling differs per endpointRFC 9457 and one mapperfromError / ProblemDetailsOne client error handlerType catalogue to govern
Offset pages skip rowsKeyset cursorsseq > $cursor ORDER BY seq LIMIT n+1Stable, fastNo random page jump
Breaking change neededAdditive first, then versions with Deprecation/SunsetRun old and new, track usagePlanned retirementTwo code paths for a while
Contract drifts from codeContract-first, lint, break check, provider testsSpectral + oasdiff + Schemathesis in CIDrift fails the buildCI time, rule upkeep
N+1 in GraphQLDataloader / eager loadingdataloadgen, BatchLoaderRegistry, @withConstant calls per levelPer-request state
Someone reads another tenant's dataOwnership check, tenant from tokenowned(), token claimsCloses the common holeA check on every path
Unbounded GraphQL costDepth/complexity limits, pagination caps, persisted queriesServer configPredictable loadSome queries refused
Many consumers need different shapesGraphQL or BFFSchema per context, composed aboveFewer endpointsNew 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 schema

Choosing ​

SituationRecommendationExtra techniqueReason
Few stable consumers, command-heavy, rules matterREST, task-basedOpenAPI, ETag/If-Match, Problem DetailsCommands and caching fit HTTP
Many clients with different views, mobile on slow linksGraphQL for reads (and thin mutations)Dataloader, persisted queries, complexity limitsClient-shaped responses
Aggregating several contexts for one screenBFF, optionally GraphQL or federationEach context keeps its own OHSOwnership stays with contexts
Internal service-to-service, strict types, streaminggRPCProtobuf with buf breaking checksCompact, typed
Telling partners that something happenedWebhooksHMAC signature, retries, delivery logPush without polling
Integration between contexts that need decouplingEventsOutbox, schema registryTemporal decoupling
Public, cacheable catalogue dataREST + CDNCache-Control, ETag, VaryHTTP caching works
Admin or settings screens, supporting subdomainPlain CRUDGenerated from the contractCheap beats clever
Money, stock, identityTask-based + idempotency + conditionalScopes per commandOne mistake costs more than the design time
Unknown future consumersPublished language first, additive changes onlyTolerant reader, open enumsDo not freeze the model
When GraphQL fitsWhen it does not
Many different clients and viewsOne or two consumers with fixed needs
Read-mostly with deep object graphsCommand-heavy, workflow-driven surface
Fast front-end iterationHeavy HTTP caching and CDN needs
A BFF or router team that can own itNo capacity to operate query limits and tooling
Already have typed contexts to composeSimple 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.v1

The 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 breaksWhat the client seesDefence in the API
Read replica lagPOST /orders returns 201, then GET /orders/o1 returns 404Return 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 cacheA placed order still shows as draftCache-Control: private, max-age=0, must-revalidate plus ETag; Vary: Authorization on shared caches; never cache personal data publicly
GraphQL client cacheTwo views of one order disagreeGlobal id, refetch the mutation payload's order, consistent version
Multi-region writesDuplicate commands in two regionsRoute each aggregate to one home region; idempotency keys in a store both can see
Webhook retries and reorderingThe receiver sees sales.order.cancelled.v1 twice, or before sales.order.placed.v1Event ids, timestamps and sequence, idempotent receivers
Eventually consistent view across contextsOrder says placed, Billing says unpaidName 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 ​

LoadDesignWhat changes
1x: one team, a few clientsREST or GraphQL in the monolith, contract file in the repoLint and break-check in CI
10x: many clients, partnersGateway with keys and quotas, developer portal, conditional requests, CDN for public readsUsage analytics per key; deprecation policy; webhooks with a delivery log
100x: many teams, many contextsPer-context OHS, BFFs per client type, federation or a router, schema registry and contract checks, regional gatewaysGovernance: 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 not

Things 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 ​

BeliefReality
REST means CRUD over tablesA resource is anything nameable; placement and cancellation-requests are resources
The API should mirror the aggregateIt mirrors the published language, which is smaller and steadier
PATCH status is the RESTful way to change stateIt hides the business intent and lets clients skip rules; commands as nouns keep the rules in the aggregate
POST is always safe to retryIt is not idempotent by default; add an Idempotency-Key
200 is fine for everything that worked201, 202, 204, 304 carry meaning that caches and clients act on
The error type is just textIt is the machine key; messages may change, types may not
Level 3 hypermedia is mandatoryIt pays when allowed actions depend on state or clients are unknown; otherwise level 2 is enough
/v2/ solves versioningAdditive evolution and a retirement plan solve it; the URL is a label
GraphQL has no versions, so nothing can breakRemoving or retyping a field breaks clients; use @deprecated and usage analytics
GraphQL errors always go in errorsBusiness outcomes belong in the payload (userErrors); errors is for failures of the request
A dataloader fixes N+1 everywhereIt batches within one level of one request; you still need limits, caching and good batch queries
The gateway makes the service secureIt proves identity and enforces coarse policy; per-resource authorisation is the service's job
The generated OpenAPI file is the contractOnly a reviewed, linted, break-checked file is a contract
Federation gives every team one shared modelIt composes models each context still owns
Webhooks are just POSTsThey need signatures, retries, ids, ordering rules and a delivery log

Cheat sheet ​

TopicWhat to remember
API in DDD termsOpen Host Service plus Published Language of one context
What to exposeWhat consumers need and you can keep promising; not the aggregate
ResourceAny nameable thing; one aggregate may be several resources
CommandsNouns for intents: /placement, /cancellation-requests, never PATCH status
MethodsGET safe; PUT/DELETE idempotent; POST needs a key
ConcurrencyETag on reads, If-Match on commands, 412 stale, 428 required
ErrorsRFC 9457, stable type, errors[].pointer for validation
Async202 + Location + Retry-After + a status resource
PaginationKeyset cursor, opaque, limit + 1 to know if there is a next page
VersioningAdd, do not change; Deprecation then Sunset; track consumers
ContractOpenAPI first; Spectral lint; breaking-change check; provider tests
API managementGateway for keys, quotas, routing, analytics; context for rules and ownership
GraphQLSchema from the published model; input + payload + userErrors; connections
N+1Dataloader per request; results in key order; per-key errors
SecurityIdentity, scope, ownership, rate limit; tenant from the token; 404 not 403
TestsHandler tests, contract lint, break check, provider verification, consumer-driven contracts

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
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
APIThe runtime interface through which other software uses a context
ResourceA nameable piece of information with an identifier (URI)
RepresentationThe bytes that stand for a resource's state at a moment, in a media type
AggregateA consistency boundary in the domain model, protected by its root
DTOData 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 APIEndpoints named after business commands rather than field updates
CRUDCreate, read, update, delete over data, without domain commands
CommandA request to change state, named as an intent
Safe methodA method that does not change state (GET, HEAD)
IdempotentRepeating gives the same effect as one request
Idempotency-KeyA client-chosen key a server uses to recognise a retry of a POST
Status codeThe HTTP result class and meaning (201, 202, 409, 412, 422, 428, 429)
ETagA validator for a representation; here the aggregate version as a weak tag
If-MatchRequest header making a command conditional on the current ETag
If-None-MatchRequest header for revalidation; 304 if unchanged
412 Precondition FailedThe condition (If-Match) did not hold
428 Precondition RequiredThe server requires a conditional request
202 AcceptedReceived, not yet processed
LocationHeader pointing to a created or monitoring resource
Retry-AfterHeader telling the client when to try again
Problem DetailsRFC 9457 error format, application/problem+json
Problem typeThe stable URI that names an error kind
JSON PointerA path into a JSON document, used in errors[].pointer
HATEOASHypermedia as the engine of application state
Richardson Maturity ModelFowler's four levels: tunnel, resources, verbs, hypermedia
HALA hypermedia JSON convention with _links and _embedded
JSON:APIA specification for resource objects, relationships, inclusion and paging
Keyset (cursor) paginationPaging by "after this key" instead of by offset
Opaque cursorA marker whose format clients must not parse
Link headerRFC 8288 header carrying rel="next" and other relations
Tolerant readerA client that ignores unknown fields and values
Deprecation headerSignals that an API or version is no longer recommended
Sunset headerRFC 8594 header with the date a URI is likely to stop responding
Contract-firstWriting and reviewing the API description before the code
OpenAPIThe specification for describing HTTP APIs (3.1.0 used here)
SpectralA linter that applies rulesets to OpenAPI and AsyncAPI files
oasdiffA tool that compares OpenAPI files and reports breaking changes
Consumer-driven contractConsumers state what they use; the provider must keep satisfying it (Pact)
API gatewayA reverse proxy in front of APIs that applies policy (Kong, Apigee)
KongAn API gateway with plugins and a developer portal
ApigeeGoogle Cloud's API management platform
Developer portalA site where consumers read docs and obtain keys
Quota / rate limitA cap on calls per key and period; exceeded gives 429
SanctumLaravel's token and SPA authentication package; tokens carry abilities
Scope / abilityA named permission carried by a token (orders:write)
Tenant isolationMaking sure a caller can reach only its own data
BOLABroken object-level authorization: reading others' objects by id
GraphQLA typed query language and runtime for APIs
SDLSchema definition language for GraphQL
ResolverThe function that produces one field's value
Input typeA GraphQL type used for arguments
Payload typeA mutation's return type, holding result and userErrors
userErrorsThe payload field carrying business failures as data
Relay connectionedges, node, cursor, pageInfo pagination model
N+1 problemOne query for a list, then one more per item
DataloaderA per-request batcher and cache for key lookups
LighthouseA schema-first GraphQL package for Laravel
gqlgenA schema-first GraphQL code generator for Go
FederationComposing subgraphs owned by different teams into a supergraph
SupergraphThe single composed graph of a federation
Schema stitchingMerging remote schemas at a gateway with explicit links
BFFBackend for Frontend: an API owned by one client type
gRPCA typed RPC framework over HTTP/2 with Protobuf contracts
WebhookAn HTTP callback an API sends to a consumer's URL
HMAC signatureA keyed hash proving a webhook came from the sender
AsyncAPIThe OpenAPI-like specification for event-driven APIs
OutboxStoring 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.

Built by Morteza Negahi