API Design Knowledge Base
Quick reference for API design patterns, REST best practices, and PHP implementation guidelines.
Core Principles
REST Constraints
| Constraint |
Description |
Implication |
| Client-Server |
Separation of concerns |
Independent evolution |
| Stateless |
No server-side session state |
Each request contains all info |
| Cacheable |
Responses declare cacheability |
Reduces server load |
| Uniform Interface |
Standard resource operations |
Predictable API surface |
| Layered System |
Client can't tell if connected directly |
Proxy, gateway, CDN support |
| Code on Demand (optional) |
Server can send executable code |
Rarely used in APIs |
Richardson Maturity Model
| Level |
Name |
Description |
Example |
| 0 |
Swamp of POX |
Single endpoint, RPC-style |
POST /api with action in body |
| 1 |
Resources |
Multiple endpoints per resource |
GET /orders/123 |
| 2 |
HTTP Verbs |
Proper use of HTTP methods + status codes |
DELETE /orders/123 → 204 |
| 3 |
HATEOAS |
Hypermedia controls in responses |
Links to related actions |
HTTP Methods Semantics
| Method |
Safe |
Idempotent |
Request Body |
Typical Use |
| GET |
Yes |
Yes |
No |
Retrieve resource |
| HEAD |
Yes |
Yes |
No |
Check resource existence |
| POST |
No |
No |
Yes |
Create resource, trigger action |
| PUT |
No |
Yes |
Yes |
Replace resource entirely |
| PATCH |
No |
No |
Yes |
Partial update |
| DELETE |
No |
Yes |
No |
Remove resource |
| OPTIONS |
Yes |
Yes |
No |
CORS preflight, capabilities |
Status Code Guide
| Range |
Category |
Common Codes |
| 2xx |
Success |
200 OK, 201 Created, 202 Accepted, 204 No Content |
| 3xx |
Redirection |
301 Moved Permanently, 304 Not Modified |
| 4xx |
Client Error |
400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests |
| 5xx |
Server Error |
500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout |
Content Negotiation
| Header |
Purpose |
Example |
| Accept |
Client requests format |
Accept: application/json |
| Content-Type |
Body format declaration |
Content-Type: application/json |
| Accept-Language |
Localization |
Accept-Language: en-US |
| Accept-Encoding |
Compression |
Accept-Encoding: gzip, br |
API Style Comparison
| Aspect |
REST |
GraphQL |
gRPC |
| Protocol |
HTTP/1.1+ |
HTTP/1.1+ |
HTTP/2 |
| Data format |
JSON |
JSON |
Protobuf |
| Schema |
OpenAPI (optional) |
SDL (required) |
.proto (required) |
| Caching |
HTTP caching native |
Complex (POST only) |
Manual |
| Over-fetching |
Common |
Solved (client picks fields) |
Solved (defined messages) |
| Under-fetching |
Common (multiple calls) |
Solved (nested queries) |
Separate RPCs |
| Learning curve |
Low |
Medium |
High |
| Best for |
Public APIs, CRUD |
Client-driven UIs, BFF |
Internal services, streaming |
Quick Checklists
API Design Checklist
Security Checklist
Detection Patterns
# REST endpoint definitions
Grep: "#\[Route|@Route|->get\(|->post\(|->put\(|->delete\(" --glob "**/*.php"
Glob: **/Controller/**/*.php
Glob: **/Action/**/*.php
# Status code usage
Grep: "->setStatusCode\(|Response\(.*[0-9]{3}|JsonResponse\(" --glob "**/*.php"
# Content negotiation
Grep: "Accept|Content-Type|application/json" --glob "**/*.php"
# API versioning
Grep: "/v[0-9]/|api-version|Accept.*vnd\." --glob "**/*.php"
# Error handling
Grep: "ProblemDetails|RFC7807|application/problem" --glob "**/*.php"
Grep: "JsonResponse.*4[0-9]{2}|JsonResponse.*5[0-9]{2}" --glob "**/*.php"
# Pagination
Grep: "page|per_page|limit|offset|cursor" --glob "**/Controller/**/*.php"
Advanced API Patterns
Cursor-Based Pagination (High-Load)
| Aspect |
Offset-Based |
Cursor-Based |
| URL |
?page=5&per_page=20 |
?cursor=abc123&limit=20 |
| Performance at scale |
Degrades (OFFSET N) |
Constant (WHERE id > X) |
| Consistency |
Misses/duplicates on insert |
Stable, no gaps |
| Random page access |
Yes |
No (sequential only) |
| Use case |
Admin panels |
Feeds, large datasets |
API Rate Limiting Algorithms
| Algorithm |
Precision |
Burst |
PHP Implementation |
| Token Bucket |
Medium |
Allows burst |
Redis Lua script |
| Sliding Window |
High |
Smooth |
Redis sorted set |
| Fixed Window |
Low |
Edge burst |
Redis INCR + EXPIRE |
| Leaky Bucket |
High |
No burst |
Redis list |
Rate Limit Headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After (on 429).
gRPC for PHP
| Factor |
Choose REST |
Choose gRPC |
| Client type |
Browser, third-party |
Internal services |
| Payload |
Small-medium JSON |
Large binary data |
| Streaming |
Not needed |
Real-time updates |
| PHP ecosystem |
Mature |
Limited (ext-grpc) |
GraphQL N+1 Prevention
| Technique |
How |
Complexity |
| DataLoader |
Batch + cache per request |
Medium |
| Query depth limit |
Max 5-7 nesting levels |
Low |
| Complexity scoring |
Cost per field, reject expensive |
Medium |
| Persisted queries |
Whitelist allowed queries |
Low |
References
For detailed information, load these reference files:
references/rest-patterns.md — Richardson Maturity details, HATEOAS, pagination, filtering, versioning strategies
references/error-handling.md — RFC 7807 Problem Details, error response patterns, GraphQL errors, PHP implementation
references/advanced-api.md — Cursor-based pagination, API rate limiting (token bucket, sliding window), gRPC PHP integration, GraphQL N+1 solutions
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: api-design-knowledge3description: API Design knowledge base. Provides REST constraints, Richardson Maturity Model, HTTP semantics, content negotiation, and GraphQL/gRPC comparison for API audits and generation. Use when this capability is needed.4---56# API Design Knowledge Base78Quick reference for API design patterns, REST best practices, and PHP implementation guidelines.910## Core Principles1112### REST Constraints1314| Constraint | Description | Implication |15|-----------|-------------|-------------|16| Client-Server | Separation of concerns | Independent evolution |17| Stateless | No server-side session state | Each request contains all info |18| Cacheable | Responses declare cacheability | Reduces server load |19| Uniform Interface | Standard resource operations | Predictable API surface |20| Layered System | Client can't tell if connected directly | Proxy, gateway, CDN support |21| Code on Demand (optional) | Server can send executable code | Rarely used in APIs |2223### Richardson Maturity Model2425| Level | Name | Description | Example |26|-------|------|-------------|---------|27| 0 | Swamp of POX | Single endpoint, RPC-style | `POST /api` with action in body |28| 1 | Resources | Multiple endpoints per resource | `GET /orders/123` |29| 2 | HTTP Verbs | Proper use of HTTP methods + status codes | `DELETE /orders/123` → `204` |30| 3 | HATEOAS | Hypermedia controls in responses | Links to related actions |3132### HTTP Methods Semantics3334| Method | Safe | Idempotent | Request Body | Typical Use |35|--------|------|------------|--------------|-------------|36| GET | Yes | Yes | No | Retrieve resource |37| HEAD | Yes | Yes | No | Check resource existence |38| POST | No | No | Yes | Create resource, trigger action |39| PUT | No | Yes | Yes | Replace resource entirely |40| PATCH | No | No | Yes | Partial update |41| DELETE | No | Yes | No | Remove resource |42| OPTIONS | Yes | Yes | No | CORS preflight, capabilities |4344### Status Code Guide4546| Range | Category | Common Codes |47|-------|----------|-------------|48| 2xx | Success | 200 OK, 201 Created, 202 Accepted, 204 No Content |49| 3xx | Redirection | 301 Moved Permanently, 304 Not Modified |50| 4xx | Client Error | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests |51| 5xx | Server Error | 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout |5253## Content Negotiation5455| Header | Purpose | Example |56|--------|---------|---------|57| Accept | Client requests format | `Accept: application/json` |58| Content-Type | Body format declaration | `Content-Type: application/json` |59| Accept-Language | Localization | `Accept-Language: en-US` |60| Accept-Encoding | Compression | `Accept-Encoding: gzip, br` |6162## API Style Comparison6364| Aspect | REST | GraphQL | gRPC |65|--------|------|---------|------|66| Protocol | HTTP/1.1+ | HTTP/1.1+ | HTTP/2 |67| Data format | JSON | JSON | Protobuf |68| Schema | OpenAPI (optional) | SDL (required) | .proto (required) |69| Caching | HTTP caching native | Complex (POST only) | Manual |70| Over-fetching | Common | Solved (client picks fields) | Solved (defined messages) |71| Under-fetching | Common (multiple calls) | Solved (nested queries) | Separate RPCs |72| Learning curve | Low | Medium | High |73| Best for | Public APIs, CRUD | Client-driven UIs, BFF | Internal services, streaming |7475## Quick Checklists7677### API Design Checklist7879- [ ] Resources use nouns, not verbs (`/orders` not `/getOrders`)80- [ ] Consistent naming convention (kebab-case or camelCase)81- [ ] Proper HTTP methods for operations82- [ ] Meaningful status codes (not always 200)83- [ ] Pagination for list endpoints84- [ ] Filtering and sorting support85- [ ] Versioning strategy defined86- [ ] Error responses follow RFC 780787- [ ] Rate limiting with proper headers88- [ ] CORS configured for browser clients8990### Security Checklist9192- [ ] Authentication on all endpoints (except public)93- [ ] Authorization checks per resource94- [ ] Input validation at API boundary95- [ ] Rate limiting per client/IP96- [ ] HTTPS only (no HTTP)97- [ ] No sensitive data in URLs98- [ ] Proper CORS policy99- [ ] Security headers set100101## Detection Patterns102103```bash104# REST endpoint definitions105Grep: "#\[Route|@Route|->get\(|->post\(|->put\(|->delete\(" --glob "**/*.php"106Glob: **/Controller/**/*.php107Glob: **/Action/**/*.php108109# Status code usage110Grep: "->setStatusCode\(|Response\(.*[0-9]{3}|JsonResponse\(" --glob "**/*.php"111112# Content negotiation113Grep: "Accept|Content-Type|application/json" --glob "**/*.php"114115# API versioning116Grep: "/v[0-9]/|api-version|Accept.*vnd\." --glob "**/*.php"117118# Error handling119Grep: "ProblemDetails|RFC7807|application/problem" --glob "**/*.php"120Grep: "JsonResponse.*4[0-9]{2}|JsonResponse.*5[0-9]{2}" --glob "**/*.php"121122# Pagination123Grep: "page|per_page|limit|offset|cursor" --glob "**/Controller/**/*.php"124```125126## Advanced API Patterns127128### Cursor-Based Pagination (High-Load)129130| Aspect | Offset-Based | Cursor-Based |131|--------|-------------|--------------|132| URL | `?page=5&per_page=20` | `?cursor=abc123&limit=20` |133| Performance at scale | Degrades (OFFSET N) | Constant (WHERE id > X) |134| Consistency | Misses/duplicates on insert | Stable, no gaps |135| Random page access | Yes | No (sequential only) |136| Use case | Admin panels | Feeds, large datasets |137138### API Rate Limiting Algorithms139140| Algorithm | Precision | Burst | PHP Implementation |141|-----------|-----------|-------|-------------------|142| Token Bucket | Medium | Allows burst | Redis Lua script |143| Sliding Window | High | Smooth | Redis sorted set |144| Fixed Window | Low | Edge burst | Redis INCR + EXPIRE |145| Leaky Bucket | High | No burst | Redis list |146147**Rate Limit Headers:** `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, `Retry-After` (on 429).148149### gRPC for PHP150151| Factor | Choose REST | Choose gRPC |152|--------|-------------|-------------|153| Client type | Browser, third-party | Internal services |154| Payload | Small-medium JSON | Large binary data |155| Streaming | Not needed | Real-time updates |156| PHP ecosystem | Mature | Limited (ext-grpc) |157158### GraphQL N+1 Prevention159160| Technique | How | Complexity |161|-----------|-----|------------|162| DataLoader | Batch + cache per request | Medium |163| Query depth limit | Max 5-7 nesting levels | Low |164| Complexity scoring | Cost per field, reject expensive | Medium |165| Persisted queries | Whitelist allowed queries | Low |166167## References168169For detailed information, load these reference files:170171- `references/rest-patterns.md` — Richardson Maturity details, HATEOAS, pagination, filtering, versioning strategies172- `references/error-handling.md` — RFC 7807 Problem Details, error response patterns, GraphQL errors, PHP implementation173- `references/advanced-api.md` — Cursor-based pagination, API rate limiting (token bucket, sliding window), gRPC PHP integration, GraphQL N+1 solutions174175---176> Converted and distributed by [TomeVault](https://tomevault.io/claim/dykyi-roman) — claim your Tome and manage your conversions.177<!-- tomevault:4.0:skill_md:2026-04-11 -->