All posts
prompt-engineeringapi-docsllm

API Documentation Prompts: Ready-to-Use Templates

Copy-paste api documentation prompts with real examples, plus what to change for your own use case.

SR

Suhail Roushan

August 6, 2026

·
7 min read
·
0 views

Writing API docs is the least favorite task for most developers. These ready-to-use API Documentation Prompts turn that chore into a 10-minute job with consistent, accurate output.

Writing API documentation feels like pulling teeth — you know the endpoint logic, but translating it into clear prose takes forever. I've tested dozens of prompt patterns with Claude, GPT-4, Gemini, and DeepSeek, and the templates below consistently produce production-ready docs. They're designed to eliminate the back-and-forth that wastes your time and token budget.

Why Generic Prompts Fail Here

"Write documentation for this API" is a garbage prompt. Here's what happens:

  • The LLM invents parameters that don't exist in your code
  • It writes flowery marketing copy instead of technical reference material
  • Response format varies wildly between runs, making review harder than writing from scratch
  • It omits error handling, rate limits, and auth details — the parts that actually matter

These failures happen because generic prompts lack constraint and context. Your API has specific shapes, types, and edge cases. The templates below force the LLM to work within your actual contract, not its imagination.

Template 1: The Contract-First Documenter

This template works best when you have a clean OpenAPI/Swagger spec or TypeScript types to feed in. It forces the LLM to stick to your actual schema.

You are a senior technical writer documenting a REST API.

Given the following OpenAPI spec (or TypeScript type definitions), produce documentation with EXACTLY this structure:

## Endpoint: {METHOD} {path}
### Purpose
One sentence: what this endpoint does and when to use it.

### Request Parameters
| Name | Type | Required | Description |
|------|------|----------|-------------|
(Only include parameters that exist in the spec. Do not invent any.)

### Request Example
```json
{valid JSON example using only spec-defined fields}

Response Example

{valid success response — 200/201 only}

Error Codes

| Code | Meaning | When it occurs | |------|---------|----------------| (Only include errors explicitly defined in the spec.)

Rate Limits

(State limits if present in spec, otherwise write "Not specified.")

RULES:

  • Do NOT add fields, parameters, or endpoints that are not in the source spec.
  • Keep descriptions under 15 words each.
  • Use JSON for all examples — no XML, no YAML.
  • If the spec is missing auth details, write "Auth: Not specified in source."

HERE IS THE SPEC: {PASTE YOUR OPENAPI SPEC OR TYPESCRIPT TYPES HERE}


**Placeholder breakdown:** The `{METHOD}` and `{path}` slots get filled per endpoint. The `{PASTE YOUR SPEC HERE}` block is where you drop your OpenAPI YAML or exported TypeScript interfaces. This template works best for REST APIs with standard CRUD operations.

## Template 2: The Code-Reading Extractor

When you don't have a spec — just a route handler file — this template extracts docs directly from implementation code. It's ideal for Express, FastAPI, or NestJS backends.

```text
You are documenting an existing API endpoint from its source code.

Read the following route handler code and produce documentation that matches the implementation EXACTLY.

## Endpoint Summary
- Method and path (extract from the route decorator or router call)
- One-sentence purpose based on WHAT THE CODE DOES, not what you think it should do.

## Request Validation Rules
List every validation check in the code (e.g., "email must match regex", "id must be integer"). For each, state:
- The exact condition
- The error response returned when it fails

## Expected Request Shape
Based on the destructured properties or request.body usage, list:
- Every field accessed
- Its inferred type (from validation logic or usage)
- Whether it's required (code throws/returns error if missing?)

## Response Shape
- What does the success path return? Copy the exact object structure.
- What status code is used?

## Error Handling
- Every try/catch block: what triggers it, what gets returned
- Any custom error classes or next(error) calls

## Side Effects
- Database writes, external API calls, file operations. List them all.

RULES:
- If the code reads a field, document it. If the code never touches it, do NOT mention it.
- Quote variable names exactly as they appear in the code.
- Do not add "best practices" suggestions — only what exists.

HERE IS THE CODE:
{PASTE YOUR ROUTE HANDLER CODE}

This template shines for legacy codebases where the spec is outdated or nonexistent. It reads what's actually there, not what should be there.

Template 3: The Edge-Case Auditor

This is for the hard scenario — you have existing docs but you suspect they're incomplete or you need to document error paths that aren't obvious.

You are auditing API documentation for completeness and accuracy.

Given the route handler code AND the existing documentation below, identify:

1. **Missing Endpoints**: Any routes defined in the code that are absent from the docs.
2. **Undocumented Parameters**: Query params, headers, or body fields the code reads but the docs don't mention.
3. **Incorrect Response Codes**: Docs say 200 but code returns 201? Docs omit 422? List every mismatch.
4. **Error Handling Gaps**: Code has try/catch blocks that return specific errors, but docs don't list them.
5. **Auth Flaws**: If the code checks for an API key or JWT, does the doc mention it? If not, flag it.

OUTPUT FORMAT:

## Discrepancy Report
| # | Type | Location (file:line) | What Code Says | What Docs Say | Severity |
|---|------|---------------------|----------------|---------------|----------|

## Missing Documentation Blocks
For each discrepancy with severity HIGH or MEDIUM, write the corrected documentation section using this format:

### {Endpoint} — {Issue}
**Current docs say:** {quote}
**What it should say:** {corrected text, matching code behavior}

## Unverified Claims
List any doc statements you cannot verify from the provided code. Mark these as "UNVERIFIED — needs manual check."

RULES:
- Only flag issues where you have evidence from the code.
- Do not restate correct documentation — only list discrepancies.
- Be specific: quote the exact line from both code and docs.

HERE IS THE CODE:
{PASTE ROUTE HANDLER CODE}

HERE IS THE EXISTING DOCUMENTATION:
{PASTE CURRENT DOCS}

Use this when you've inherited a project with stale docs, or before a public API release to catch gaps.

How to Adapt These for Your Own Codebase

The templates are starting points, not magic bullets. Here's what I've found works:

  • Replace the output format with your company's doc style guide. If you use Redocly or Stoplight, paste your linting rules into the prompt.
  • Add your tech stack context. One line like "This is an Express app using Zod for validation" helps the LLM infer patterns correctly.
  • Feed multiple files at once. For Template 2, paste the route file plus the validation schema file — you'll get more accurate type information.
  • Iterate in batches. Don't run one endpoint at a time. Paste 5–10 endpoints and ask for all their docs in one response. You'll get consistent tone and structure across the whole set.
  • Save your best outputs as few-shot examples. If you have a perfectly written doc page, include it in the prompt as "Here's an example of the expected quality."

Do These Prompts Work With Any LLM?

Yes, but with caveats. Claude 3.5 Sonnet and GPT-4 handle the structured output formats most reliably — they follow the exact table and heading syntax without drifting. Gemini works well but occasionally adds extra commentary you didn't ask for. DeepSeek is fast and decent for Template 1, but I've seen it hallucinate parameters more often on Template 2, so verify its output against your code.

The biggest variable is context window. Template 3 needs enough room for both code and docs — you'll want at least 8k tokens of context for that one. If you're on a smaller model, split the code into chunks and run the audit per file.

The one adjustment that improves these prompts the most: add a single line at the end saying "Return only the documentation. No preamble, no closing remarks, no markdown code fences around your response." It cuts token waste and makes the output directly paste-ready.

Related posts

Written by Suhail Roushan — Full-stack developer. More posts on AI, Next.js, and building products at suhailroushan.com/blog.

Get in touch