API Resource Names, Relationships, and Collections
Model API URLs around stable resources and relationships, with clear collection behavior that clients can navigate without learning server internals.
Use customer and order resources to shape stable URLs, scope nested collections, and return bounded lists in a deterministic order. The guide follows one order collection from its route to its response and authorization checks.
API Resource Names, Relationships, and Collections
Introduction
Model routes around the things clients read and change. In this example, a customer has an orders collection, and each order has a stable ID. The URLs describe that relationship without exposing storage tables or service boundaries.
API resource names should reflect concepts clients use, while storage can follow the database’s needs. The REST API design guide covers broader conventions; this page follows one customer-orders model through its routes and response.
Model customer orders from the route to the response
Use a nested collection when the parent scopes the records:
GET /v1/customers/cus_18/orders
GET /v1/customers/cus_18/orders/ord_92
The first route lists one customer’s orders. The second addresses one order within that customer. The parent ID is useful for query scope and authorization checks, but it is not proof of permission by itself.
An order representation should use API terms and remain small enough for a list:
{
"id": "ord_92",
"customerId": "cus_18",
"createdAt": "2026-11-03T14:20:00Z",
"status": "shipped",
"totalCents": 4250
}
The list wraps summaries with pagination metadata:
{
"items": [
{
"id": "ord_92",
"customerId": "cus_18",
"createdAt": "2026-11-03T14:20:00Z",
"status": "shipped",
"totalCents": 4250
}
],
"nextCursor": "opaque-token",
"hasMore": true
}
Define the default sort as newest first, with id as a unique tie-breaker: (createdAt DESC, id DESC). The tie-breaker gives every result a position even when timestamps match. Keep the list bounded; this example caps a page at 50 items. Set the limit for each API based on its payload and service constraints.
If clients need full line items or customer details, expose a separate resource or link instead of growing every order summary. Keep historical order facts, such as the charged total, on the order even if the current customer or catalog record changes.
Choose route depth by relationship
graph LR
Customer -->|has many| Order
Nest a collection when the parent provides meaningful scope, such as listing one customer’s orders. Keep nesting shallow. If an order can be addressed without its customer context, a top-level item route can also work, but the service must still check the order’s actual parent before returning it.
Use resource paths for durable entities
Use resource paths when clients work with identifiable domain entities and standard HTTP methods fit the operation. Avoid routes that expose table names, repeat every relationship, or differ only to match one client team’s vocabulary. A command endpoint can be clearer when an operation does not read like creating, reading, updating, or deleting a resource.
Route trade-offs
| Modeling choice | Strength | Cost |
|---|---|---|
| Shallow nested collection | Parent scope is explicit | Can duplicate access paths |
| Link to related resource | Separates ownership and lookup | Client may need another request |
| Embedded related object | Fewer round trips | Can become stale or oversized |
| Bare array response | Minimal representation | No obvious place for pagination metadata |
Enforce parent scope and bound the list
The handler authorizes the parent before querying its collection. The example’s page limit is an API policy; the repository should enforce the same cap.
interface OrderSummary {
id: string;
customerId: string;
createdAt: string;
status: string;
totalCents: number;
}
interface OrderPage {
items: OrderSummary[];
nextCursor: string | null;
hasMore: boolean;
}
async function listCustomerOrders(
customerId: string,
user: User,
): Promise<OrderPage> {
await authorizeCustomerRead(user, customerId);
const page = await orderRepository.listByCustomer(customerId, {
limit: 50,
orderBy: [
{ field: "createdAt", direction: "desc" },
{ field: "id", direction: "desc" },
],
});
return {
items: page.items.map(toOrderSummary),
nextCursor: page.nextCursor,
hasMore: page.nextCursor !== null,
};
}
Map database rows into the public OrderSummary shape rather than serializing storage records directly. Every request for a nested item should verify that the order belongs to the customer in the route.
Stable ordering and page boundaries
Define the sort before choosing a pagination mechanism. This example sorts by (createdAt DESC, id DESC) and returns a bounded page. The next token is opaque to clients and does not grant access; authenticate and recheck customer scope on every request, as AIP-158 recommends. The filtering, sorting, and pagination guide covers cursor mechanics and field selection.
Route and collection failures to guard against
- A nested order route returns another customer’s record. Check both the caller’s permission and the order’s customer association.
- A list query filters by order ID but forgets the customer scope. Include the route’s customer ID in the authorization and data-access path.
- An order list embeds every line item and current product detail. Return a compact summary, then let clients request detail when they need it.
- A route rename strands older clients. Measure old-route use and provide a documented migration path before removing an alias.
An opaque or sequential ID does not grant access. Check authorization on every request, and keep storage-only fields out of the public representation.
Quick recap checklist
- Name resources with stable domain terms and use a consistent collection convention.
- Keep list responses bounded and define pagination and ordering.
- Use nested paths only when the parent meaningfully scopes the child collection.
- Embed small stable summaries; link separately fetched or independently permissioned resources.
Interview questions
Storage schemas change for internal reasons and often expose implementation details. An API model should reflect stable concepts clients use, allowing the database to evolve independently.
It is useful when the parent meaningfully scopes the child collection, such as listing one customer's orders. Keep nesting shallow and verify the relationship and caller's access on the server.
Embed a small, stable summary when it saves a meaningful round trip. Link or provide a separate endpoint for large, frequently changing, or independently permissioned records.
A unique tie-breaker gives records with the same timestamp a defined order, so the server can continue the collection consistently.
Further reading
- Google API Improvement Proposal 158: Pagination. Page tokens, bounded page sizes, and collection pagination behavior.
- RFC 8288: Web Linking. A standard model for links between resources.
- RESTful API Design. Broader conventions for HTTP methods, resource modeling, and API evolution.
- Filtering, Sorting, and Pagination. Practical options for collection queries and page navigation.
Conclusion
Keep customer scope visible in the route, return bounded order summaries, and define a stable sort. Next, see the filtering, sorting, and pagination guide for cursor mechanics and field selection.
Category
Related Posts
API Request, Response, and Error Shapes Clients Can Trust
Design consistent API request and response envelopes, validation errors, and problem details so client developers can handle success and failure reliably.
HTTP Methods, Status Codes, and Headers in API Design
Choose HTTP methods that match the operation, return status codes clients can act on, and use headers for metadata, caching, and safe retries.
API Filtering, Sorting, Pagination, and Field Selection
Build collection endpoints that let clients narrow, order, page through, and shape results without slow queries or unstable response behavior.