Back to cookbook

AI Prompt to Generate API Documentation From Source Code

0 views Updated

Make this prompt yours

Share

This AI prompt for API documentation turns a block of source code (a function, a class, a set of REST route handlers) into clear, structured reference docs. It's built for backend and full-stack developers who have working code but no written documentation, and for teams onboarding new engineers who need to understand an endpoint's inputs, outputs, and failure modes without reading the implementation line by line.

Instead of asking the model to "document this code" and hoping for consistent formatting, the prompt specifies the exact sections every entry must include: a one-line summary, parameters with types, return values, error conditions, and a usage example. This keeps ChatGPT, Claude, or Gemini from skipping edge cases or inventing behavior the code doesn't actually have β€” the model is instructed to describe only what the code does, not what a typical API of that kind might do.

Because the output needs to come back as consistent Markdown or JSON across many functions in a codebase, it helps to lock down that structure before you run the prompt at scale; the Prompt Formatter can convert your draft instructions into a strict Markdown or JSON template so every generated doc entry follows the same schema.

Prompt template

Make this prompt yours

prompt-template
300 tokens
ROLE: You are a technical writer who specializes in developer-facing API documentation. CONTEXT: Language/framework: [PROGRAMMING LANGUAGE AND FRAMEWORK, e.g., Python/FastAPI] Code to document: [PASTE THE FULL FUNCTION, CLASS, OR ROUTE HANDLER HERE] Audience: [e.g., external API consumers / internal engineering team / open-source contributors] TASK: Document the code above. Base every statement only on what the code actually does β€” do not assume standard behavior that isn't present in the code itself. For each function or endpoint, produce: 1. SUMMARY: one sentence describing its purpose 2. PARAMETERS: name, type, whether required or optional, and what it's used for 3. RETURNS: the type and shape of the return value or response 4. ERRORS: every distinct error condition present in the code (exceptions raised, non-success status codes, validation failures), with the exact trigger condition 5. EXAMPLE: a realistic call or request with sample input and the resulting output CONSTRAINTS: - If a parameter's type or default value is ambiguous in the code, flag it as [NEEDS CLARIFICATION] rather than guessing - Do not add a 'notes' or 'best practices' section unless explicitly asked - Keep the summary to one sentence OUTPUT FORMAT: Return the documentation in [MARKDOWN / JSON / OPENAPI YAML] using this exact section order: Summary, Parameters, Returns, Errors, Example.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
158 tokens
Language/framework: Python/FastAPI Code to document: @app.post("/users/{user_id}/orders") async def create_order(user_id: int, order: OrderCreate): user = await db.get_user(user_id) if not user: raise HTTPException(status_code=404, detail="User not found") if order.quantity <= 0: raise HTTPException(status_code=400, detail="Quantity must be positive") if user.credit_balance < order.quantity * order.unit_price: raise HTTPException(status_code=402, detail="Insufficient credit balance") new_order = await db.create_order(user_id, order) return {"order_id": new_order.id, "status": "created"} Audience: internal engineering team Output format: Markdown

Example output

example-output
234 tokens

POST /users/{user_id}/orders

Summary: Creates a new order for a user after validating their identity, order quantity, and available credit balance.

Parameters

  • user_id (int, required, path) β€” the ID of the user placing the order
  • order (OrderCreate, required, body) β€” contains quantity (number) and unit_price (number)

Returns

  • 200 OK with JSON body: {"order_id": <int>, "status": "created"}

Errors

  • 404 Not Found β€” raised when no user exists for the given user_id
  • 400 Bad Request β€” raised when order.quantity is zero or negative
  • 402 Payment Required β€” raised when the user's credit_balance is less than quantity * unit_price

Example

POST /users/482/orders
{
  "quantity": 3,
  "unit_price": 19.99
}

Response: 200 OK
{
  "order_id": 9931,
  "status": "created"
}

When to use it

  • You have working, tested code but no written reference docs for its public functions or endpoints
  • You're preparing a library or internal API for other developers to consume and need consistent entries
  • You've just finished a sprint of new endpoints and need documentation before a release or handoff
  • You want a first draft of docstrings or a README's API section that you'll edit rather than write from scratch

Best practices

  • Paste the complete function or route handler, including type annotations and existing comments, so the model isn't guessing at parameter types
  • Explicitly tell the model to document only observable behavior in the code, not assumed behavior from similar APIs it has seen before
  • Ask for one documented error case per actual error path in the code (a thrown exception, a non-200 response, a validation failure) rather than a generic 'may throw an error' line
  • Run a batch of functions through the same prompt and spot-check for format drift; the Prompt Debugger can flag vague instructions in your template before they cause inconsistent output across dozens of functions

Common mistakes

  • Pasting only the function signature instead of the full body, which forces the model to guess at side effects and error handling
  • Not specifying an output format, resulting in docs that mix prose paragraphs, bullet lists, and tables across different functions
  • Accepting a documented parameter type without checking it against the actual code, especially for loosely typed languages like JavaScript or Python
  • Skipping the request for usage examples, which are often the most useful part of documentation for a developer unfamiliar with the API

FAQs

How do I get an AI model to document code without making up behavior it doesn't have?

