Audit API Consistency
Overview
Scan the codebase for API route definitions and analyze them for consistency across naming, HTTP method usage, error response shapes, pagination, auth patterns, and versioning. Produce a structured report with severity-rated findings and concrete fix recommendations. This is an audit skill -- it analyzes what exists, it does not create new APIs.
Workflow
Read project context -- Read .chalk/docs/engineering/ for:
- Existing API design documents that define the intended conventions
- Architecture docs describing the API layer
- Any API style guides or conventions documents
- Prior audit reports to check if previously flagged issues were resolved
Discover route definitions -- Scan the codebase to find all API endpoints:
- Use Grep to search for route registration patterns:
- Express/Koa:
router.get, router.post, app.use, etc.
- Django:
path(, url(, @api_view
- Spring:
@GetMapping, @PostMapping, @RequestMapping
- FastAPI:
@app.get, @router.post
- Rails:
resources :, get ', post '
- Next.js: files in
app/api/ or pages/api/
- Build a complete inventory of endpoints with: method, path, handler file, and handler function
Analyze each consistency category -- For each category below, compare every endpoint against the dominant pattern. The dominant pattern is the convention used by the majority of endpoints.
Classify findings by severity -- Each inconsistency gets one of:
- Critical: Will cause client errors or security issues (e.g., missing auth on a protected endpoint)
- High: Breaks client assumptions or developer experience (e.g., different error shapes)
- Medium: Inconsistency that causes confusion but no runtime issues (e.g., mixed naming conventions)
- Low: Minor deviation that could be addressed opportunistically (e.g., inconsistent sort defaults)
Generate fix recommendations -- For each finding, provide:
- The current state (what is inconsistent)
- The expected state (what it should be, based on dominant pattern)
- A concrete code change or migration path
- Whether it is a breaking change for existing clients
Output the report -- Present the report in conversation or write to .chalk/docs/engineering/<n>_api_audit.md if the user requests a persisted report.
Summarize -- Provide an executive summary with total findings by severity, the most impactful issues, and a recommended prioritization for fixes.
Consistency Categories
1. URL Naming Patterns
Check for:
- Plural vs. singular nouns:
/users vs. /user (pick one, apply everywhere)
- Casing consistency:
/user-profiles vs. /userProfiles vs. /user_profiles
- Nesting depth: Are some resources nested 3+ levels while others are flat?
- Verb usage:
/api/getUsers (RPC-style) mixed with /api/users (REST-style)
- ID format in paths:
:id vs. :userId vs. {id} -- consistent parameter naming
- Trailing slashes: Some paths with
/, some without
2. HTTP Method Usage
Check for:
- GET with side effects: GET endpoints that modify data (should be POST/PATCH/DELETE)
- POST for retrieval: POST used to fetch data that should be a GET with query params
- PUT vs. PATCH confusion: PUT used for partial updates (should be PATCH) or PATCH used for full replacement (should be PUT)
- DELETE semantics: Some DELETEs return the deleted resource, others return 204 No Content -- pick one
- Correct status codes: POST returning 200 instead of 201, DELETE returning 200 instead of 204
3. Error Response Format
Check for:
- Shape consistency: Do all endpoints return errors in the same JSON structure?
- Error code presence: Do all errors include a machine-readable error code?
- Validation error format: Are field-level validation errors structured consistently?
- HTTP status code accuracy: 400 vs. 422 for validation, 401 vs. 403 for auth
- Error middleware: Is error formatting centralized or scattered across handlers?
- Stack traces in production: Are internal details leaked in error responses?
4. Pagination Approach
Check for:
- Pagination presence: Are all list endpoints paginated? Flag any that return unbounded results
- Pagination style: Cursor vs. offset -- is it consistent across all list endpoints?
- Parameter naming:
page/limit vs. offset/count vs. cursor/size
- Default values: Are default page sizes consistent?
- Maximum limits: Do all paginated endpoints enforce a maximum page size?
- Response meta shape: Is pagination metadata structured the same way everywhere?
5. Authentication and Authorization
Check for:
- Auth middleware coverage: Are all non-public endpoints protected by auth middleware?
- Auth header format: Consistent use of
Authorization: Bearer <token> or API key headers
- Missing auth on sensitive endpoints: POST/PUT/PATCH/DELETE without auth checks
- Role/scope checking: Is authorization granularity consistent?
- Public endpoint documentation: Are intentionally public endpoints clearly marked?
6. Versioning
Check for:
- Version presence: Is API versioning used at all? If so, is it consistent?
- Version format: URL-based (
/api/v1/) vs. header-based (Accept: application/vnd.api.v1+json)
- Unversioned endpoints: Endpoints that bypass the versioning scheme
- Deprecated versions: Are old versions still active without deprecation headers?
7. Response Envelope
Check for:
- Wrapper consistency: Do all endpoints use the same response wrapper (
{ data }, { data, meta }, or raw)?
- Single vs. collection distinction: Single resources returning arrays or collections returning unwrapped objects
- Null handling:
null vs. absent key vs. empty string for missing optional fields
- Timestamp format: ISO 8601 everywhere or mixed formats?
Report Format
# API Consistency Audit Report
Date: <YYYY-MM-DD>
Scope: <All endpoints | Specific area>
Total endpoints scanned: <count>
## Executive Summary
<2-3 sentences. Overall consistency score, most impactful issues, recommended priority.>
### Findings by Severity
| Severity | Count |
|----------|-------|
| Critical | <n> |
| High | <n> |
| Medium | <n> |
| Low | <n> |
## Dominant Patterns (Established Conventions)
<Document the patterns used by the majority of endpoints. These are the "correct" baseline.>
| Category | Dominant Pattern | Adoption Rate |
|----------|-----------------|---------------|
| URL casing | kebab-case | 85% (34/40) |
| Pluralization | Plural nouns | 90% (36/40) |
| Error shape | `{ error: { code, message, status, details } }` | 75% (30/40) |
| Pagination | Offset with `page`/`limit` | 100% (8/8 list endpoints) |
| Auth | Bearer token via middleware | 92% (37/40) |
## Findings
### Critical
**[C-1]** Missing auth on `POST /api/v1/admin/settings`
- **File**: `src/routes/admin.ts:45`
- **Issue**: Endpoint modifies system settings but has no auth middleware
- **Expected**: Auth middleware with `admin` role check
- **Fix**: Add `requireAuth('admin')` middleware
- **Breaking**: No
### High
**[H-1]** Inconsistent error shape in billing endpoints
- **File**: `src/routes/billing.ts`
- **Issue**: Returns `{ "message": "error" }` instead of standard `{ "error": { "code": "...", "message": "..." } }`
- **Expected**: Use shared error middleware
- **Fix**: Replace manual error returns with `throw new AppError('BILLING_ERROR', message)`
- **Breaking**: Yes -- clients parsing billing errors will need to update
### Medium
...
### Low
...
## Migration Recommendations
### Priority 1: Critical and High (do now)
<Ordered list of fixes with estimated effort>
### Priority 2: Medium (next sprint)
<Ordered list>
### Priority 3: Low (opportunistic)
<Fixes to apply when touching these files for other reasons>
## Legacy Endpoints
<List endpoints that are intentionally inconsistent due to backwards compatibility. Document why they are exempt and whether a migration is planned.>
Scanning Strategy
When scanning a large codebase, follow this order for efficiency:
- Find the router/route files first -- Grep for the framework's routing pattern to locate all route files
- Extract the endpoint inventory -- Build the full list before analyzing
- Check error middleware/handler -- Find the centralized error handling to understand the intended pattern
- Spot-check endpoints -- Read 3-5 endpoint handlers in full to understand the actual implementation pattern
- Compare outliers -- Focus analysis time on endpoints that deviate from the dominant pattern
Anti-patterns
- Only checking names, not behavior -- URL naming is the easiest thing to audit but the least impactful. Inconsistent error shapes and missing auth are far more dangerous. Always audit behavior (error handling, auth, pagination) before cosmetic naming.
- Ignoring legacy endpoints -- Old endpoints that predate current conventions should still be cataloged. Document them as "legacy, migration planned" or "legacy, exempt" -- but do not pretend they do not exist.
- Not suggesting a migration path -- Flagging inconsistencies without explaining how to fix them is not useful. Every finding must include a concrete fix and whether it is a breaking change.
- Auditing against an ideal, not the project's own conventions -- The correct convention is whatever the majority of the codebase uses, not what a blog post says. If the project uses
snake_case URLs, do not flag them as wrong because REST guides prefer kebab-case.
- Missing auth gaps -- The single most valuable finding in an API audit is an endpoint that should require auth but does not. Always prioritize auth coverage analysis.
- One-time audit with no follow-up -- An audit is only valuable if issues get fixed. Include a prioritized action plan and suggest re-running the audit after fixes are applied.
1---2name: audit-api-consistency3description: Audit existing API endpoints for consistency when the user asks to check API quality, review API patterns, audit endpoints, or find API inconsistencies4---5
6# Audit API Consistency
7
8## Overview
9
10Scan the codebase for API route definitions and analyze them for consistency across naming, HTTP method usage, error response shapes, pagination, auth patterns, and versioning. Produce a structured report with severity-rated findings and concrete fix recommendations. This is an audit skill -- it analyzes what exists, it does not create new APIs.
11
12## Workflow
13
141. **Read project context** -- Read `.chalk/docs/engineering/` for:
15 - Existing API design documents that define the intended conventions
16 - Architecture docs describing the API layer
17 - Any API style guides or conventions documents
18 - Prior audit reports to check if previously flagged issues were resolved
19
202. **Discover route definitions** -- Scan the codebase to find all API endpoints:
21 - Use Grep to search for route registration patterns:
22 - Express/Koa: `router.get`, `router.post`, `app.use`, etc.
23 - Django: `path(`, `url(`, `@api_view`
24 - Spring: `@GetMapping`, `@PostMapping`, `@RequestMapping`
25 - FastAPI: `@app.get`, `@router.post`
26 - Rails: `resources :`, `get '`, `post '`
27 - Next.js: files in `app/api/` or `pages/api/`
28 - Build a complete inventory of endpoints with: method, path, handler file, and handler function
29
303. **Analyze each consistency category** -- For each category below, compare every endpoint against the dominant pattern. The dominant pattern is the convention used by the majority of endpoints.
31
324. **Classify findings by severity** -- Each inconsistency gets one of:
33 - **Critical**: Will cause client errors or security issues (e.g., missing auth on a protected endpoint)
34 - **High**: Breaks client assumptions or developer experience (e.g., different error shapes)
35 - **Medium**: Inconsistency that causes confusion but no runtime issues (e.g., mixed naming conventions)
36 - **Low**: Minor deviation that could be addressed opportunistically (e.g., inconsistent sort defaults)
37
385. **Generate fix recommendations** -- For each finding, provide:
39 - The current state (what is inconsistent)
40 - The expected state (what it should be, based on dominant pattern)
41 - A concrete code change or migration path
42 - Whether it is a breaking change for existing clients
43
446. **Output the report** -- Present the report in conversation or write to `.chalk/docs/engineering/<n>_api_audit.md` if the user requests a persisted report.
45
467. **Summarize** -- Provide an executive summary with total findings by severity, the most impactful issues, and a recommended prioritization for fixes.
47
48## Consistency Categories
49
50### 1. URL Naming Patterns
51
52Check for:
53- **Plural vs. singular nouns**: `/users` vs. `/user` (pick one, apply everywhere)
54- **Casing consistency**: `/user-profiles` vs. `/userProfiles` vs. `/user_profiles`
55- **Nesting depth**: Are some resources nested 3+ levels while others are flat?
56- **Verb usage**: `/api/getUsers` (RPC-style) mixed with `/api/users` (REST-style)
57- **ID format in paths**: `:id` vs. `:userId` vs. `{id}` -- consistent parameter naming
58- **Trailing slashes**: Some paths with `/`, some without
59
60### 2. HTTP Method Usage
61
62Check for:
63- **GET with side effects**: GET endpoints that modify data (should be POST/PATCH/DELETE)
64- **POST for retrieval**: POST used to fetch data that should be a GET with query params
65- **PUT vs. PATCH confusion**: PUT used for partial updates (should be PATCH) or PATCH used for full replacement (should be PUT)
66- **DELETE semantics**: Some DELETEs return the deleted resource, others return 204 No Content -- pick one
67- **Correct status codes**: POST returning 200 instead of 201, DELETE returning 200 instead of 204
68
69### 3. Error Response Format
70
71Check for:
72- **Shape consistency**: Do all endpoints return errors in the same JSON structure?
73- **Error code presence**: Do all errors include a machine-readable error code?
74- **Validation error format**: Are field-level validation errors structured consistently?
75- **HTTP status code accuracy**: 400 vs. 422 for validation, 401 vs. 403 for auth
76- **Error middleware**: Is error formatting centralized or scattered across handlers?
77- **Stack traces in production**: Are internal details leaked in error responses?
78
79### 4. Pagination Approach
80
81Check for:
82- **Pagination presence**: Are all list endpoints paginated? Flag any that return unbounded results
83- **Pagination style**: Cursor vs. offset -- is it consistent across all list endpoints?
84- **Parameter naming**: `page`/`limit` vs. `offset`/`count` vs. `cursor`/`size`
85- **Default values**: Are default page sizes consistent?
86- **Maximum limits**: Do all paginated endpoints enforce a maximum page size?
87- **Response meta shape**: Is pagination metadata structured the same way everywhere?
88
89### 5. Authentication and Authorization
90
91Check for:
92- **Auth middleware coverage**: Are all non-public endpoints protected by auth middleware?
93- **Auth header format**: Consistent use of `Authorization: Bearer <token>` or API key headers
94- **Missing auth on sensitive endpoints**: POST/PUT/PATCH/DELETE without auth checks
95- **Role/scope checking**: Is authorization granularity consistent?
96- **Public endpoint documentation**: Are intentionally public endpoints clearly marked?
97
98### 6. Versioning
99
100Check for:
101- **Version presence**: Is API versioning used at all? If so, is it consistent?
102- **Version format**: URL-based (`/api/v1/`) vs. header-based (`Accept: application/vnd.api.v1+json`)
103- **Unversioned endpoints**: Endpoints that bypass the versioning scheme
104- **Deprecated versions**: Are old versions still active without deprecation headers?
105
106### 7. Response Envelope
107
108Check for:
109- **Wrapper consistency**: Do all endpoints use the same response wrapper (`{ data }`, `{ data, meta }`, or raw)?
110- **Single vs. collection distinction**: Single resources returning arrays or collections returning unwrapped objects
111- **Null handling**: `null` vs. absent key vs. empty string for missing optional fields
112- **Timestamp format**: ISO 8601 everywhere or mixed formats?
113
114## Report Format
115
116```markdown
117# API Consistency Audit Report
118
119Date: <YYYY-MM-DD>
120Scope: <All endpoints | Specific area>
121Total endpoints scanned: <count>
122
123## Executive Summary
124
125<2-3 sentences. Overall consistency score, most impactful issues, recommended priority.>
126
127### Findings by Severity
128
129| Severity | Count |
130|----------|-------|
131| Critical | <n> |
132| High | <n> |
133| Medium | <n> |
134| Low | <n> |
135
136## Dominant Patterns (Established Conventions)
137
138<Document the patterns used by the majority of endpoints. These are the "correct" baseline.>
139
140| Category | Dominant Pattern | Adoption Rate |
141|----------|-----------------|---------------|
142| URL casing | kebab-case | 85% (34/40) |
143| Pluralization | Plural nouns | 90% (36/40) |
144| Error shape | `{ error: { code, message, status, details } }` | 75% (30/40) |
145| Pagination | Offset with `page`/`limit` | 100% (8/8 list endpoints) |
146| Auth | Bearer token via middleware | 92% (37/40) |
147
148## Findings
149
150### Critical
151
152**[C-1]** Missing auth on `POST /api/v1/admin/settings`
153- **File**: `src/routes/admin.ts:45`
154- **Issue**: Endpoint modifies system settings but has no auth middleware
155- **Expected**: Auth middleware with `admin` role check
156- **Fix**: Add `requireAuth('admin')` middleware
157- **Breaking**: No
158
159### High
160
161**[H-1]** Inconsistent error shape in billing endpoints
162- **File**: `src/routes/billing.ts`
163- **Issue**: Returns `{ "message": "error" }` instead of standard `{ "error": { "code": "...", "message": "..." } }`
164- **Expected**: Use shared error middleware
165- **Fix**: Replace manual error returns with `throw new AppError('BILLING_ERROR', message)`
166- **Breaking**: Yes -- clients parsing billing errors will need to update
167
168### Medium
169
170...
171
172### Low
173
174...
175
176## Migration Recommendations
177
178### Priority 1: Critical and High (do now)
179
180<Ordered list of fixes with estimated effort>
181
182### Priority 2: Medium (next sprint)
183
184<Ordered list>
185
186### Priority 3: Low (opportunistic)
187
188<Fixes to apply when touching these files for other reasons>
189
190## Legacy Endpoints
191
192<List endpoints that are intentionally inconsistent due to backwards compatibility. Document why they are exempt and whether a migration is planned.>
193```
194
195## Scanning Strategy
196
197When scanning a large codebase, follow this order for efficiency:
198
1991. **Find the router/route files first** -- Grep for the framework's routing pattern to locate all route files
2002. **Extract the endpoint inventory** -- Build the full list before analyzing
2013. **Check error middleware/handler** -- Find the centralized error handling to understand the intended pattern
2024. **Spot-check endpoints** -- Read 3-5 endpoint handlers in full to understand the actual implementation pattern
2035. **Compare outliers** -- Focus analysis time on endpoints that deviate from the dominant pattern
204
205## Anti-patterns
206
207- **Only checking names, not behavior** -- URL naming is the easiest thing to audit but the least impactful. Inconsistent error shapes and missing auth are far more dangerous. Always audit behavior (error handling, auth, pagination) before cosmetic naming.
208- **Ignoring legacy endpoints** -- Old endpoints that predate current conventions should still be cataloged. Document them as "legacy, migration planned" or "legacy, exempt" -- but do not pretend they do not exist.
209- **Not suggesting a migration path** -- Flagging inconsistencies without explaining how to fix them is not useful. Every finding must include a concrete fix and whether it is a breaking change.
210- **Auditing against an ideal, not the project's own conventions** -- The correct convention is whatever the majority of the codebase uses, not what a blog post says. If the project uses `snake_case` URLs, do not flag them as wrong because REST guides prefer `kebab-case`.
211- **Missing auth gaps** -- The single most valuable finding in an API audit is an endpoint that should require auth but does not. Always prioritize auth coverage analysis.
212- **One-time audit with no follow-up** -- An audit is only valuable if issues get fixed. Include a prioritized action plan and suggest re-running the audit after fixes are applied.