Back to cookbook

AI Prompt to Generate API Documentation From Source Code

0 views Published

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

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

AI Prompt to Write a GitHub Actions CI/CD Workflow from Plain English

This is a prompt for turning a plain English description of your build, test, and deploy process into a working GitHub Actions workflow YAML…

Role: You are a DevOps engineer writing a GitHub Actions workflow file.

Context:
Project type: [LANGUAGE/FRAMEWORK, e.g. Node.js with npm, Python with Poetry]
Repository structure notes: [e.g. monorepo with /api and /web folders, single app at root]
Runner: [e.g. ubuntu-latest]

Task:
Write a GitHub Actions workflow (.github/workflows/[FILENAME].yml) that does the following, in this order:
1. Trigger on: [TRIGGER EVENTS, e.g. pull_request to main, push of tags matching v*]
2. Job 1 - [JOB NAME, e.g. lint]: [WHAT IT DOES]
3. Job 2 - [JOB NAME, e.g. test]: [WHAT IT DOES], must run only after Job 1 succeeds
4. Job 3 - [JOB NAME, e.g. deploy]: [WHAT IT DOES], must run only after Job 2 succeeds and only on [CONDITION, e.g. tag pushes to main]

Secrets/environment variables needed (reference by name only, do not invent values): [SECRET NAMES, e.g. DEPLOY_TOKEN, AWS_ACCESS_KEY_ID]

Constraints:
- Pin third-party actions to a specific major version (e.g. actions/checkout@v4)
- Use caching for dependencies where the ecosystem supports it
- Keep job names and step names descriptive enough to read clearly in the Actions UI

Output format:
Return the complete YAML file in a fenced code block, followed by a short bullet list explaining what each job does and when it runs.

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Debug a Failed Vercel Deployment Using Vercel's MCP Server

This Vercel MCP prompt helps developers and DevOps engineers figure out why a deployment failed without manually scrolling through build log…

ROLE: You are a deployment troubleshooting assistant with access to Vercel's MCP server.

CONTEXT:
- Project: [PROJECT_NAME]
- Framework: [FRAMEWORK, e.g. Next.js 14]
- Deployment ID or URL: [DEPLOYMENT_ID_OR_URL]
- Last known good deployment: [PREVIOUS_DEPLOYMENT_ID_OR_URL, or 'none']
- What changed since the last successful deploy: [RECENT_CHANGES_SUMMARY]

TASK:
1. Retrieve the build and runtime logs for the failing deployment.
2. Identify the failure category: build error, runtime error, environment/configuration issue, or dependency issue.
3. Quote the specific log lines that show the root cause.
4. If a last known good deployment is provided, compare configuration and environment variables between the two.
5. Propose a ranked list of likely fixes, most probable first.

CONSTRAINTS:
- Do not guess at a cause without quoting supporting log evidence.
- Flag if critical information (e.g. an environment variable value) is missing rather than assuming it.

OUTPUT FORMAT:
- Failure category
- Root cause (with quoted log evidence)
- Ranked fix recommendations
- Any missing information needed to confirm the diagnosis

Make this prompt yours

Code Generation & Software Engineering

ChatGPT Prompt to Generate a Production-Ready Dockerfile for Your App

This Dockerfile generator prompt gives ChatGPT, Claude, or Gemini everything needed to write a secure, production ready Dockerfile for your…

You are an expert DevOps engineer who writes secure, production-ready Dockerfiles.

Context:
- Application language and version: [LANGUAGE AND VERSION, e.g., Node.js 20]
- Framework: [FRAMEWORK, e.g., Express, Django, Spring Boot]
- Package manager: [PACKAGE MANAGER, e.g., npm, pip, Maven]
- Target deployment platform: [PLATFORM, e.g., AWS ECS, Kubernetes, linux/amd64]
- Special requirements: [e.g., private package registry, native dependencies, health checks]

Task:
Write a production-ready Dockerfile for this application. Use a multi-stage build that separates the build/dependency-install stage from the final runtime stage. The final image should:
1. Use the smallest reasonable base image for the runtime.
2. Run as a non-root user.
3. Only copy the files needed to run the application, not build tools or source maps.
4. Include a HEALTHCHECK instruction appropriate for this type of service.
5. Set any necessary environment variables and expose the correct port.

Constraints:
- Do not use the "latest" tag for any base image; pin a specific version.
- Keep the final image size as small as possible.
- Explain, in a short comment above each non-obvious instruction, why it's there.

Output format:
1. The complete Dockerfile in a single code block.
2. A short bullet list explaining the base image choice and any trade-offs.
3. One suggested .dockerignore entry list for this stack.

Make this prompt yours