API Design
Choosing the Right API Type
| Type |
Best For |
Avoid When |
| REST |
Public APIs, CRUD, simple clients, IoT |
Complex nested data, rapid schema iteration |
| GraphQL |
Mobile apps, complex nested data, multiple clients |
Simple CRUD, small teams new to it |
| tRPC |
TypeScript monorepos, internal full-stack TS APIs |
Non-TypeScript clients, public APIs |
| gRPC |
High-performance microservice comms, streaming |
Browser clients, simple use cases |
REST API Design
URL Conventions
GET /users ← list
GET /users/{id} ← single
POST /users ← create
PUT /users/{id} ← replace
PATCH /users/{id} ← partial update
DELETE /users/{id} ← delete
# Nested resources
GET /users/{id}/orders
POST /users/{id}/orders
# Actions (when REST verbs aren't enough)
POST /orders/{id}/cancel
POST /users/{id}/activate
HTTP Status Codes
| Code |
Use When |
| 200 |
Successful GET, PUT, PATCH |
| 201 |
Successful POST that creates |
| 204 |
Successful DELETE (no body) |
| 400 |
Validation failure, bad request |
| 401 |
Missing/invalid authentication |
| 403 |
Authenticated but not authorized |
| 404 |
Resource not found |
| 409 |
Conflict (duplicate, version mismatch) |
| 422 |
Unprocessable entity (semantic errors) |
| 429 |
Rate limit exceeded |
| 500 |
Unexpected server error |
Response Envelope
// Collection
{
"data": [...],
"meta": { "total": 100, "page": 1, "perPage": 20 }
}
// Single resource
{ "data": { "id": "1", "name": "James" } }
// Error
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"details": [{ "field": "email", "issue": "Invalid format" }]
}
}
API Design Principles
Versioning Strategy
# URL versioning (most visible, easiest to route)
/v1/users
/v2/users
# Header versioning (cleaner URLs)
Accept: application/vnd.api+json;version=2
```text
Never break existing clients. Deprecate, then remove.
### Pagination
```text
# Offset (simple, good for small datasets)
GET /posts?page=2&perPage=20
# Cursor (fast for large datasets, use for infinite scroll)
GET /posts?cursor=eyJpZCI6MTAwfQ&limit=20
```text
### Filtering & Sorting
```text
GET /orders?status=pending&userId=123
GET /products?sort=-price,name # - prefix = descending
GET /products?fields=id,name,price # sparse fieldsets
```text
### Idempotency
```text
# Include idempotency key for non-idempotent operations
POST /payments
Idempotency-Key: unique-client-generated-uuid
```text
---
## GraphQL Design
### Schema Design Rules
- Describe business domain, not DB structure
- Use connections pattern for lists (pagination-ready)
- Mutations return the modified object
- Use enums for finite value sets
- Add descriptions to all types and fields
```graphql
type Query {
user(id: ID!): User
users(filter: UserFilter, pagination: PaginationInput): UserConnection!
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
API Security Checklist
1---2name: api-design3description: API Design4---56# API Design78## Choosing the Right API Type910| Type | Best For | Avoid When |11|---|---|---|12| **REST** | Public APIs, CRUD, simple clients, IoT | Complex nested data, rapid schema iteration |13| **GraphQL** | Mobile apps, complex nested data, multiple clients | Simple CRUD, small teams new to it |14| **tRPC** | TypeScript monorepos, internal full-stack TS APIs | Non-TypeScript clients, public APIs |15| **gRPC** | High-performance microservice comms, streaming | Browser clients, simple use cases |1617---1819## REST API Design2021### URL Conventions22```text23GET /users ← list24GET /users/{id} ← single25POST /users ← create26PUT /users/{id} ← replace27PATCH /users/{id} ← partial update28DELETE /users/{id} ← delete2930# Nested resources31GET /users/{id}/orders32POST /users/{id}/orders3334# Actions (when REST verbs aren't enough)35POST /orders/{id}/cancel36POST /users/{id}/activate37```3839### HTTP Status Codes40| Code | Use When |41|---|---|42| 200 | Successful GET, PUT, PATCH |43| 201 | Successful POST that creates |44| 204 | Successful DELETE (no body) |45| 400 | Validation failure, bad request |46| 401 | Missing/invalid authentication |47| 403 | Authenticated but not authorized |48| 404 | Resource not found |49| 409 | Conflict (duplicate, version mismatch) |50| 422 | Unprocessable entity (semantic errors) |51| 429 | Rate limit exceeded |52| 500 | Unexpected server error |5354### Response Envelope55```json56// Collection57{58 "data": [...],59 "meta": { "total": 100, "page": 1, "perPage": 20 }60}6162// Single resource63{ "data": { "id": "1", "name": "James" } }6465// Error66{67 "error": {68 "code": "VALIDATION_ERROR",69 "message": "Validation failed",70 "details": [{ "field": "email", "issue": "Invalid format" }]71 }72}73```7475---7677## API Design Principles7879### Versioning Strategy80```text81# URL versioning (most visible, easiest to route)82/v1/users83/v2/users8485# Header versioning (cleaner URLs)86Accept: application/vnd.api+json;version=287```text8889Never break existing clients. Deprecate, then remove.9091### Pagination92```text93# Offset (simple, good for small datasets)94GET /posts?page=2&perPage=209596# Cursor (fast for large datasets, use for infinite scroll)97GET /posts?cursor=eyJpZCI6MTAwfQ&limit=2098```text99100### Filtering & Sorting101```text102GET /orders?status=pending&userId=123103GET /products?sort=-price,name # - prefix = descending104GET /products?fields=id,name,price # sparse fieldsets105```text106107### Idempotency108```text109# Include idempotency key for non-idempotent operations110POST /payments111Idempotency-Key: unique-client-generated-uuid112```text113114---115116## GraphQL Design117118### Schema Design Rules119- Describe business domain, not DB structure120- Use connections pattern for lists (pagination-ready)121- Mutations return the modified object122- Use enums for finite value sets123- Add descriptions to all types and fields124125```graphql126type Query {127 user(id: ID!): User128 users(filter: UserFilter, pagination: PaginationInput): UserConnection!129}130131type Mutation {132 createUser(input: CreateUserInput!): CreateUserPayload!133 updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!134}135136type UserConnection {137 edges: [UserEdge!]!138 pageInfo: PageInfo!139 totalCount: Int!140}141```142143---144145## API Security Checklist146147- [ ] All endpoints require authentication (unless explicitly public)148- [ ] Authorization checked per resource, not just per route149- [ ] Rate limiting on all endpoints, stricter on auth endpoints150- [ ] Input validation on every parameter and body field151- [ ] Sensitive data not returned unless explicitly needed152- [ ] CORS configured with explicit whitelist153- [ ] API versioning strategy defined before going public