Paste the complete function body, not just the signature, and explicitly instruct the model to describe only behavior that is visible in the code. Adding a rule like "flag anything ambiguous as [NEEDS CLARIFICATION] instead of guessing" significantly reduces invented parameter descriptions and fabricated default values.

Can this prompt generate OpenAPI/Swagger specs instead of Markdown?

Yes. Change the output format instruction to request OpenAPI YAML or JSON Schema and the model will map the same summary, parameters, returns, and errors into the equivalent OpenAPI fields, as long as you specify the OpenAPI version you're targeting.

Which AI model is best for generating API documentation from code?

Claude, ChatGPT, and Gemini can all follow this structured template effectively since the task is format-driven rather than requiring specialized domain knowledge. The more important factor is how completely you paste the source code, since all three models document only what they can see.

How do I keep documentation consistent across dozens of functions in a large codebase?

Lock the output format down before running the prompt at scale. Reusing the exact same section order and headings for every function prevents drift, and spot-checking a sample batch against the actual code catches cases where the model inferred behavior instead of reading it.

Which Cuelara tool can help me tighten this prompt before running it across many functions?

Prompt Formatter β€” converts your documentation instructions into a strict Markdown, JSON, or XML template so every function's output follows the identical structure. Prompt Debugger β€” scans the prompt itself for vague constraints that could let the model guess at behavior instead of reading the code.

Found this prompt useful? Share it.

Share

More in Code Generation & Software Engineering

Code Generation & Software Engineering

Prompt to Generate Unit Tests From a Function

This prompt turns an existing function into a set of unit tests covering its normal behavior, edge cases, and error handling, built for deve…

You are a senior software engineer writing unit tests.

Function to test:
[PASTE THE FUNCTION CODE]

Language and test framework: [E.G. TYPESCRIPT WITH VITEST, PYTHON WITH PYTEST]

Instructions:
1. Write tests covering normal, expected inputs.
2. Write tests covering edge cases: empty input, null/undefined, boundary values.
3. Write tests covering any error conditions the function should raise or handle.
4. Use clear, descriptive test names that state what is being verified.
5. Return only the test code, in a single code block, ready to run.

Output format: one fenced code block containing the complete test file.

Make this prompt yours

Code Generation & Software Engineering

Claude Prompt to Refactor Legacy Code for Readability and Maintainability

This Claude prompt for refactoring legacy code is built for developers who've inherited a function or module that works but is hard to read,…

Role: You are a senior software engineer specializing in code readability and maintainability.

Context:
Language/framework: [LANGUAGE_AND_VERSION]
Style guide or conventions to follow: [STYLE_GUIDE_OR_LINTING_RULES]
What this code does: [BRIEF_DESCRIPTION_OF_FUNCTIONALITY]
Constraints (things that must not change): [PUBLIC_API_SIGNATURES_OR_OTHER_CONSTRAINTS]

Code to refactor:
[PASTE_FULL_FUNCTION_OR_FILE_HERE]

Instructions:
1. Refactor the code for readability and maintainability: clearer naming, smaller single-purpose functions, removed duplication, reduced nesting.
2. Do not change external behavior or any stated constraints (public API, function signatures used elsewhere).
3. List each change you made, one by one, with a short reason for it.
4. Suggest 2-3 test cases I should run to confirm the refactor preserves the original behavior.
5. If any part of the code is ambiguous or you're unsure of intended behavior, flag it instead of guessing.

Output format:
1. Refactored code in a fenced code block
2. A numbered list of changes with a one-line reason for each
3. Suggested test cases

Make this prompt yours

Code Generation & Software Engineering

ChatGPT Prompt to Review Code for Bugs, Style, and Security Issues

This code review prompt turns ChatGPT, Claude, or Gemini into a thorough reviewer that checks a diff or file for bugs, style problems, and s…

You are an experienced software engineer performing a code review. Review the following code change for issues a careful human reviewer would catch before approving a pull request.

Context:
- Language/framework: [LANGUAGE AND FRAMEWORK]
- Style guide or conventions to follow: [STYLE GUIDE, e.g. PEP 8, Airbnb JS, or "none specified"]
- Purpose of this change: [ONE-SENTENCE DESCRIPTION OF WHAT THE CHANGE DOES]

Code to review:
[PASTE DIFF OR FULL FILE CONTENTS HERE]

Review the code across these categories, in this order:
1. Correctness β€” logic errors, edge cases, off-by-one errors, null/undefined handling
2. Security β€” injection risks, unvalidated input, broken access control, exposed secrets
3. Readability β€” unclear naming, missing comments where logic is non-obvious, overly complex functions
4. Performance β€” unnecessary loops, redundant computation, inefficient queries
5. Test coverage β€” missing tests for new logic or edge cases

Constraints:
- Cite the specific line number or exact code snippet for every finding
- Label each finding as Blocking, Should-fix, or Nitpick
- Do not rewrite the code β€” describe the issue and suggest a fix in words
- If a category has no issues, state that explicitly rather than skipping it

Output format:
For each category, list findings as:
[Severity] Line/snippet: [code reference]
Issue: [what's wrong]
Suggested fix: [brief description]

End with a one-line overall verdict: Approve, Approve with comments, or Request changes.

Make this prompt yours