API Design
Design clear, consistent, secure, and evolvable APIs, including resource modeling, errors, pagination, asynchronous operations, and versioning.
Introduction
An API is a contract. Once other code (a front end, a customer’s script, a partner integration) depends on it, changing it becomes expensive. A good API is consistent, predictable, hard to misuse, and designed to evolve without breaking clients.
SignalDesk has internal APIs (between its browser client and server, and between modules) and potentially external ones. The same principles apply, with more rigor for anything outside your control.
Learning Objectives
- Choose an API style appropriate to the use case.
- Model resources and operations consistently.
- Design pagination, filtering, errors, and idempotency.
- Handle long-running operations and authentication.
- Plan versioning and compatibility.
- Use AI to draft and review API specifications, and validate them with tooling.
1. Choosing an API Style
| Style | Strengths | Trade-offs |
|---|---|---|
| REST over HTTP/JSON | Widely understood, cacheable, tool support | Can lead to many round trips; over-/under-fetching |
| GraphQL | Clients request exactly the data needed; one endpoint | Complexity in caching, authorization, query cost control |
| RPC (including gRPC) | Efficient, strongly typed, good for service-to-service | Less browser-friendly, tighter coupling |
| Event / webhook | Notify consumers of changes | Delivery guarantees, retries, security |
For a typical web product with a browser client and possible third-party integrations, a resource-oriented REST/JSON API is a reasonable default. Choose another style when a driver justifies it, and record the reasoning.
2. Model Resources, Not Screens
Resources are the nouns of your domain. Use consistent, plural names and hierarchy only where ownership is real.
1
2
3
4
5
6
7
8
9
10
11
GET /v1/workspaces/{workspaceId}/feedback-items
POST /v1/workspaces/{workspaceId}/feedback-items
GET /v1/workspaces/{workspaceId}/feedback-items/{itemId}
GET /v1/workspaces/{workspaceId}/themes
POST /v1/workspaces/{workspaceId}/themes
PUT /v1/workspaces/{workspaceId}/themes/{themeId}/items/{itemId} (assign)
DELETE /v1/workspaces/{workspaceId}/themes/{themeId}/items/{itemId} (unassign)
POST /v1/workspaces/{workspaceId}/imports (start import)
GET /v1/workspaces/{workspaceId}/imports/{importId}
Guidelines:
- Use HTTP methods by their semantics: GET reads and is safe; PUT and DELETE are idempotent; POST creates or triggers processing.
- Keep naming, casing, and structure uniform across the whole API.
- Put the tenant in the path or derive it from the credential, and enforce authorization on every request.
- Do not expose internal identifiers or database structure unnecessarily.
3. Requests and Responses
Pagination. Never return unbounded collections. Prefer cursor-based pagination for large, changing data:
1
2
GET /v1/workspaces/{id}/feedback-items?limit=50&cursor=eyJpZCI6...
-> { "items": [...], "next_cursor": "..." }
Filtering and sorting. Use explicit, documented parameters, and index the supported ones.
Partial updates. Be clear on semantics: PUT replaces; PATCH changes the supplied fields.
Consistent shapes. Use one convention for timestamps (ISO 8601 with time zone), identifiers, and enumerations.
4. Errors
Provide a single, structured error format with a stable machine-readable code and a human-readable message:
1
2
3
4
5
6
7
8
{
"error": {
"code": "import_file_too_large",
"message": "The file exceeds the 20 MB limit.",
"details": { "max_bytes": 20971520 },
"request_id": "req_8f3a..."
}
}
Use HTTP status codes meaningfully: 400 validation, 401 unauthenticated, 403 forbidden, 404 not found, 409 conflict, 422 semantic errors, 429 rate limited, 5xx server problems. Do not leak internal details, stack traces, or whether a resource exists in another tenant. Include a request identifier for support and tracing.
5. Idempotency and Retries
Networks fail, and clients retry. Make operations safe to repeat:
- GET, PUT, and DELETE should be idempotent by design.
- For POST operations that create things, accept an idempotency key header; the server stores the result and returns it on a repeat.
- Document which operations are safe to retry.
This directly supports the reliability and import-duplication requirements.
6. Long-Running Operations
Imports and summaries take time. Do not hold the request open.
1
2
3
4
5
6
POST /v1/workspaces/{id}/imports -> 202 Accepted
Location: /v1/workspaces/{id}/imports/{importId}
GET /v1/workspaces/{id}/imports/{importId}
-> { "status": "running", "processed": 4200, "total": 10000 }
-> { "status": "completed", "imported": 9800, "skipped": 150, "duplicates": 50 }
Support polling, and optionally a webhook or notification on completion. Define the possible statuses and their transitions.
7. Authentication, Authorization, and Protection
- Authentication: use established standards (for example OAuth 2.0 / OpenID Connect for users; scoped API tokens for integrations). Do not invent your own.
- Authorization: check workspace membership and role on every request, centrally.
- Rate limiting and quotas: protect against abuse and runaway clients; return 429 with retry guidance.
- Input validation: validate type, size, and format at the boundary.
- Transport security: HTTPS only.
- Sensitive data: do not place secrets or personal data in URLs, which are logged.
8. Versioning and Evolution
Plan for change from the start.
| Change | Breaking? |
|---|---|
| Add an optional response field | No |
| Add a new endpoint | No |
| Remove or rename a field | Yes |
| Change a field’s type or meaning | Yes |
| Make an optional request field required | Yes |
Strategies: version in the path (/v1/) or header; keep old versions for a defined deprecation period; communicate deprecation clearly; prefer additive changes. Clients should ignore fields they do not recognize.
9. Specify the Contract
Write the API as an OpenAPI (or equivalent) specification before or alongside implementation. Benefits: a shared reference, generated documentation, mock servers, contract tests, and client generation. Store it in version control, and validate changes automatically for breaking differences.
10. Use AI to Draft and Review
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Act as an API designer.
Context: resources and operations needed, authentication model,
tenancy, non-functional requirements (latency, rate limits),
and conventions.
[Paste.]
Tasks:
1. Draft an OpenAPI 3 specification for these resources, including
pagination, error format, and idempotency for create operations.
2. List inconsistencies in naming, status codes, or semantics.
3. Identify operations lacking authorization rules.
4. Identify changes that would be breaking in the future and how to
avoid them.
Do not add endpoints that are not required. Mark any assumption.
Validate the generated specification with an OpenAPI linter and review every endpoint. AI-generated APIs often introduce redundant endpoints, inconsistent naming, or missing authorization.
11. Practical Exercise
- List the resources and operations SignalDesk needs, derived from the SRS use cases.
- Write an OpenAPI specification for at least eight endpoints, including one asynchronous operation and one paginated list.
- Define the shared error format, authentication scheme, and rate-limit policy.
- Write a versioning and deprecation policy.
- Create a table linking each endpoint to the requirement IDs it satisfies.
- Lint the specification and fix problems; run an AI review and triage.
Verification
You are ready to continue when:
- The API is consistent in naming, status codes, pagination, and errors.
- Authorization is defined for every endpoint.
- Long-running operations are asynchronous with a clear status model.
- Create operations support safe retries.
- A versioning policy exists and the specification passes linting.
Key Takeaways
- An API is a long-lived contract; design for evolution.
- Model resources consistently, and handle errors, pagination, and retries deliberately.
- Make long-running work asynchronous and observable.
- Specify with OpenAPI; AI can draft it, but tooling and humans validate it.
What’s Next?
Next, we test the design against growth: how to reason about scalability and performance before problems appear.