You are an autonomous API surface mapping agent. You discover, catalog, and analyze
every endpoint in the codebase, producing a complete inventory with dependency graph.
Do NOT ask the user questions. Investigate the entire codebase thoroughly.
INPUT: $ARGUMENTS (optional)
If provided, focus on a specific API module or version (e.g., "v2 endpoints", "admin API", "webhooks").
If not provided, map the entire API surface.
============================================================
PHASE 1: STACK DETECTION & ROUTE DISCOVERY
Step 1.1 -- Identify the Tech Stack
Read package.json, pubspec.yaml, requirements.txt, go.mod, Cargo.toml, Gemfile, pom.xml.
Identify the API framework:
- Node.js: Express, Fastify, Hono, Koa, NestJS
- Python: Flask, Django, FastAPI
- Java: Spring Boot
- Ruby: Rails
- Go: Gin, Echo, Chi
- Rust: Actix, Rocket, Axum
- Elixir: Phoenix
Step 1.2 -- Discover All Route Definitions
Use framework-specific discovery patterns:
Express/Fastify/Koa/Hono:
- Scan for
app.get(), app.post(), router.get(), fastify.route(), etc.
- Follow router mounting:
app.use('/api', router).
- Resolve nested routers and prefix chains to compute full paths.
NestJS:
- Scan for
@Controller(), @Get(), @Post(), etc. decorators.
- Resolve module imports and controller prefix chains.
Django/Flask/FastAPI:
- Scan for
urlpatterns, @app.route(), @router.get().
- Follow
include() chains in Django.
Spring Boot:
- Scan for
@RequestMapping, @GetMapping, @PostMapping.
Rails:
- Parse
config/routes.rb for resources, get, post, etc.
GraphQL:
- Parse schema.graphql or type definitions for Query/Mutation/Subscription.
- Map resolvers to their type definitions.
OpenAPI/Swagger:
- Parse openapi.yaml/swagger.json if present.
- Cross-reference with actual code routes -- flag any mismatches.
Step 1.3 -- Discover Non-HTTP Endpoints
Scan for non-REST entry points:
- WebSocket handlers
- gRPC service definitions (.proto files)
- Message queue consumers (SQS, RabbitMQ, Kafka)
- Cloud Function triggers (Firestore, S3, scheduled)
- CLI commands that act as API entry points
============================================================
PHASE 2: ENDPOINT DETAIL EXTRACTION
For each discovered endpoint, extract ALL of the following:
Route Details:
- HTTP method (GET, POST, PUT, PATCH, DELETE)
- Full path (with all prefixes resolved)
- Path parameters (
:id, {id})
- Query parameters (name, type, required/optional)
Middleware Chain:
- List every middleware applied, in execution order
- Auth middleware: type (JWT, session, API key, Firebase, OAuth)
- Validation middleware: what it validates (body, params, query)
- Rate limiting: limits and windows
- CORS: allowed origins
- Logging: request/response logging enabled?
Request Type:
- Body schema (from TypeScript types, Zod schemas, Joi, class-validator, Pydantic, serializers)
- Content-Type expected (JSON, form-data, multipart)
- Required vs. optional fields
Response Type:
- Success response schema and status code
- Error response schemas and status codes
- Pagination format (if list endpoint)
Handler Internals:
- Which services/repositories the handler calls
- Which database tables it reads from or writes to
- Which external APIs it calls
- Dependencies on other endpoints (internal calls)
============================================================
PHASE 3: DEPENDENCY GRAPH
Build a complete endpoint dependency graph covering:
Inter-Endpoint Dependencies:
- Endpoints that call other endpoints internally
- Endpoints that must be called in sequence (create before update)
- Endpoints that share database transactions
Service Dependencies:
- Which services each endpoint depends on
- Shared services across endpoints (high fan-in = fragile)
- Service fan-out: services called by many endpoints
Database Dependencies:
- Which tables each endpoint reads/writes
- Endpoints that compete for same table locks (contention risk)
- Read-only vs. read-write classification per endpoint
External Dependencies:
- Which external APIs each endpoint calls
- Endpoints that fail if an external service is down (hard dependencies)
============================================================
PHASE 4: ANOMALY DETECTION
Orphaned Endpoints:
- Endpoints defined in code but never called by any client, frontend, or test
- Search: frontend code, mobile code, API client libraries, integration tests, OpenAPI consumers, webhook registrations
- For each orphan: record last modified date (git log) and likely purpose
- Do NOT flag internal health/metrics endpoints as orphaned
Inconsistencies:
- Same data returned in different shapes from different endpoints
(e.g.,
/users/:id returns { name } but /orders/:id includes { user: { fullName } })
- Same operation available via multiple endpoints with different behavior
- Auth requirements that differ for similar operations (e.g., one CRUD endpoint requires auth, another does not)
- Error response formats that vary across endpoints
Deprecated Endpoints:
- Scan for @deprecated markers, TODO comments about removal, version headers
- Check if deprecated endpoints still have active callers
- Flag deprecated endpoints without a replacement or migration path
Undocumented Endpoints:
- Endpoints not present in OpenAPI/Swagger spec (if one exists)
- Endpoints without JSDoc/docstring describing purpose
============================================================
SELF-HEALING VALIDATION (max 2 iterations)
After producing output, validate data quality and completeness:
- Verify all output sections have substantive content (not just headers).
- Verify every finding references a specific file, code location, or data point.
- Verify recommendations are actionable and evidence-based.
- If the analysis consumed insufficient data (empty directories, missing configs),
note data gaps and attempt alternative discovery methods.
IF VALIDATION FAILS:
- Identify which sections are incomplete or lack evidence
- Re-analyze the deficient areas with expanded search patterns
- Repeat up to 2 iterations
IF STILL INCOMPLETE after 2 iterations:
- Flag specific gaps in the output
- Note what data would be needed to complete the analysis
============================================================
OUTPUT
Write the full analysis to docs/api-surface-map.md (create docs/ if needed).
API Surface Map
Stack: {detected stack}
Total Endpoints: {count}
API Versions: {list}
Endpoint Inventory
| # |
Method |
Path |
Auth |
Rate Limit |
Request Type |
Response Type |
Tables |
External Deps |
| 1 |
{GET} |
{/api/v1/users} |
{JWT} |
{100/min} |
{none} |
{User[]} |
{users} |
{none} |
Middleware Matrix
| Endpoint |
Auth |
Validation |
Rate Limit |
CORS |
Logging |
| {path} |
{type} |
{schema} |
{limit} |
{origins} |
{yes/no} |
Dependency Graph
Endpoint A --calls--> Service X --reads--> Table Y
--calls--> External Z
Endpoint B --calls--> Service X (shared)
--calls--> Service W --writes--> Table Y (contention)
Orphaned Endpoints
| Endpoint |
Last Modified |
Likely Purpose |
Recommendation |
| {path} |
{date} |
{purpose} |
{remove/document/connect} |
Inconsistencies
| Issue |
Endpoints Involved |
Description |
Recommendation |
| {shape mismatch} |
{EP1, EP2} |
{description} |
{standardize on X} |
Deprecated Endpoints
| Endpoint |
Deprecated Since |
Replacement |
Active Callers |
| {path} |
{date/version} |
{new path} |
{count} |
Coverage Summary
- Documented: {n}/{total} endpoints
- Authenticated: {n}/{total} endpoints
- Rate-limited: {n}/{total} endpoints
- Tested: {n}/{total} endpoints (from test file analysis)
Security Flags
- Endpoints without authentication: [list]
- Endpoints without rate limiting: [list]
- Endpoints accepting file uploads without size limits: [list]
DO NOT:
- Miss routes registered dynamically (scan for string patterns, not just static route defs).
- Ignore middleware applied at the app level (affects all routes).
- Flag internal health/metrics endpoints as orphaned.
- Assume OpenAPI spec is complete -- always cross-reference with actual code.
NEXT STEPS:
- "Run
/api-review to evaluate API design quality."
- "Run
/api-docs to generate or update API documentation."
- "Run
/security-review to audit auth and access control."
- "Run
/dead-code to remove truly orphaned endpoints."
============================================================
SELF-EVOLUTION TELEMETRY
After producing output, record execution metadata for the /evolve pipeline.
Check if a project memory directory exists:
- Look for the project path in
~/.claude/projects/
- If found, append to
skill-telemetry.md in that memory directory
Entry format:
### /api-surface — {{YYYY-MM-DD}}
- Outcome: {{SUCCESS | PARTIAL | FAILED}}
- Self-healed: {{yes — what was healed | no}}
- Iterations used: {{N}} / {{N max}}
- Bottleneck: {{phase that struggled or "none"}}
- Suggestion: {{one-line improvement idea for /evolve, or "none"}}
Only log if the memory directory exists. Skip silently if not found.
Keep entries concise — /evolve will parse these for skill improvement signals.
1---
2name: api-surface
3description: >
4 Maps the entire API surface of a codebase -- route definitions, middleware chains, auth requirements,
5 request/response types, deprecated endpoints, orphaned endpoints, and cross-endpoint inconsistencies.
6
7 USE THIS SKILL WHEN:
8 - You need a complete inventory of all API endpoints in a project
9 - Someone asks "what endpoints do we have?" or "what does our API look like?"
10 - You are onboarding to a new backend codebase and need to understand its API
11 - You need to find orphaned, undocumented, or deprecated endpoints
12 - Someone asks about API inconsistencies (different response shapes, auth gaps)
13 - You are preparing for an API review, documentation sprint, or versioning migration
14 - You need to understand endpoint dependencies before refactoring
15 - A project has no OpenAPI spec and you need to generate one from code
16 - You suspect there are endpoints without authentication or rate limiting
17
18 TRIGGER PHRASES: "API surface", "list all endpoints", "API inventory", "endpoint map",
19 "orphaned endpoints", "API inconsistencies", "undocumented endpoints", "route discovery",
20 "API audit", "middleware matrix", "endpoint dependencies", "API coverage"
21version: "2.0.0"
22category: analysis
23platforms:
24 - CLAUDE_CODE
25metadata:
26 source: https://skillmd.com/skills/aibot88/api-surface
27---
28
29You are an autonomous API surface mapping agent. You discover, catalog, and analyze
30every endpoint in the codebase, producing a complete inventory with dependency graph.
31Do NOT ask the user questions. Investigate the entire codebase thoroughly.
32
33INPUT: $ARGUMENTS (optional)
34If provided, focus on a specific API module or version (e.g., "v2 endpoints", "admin API", "webhooks").
35If not provided, map the entire API surface.
36
37============================================================
38PHASE 1: STACK DETECTION & ROUTE DISCOVERY
39============================================================
40
41Step 1.1 -- Identify the Tech Stack
42
43Read package.json, pubspec.yaml, requirements.txt, go.mod, Cargo.toml, Gemfile, pom.xml.
44Identify the API framework:
45- Node.js: Express, Fastify, Hono, Koa, NestJS
46- Python: Flask, Django, FastAPI
47- Java: Spring Boot
48- Ruby: Rails
49- Go: Gin, Echo, Chi
50- Rust: Actix, Rocket, Axum
51- Elixir: Phoenix
52
53Step 1.2 -- Discover All Route Definitions
54
55Use framework-specific discovery patterns:
56
57**Express/Fastify/Koa/Hono:**
58- Scan for `app.get()`, `app.post()`, `router.get()`, `fastify.route()`, etc.
59- Follow router mounting: `app.use('/api', router)`.
60- Resolve nested routers and prefix chains to compute full paths.
61
62**NestJS:**
63- Scan for `@Controller()`, `@Get()`, `@Post()`, etc. decorators.
64- Resolve module imports and controller prefix chains.
65
66**Django/Flask/FastAPI:**
67- Scan for `urlpatterns`, `@app.route()`, `@router.get()`.
68- Follow `include()` chains in Django.
69
70**Spring Boot:**
71- Scan for `@RequestMapping`, `@GetMapping`, `@PostMapping`.
72
73**Rails:**
74- Parse `config/routes.rb` for resources, get, post, etc.
75
76**GraphQL:**
77- Parse schema.graphql or type definitions for Query/Mutation/Subscription.
78- Map resolvers to their type definitions.
79
80**OpenAPI/Swagger:**
81- Parse openapi.yaml/swagger.json if present.
82- Cross-reference with actual code routes -- flag any mismatches.
83
84Step 1.3 -- Discover Non-HTTP Endpoints
85
86Scan for non-REST entry points:
87- WebSocket handlers
88- gRPC service definitions (.proto files)
89- Message queue consumers (SQS, RabbitMQ, Kafka)
90- Cloud Function triggers (Firestore, S3, scheduled)
91- CLI commands that act as API entry points
92
93============================================================
94PHASE 2: ENDPOINT DETAIL EXTRACTION
95============================================================
96
97For each discovered endpoint, extract ALL of the following:
98
99**Route Details:**
100- HTTP method (GET, POST, PUT, PATCH, DELETE)
101- Full path (with all prefixes resolved)
102- Path parameters (`:id`, `{id}`)
103- Query parameters (name, type, required/optional)
104
105**Middleware Chain:**
106- List every middleware applied, in execution order
107- Auth middleware: type (JWT, session, API key, Firebase, OAuth)
108- Validation middleware: what it validates (body, params, query)
109- Rate limiting: limits and windows
110- CORS: allowed origins
111- Logging: request/response logging enabled?
112
113**Request Type:**
114- Body schema (from TypeScript types, Zod schemas, Joi, class-validator, Pydantic, serializers)
115- Content-Type expected (JSON, form-data, multipart)
116- Required vs. optional fields
117
118**Response Type:**
119- Success response schema and status code
120- Error response schemas and status codes
121- Pagination format (if list endpoint)
122
123**Handler Internals:**
124- Which services/repositories the handler calls
125- Which database tables it reads from or writes to
126- Which external APIs it calls
127- Dependencies on other endpoints (internal calls)
128
129============================================================
130PHASE 3: DEPENDENCY GRAPH
131============================================================
132
133Build a complete endpoint dependency graph covering:
134
135**Inter-Endpoint Dependencies:**
136- Endpoints that call other endpoints internally
137- Endpoints that must be called in sequence (create before update)
138- Endpoints that share database transactions
139
140**Service Dependencies:**
141- Which services each endpoint depends on
142- Shared services across endpoints (high fan-in = fragile)
143- Service fan-out: services called by many endpoints
144
145**Database Dependencies:**
146- Which tables each endpoint reads/writes
147- Endpoints that compete for same table locks (contention risk)
148- Read-only vs. read-write classification per endpoint
149
150**External Dependencies:**
151- Which external APIs each endpoint calls
152- Endpoints that fail if an external service is down (hard dependencies)
153
154============================================================
155PHASE 4: ANOMALY DETECTION
156============================================================
157
158**Orphaned Endpoints:**
159- Endpoints defined in code but never called by any client, frontend, or test
160- Search: frontend code, mobile code, API client libraries, integration tests, OpenAPI consumers, webhook registrations
161- For each orphan: record last modified date (git log) and likely purpose
162- Do NOT flag internal health/metrics endpoints as orphaned
163
164**Inconsistencies:**
165- Same data returned in different shapes from different endpoints
166 (e.g., `/users/:id` returns `{ name }` but `/orders/:id` includes `{ user: { fullName } }`)
167- Same operation available via multiple endpoints with different behavior
168- Auth requirements that differ for similar operations (e.g., one CRUD endpoint requires auth, another does not)
169- Error response formats that vary across endpoints
170
171**Deprecated Endpoints:**
172- Scan for @deprecated markers, TODO comments about removal, version headers
173- Check if deprecated endpoints still have active callers
174- Flag deprecated endpoints without a replacement or migration path
175
176**Undocumented Endpoints:**
177- Endpoints not present in OpenAPI/Swagger spec (if one exists)
178- Endpoints without JSDoc/docstring describing purpose
179
180
181============================================================
182SELF-HEALING VALIDATION (max 2 iterations)
183============================================================
184
185After producing output, validate data quality and completeness:
186
1871. Verify all output sections have substantive content (not just headers).
1882. Verify every finding references a specific file, code location, or data point.
1893. Verify recommendations are actionable and evidence-based.
1904. If the analysis consumed insufficient data (empty directories, missing configs),
191 note data gaps and attempt alternative discovery methods.
192
193IF VALIDATION FAILS:
194- Identify which sections are incomplete or lack evidence
195- Re-analyze the deficient areas with expanded search patterns
196- Repeat up to 2 iterations
197
198IF STILL INCOMPLETE after 2 iterations:
199- Flag specific gaps in the output
200- Note what data would be needed to complete the analysis
201
202============================================================
203OUTPUT
204============================================================
205
206Write the full analysis to `docs/api-surface-map.md` (create `docs/` if needed).
207
208## API Surface Map
209
210### Stack: {detected stack}
211### Total Endpoints: {count}
212### API Versions: {list}
213
214### Endpoint Inventory
215
216| # | Method | Path | Auth | Rate Limit | Request Type | Response Type | Tables | External Deps |
217|---|--------|------|------|-----------|-------------|--------------|--------|---------------|
218| 1 | {GET} | {/api/v1/users} | {JWT} | {100/min} | {none} | {User[]} | {users} | {none} |
219
220### Middleware Matrix
221
222| Endpoint | Auth | Validation | Rate Limit | CORS | Logging |
223|----------|------|-----------|-----------|------|---------|
224| {path} | {type} | {schema} | {limit} | {origins} | {yes/no} |
225
226### Dependency Graph
227
228```
229Endpoint A --calls--> Service X --reads--> Table Y
230 --calls--> External Z
231Endpoint B --calls--> Service X (shared)
232 --calls--> Service W --writes--> Table Y (contention)
233```
234
235### Orphaned Endpoints
236
237| Endpoint | Last Modified | Likely Purpose | Recommendation |
238|----------|-------------|---------------|----------------|
239| {path} | {date} | {purpose} | {remove/document/connect} |
240
241### Inconsistencies
242
243| Issue | Endpoints Involved | Description | Recommendation |
244|-------|-------------------|-------------|----------------|
245| {shape mismatch} | {EP1, EP2} | {description} | {standardize on X} |
246
247### Deprecated Endpoints
248
249| Endpoint | Deprecated Since | Replacement | Active Callers |
250|----------|-----------------|-------------|----------------|
251| {path} | {date/version} | {new path} | {count} |
252
253### Coverage Summary
254- **Documented:** {n}/{total} endpoints
255- **Authenticated:** {n}/{total} endpoints
256- **Rate-limited:** {n}/{total} endpoints
257- **Tested:** {n}/{total} endpoints (from test file analysis)
258
259### Security Flags
260- Endpoints without authentication: [list]
261- Endpoints without rate limiting: [list]
262- Endpoints accepting file uploads without size limits: [list]
263
264DO NOT:
265- Miss routes registered dynamically (scan for string patterns, not just static route defs).
266- Ignore middleware applied at the app level (affects all routes).
267- Flag internal health/metrics endpoints as orphaned.
268- Assume OpenAPI spec is complete -- always cross-reference with actual code.
269
270NEXT STEPS:
271- "Run `/api-review` to evaluate API design quality."
272- "Run `/api-docs` to generate or update API documentation."
273- "Run `/security-review` to audit auth and access control."
274- "Run `/dead-code` to remove truly orphaned endpoints."
275
276
277============================================================
278SELF-EVOLUTION TELEMETRY
279============================================================
280
281After producing output, record execution metadata for the /evolve pipeline.
282
283Check if a project memory directory exists:
284- Look for the project path in `~/.claude/projects/`
285- If found, append to `skill-telemetry.md` in that memory directory
286
287Entry format:
288```
289### /api-surface — {{YYYY-MM-DD}}
290- Outcome: {{SUCCESS | PARTIAL | FAILED}}
291- Self-healed: {{yes — what was healed | no}}
292- Iterations used: {{N}} / {{N max}}
293- Bottleneck: {{phase that struggled or "none"}}
294- Suggestion: {{one-line improvement idea for /evolve, or "none"}}
295```
296
297Only log if the memory directory exists. Skip silently if not found.
298Keep entries concise — /evolve will parse these for skill improvement signals.