Back to cookbook

AI Prompt to Generate an OpenAPI Spec From Existing API Code

0 views Updated

Make this prompt yours

Share

This OpenAPI spec generator prompt tells ChatGPT, Claude, or Gemini how to read your existing API route handlers, controllers, or endpoint functions and produce a clean, versioned OpenAPI (Swagger) specification instead of guessing at a schema from scratch. It's built for backend developers, API maintainers, and teams who inherited undocumented endpoints and need a spec that actually matches the code, not a hand-written approximation that drifts out of date.

The prompt forces the model to work endpoint by endpoint: extract the HTTP method and path, infer request parameters and body shape from the function signature and any validation logic, infer response shapes from what the handler actually returns (including error responses), and flag anything it can't determine with confidence rather than inventing a plausible-looking field. That last part matters — a generated spec with confidently wrong types is worse than no spec, because downstream consumers (client SDKs, mock servers, contract tests) will trust it.

Because the output is YAML or JSON that other tools parse, keeping the prompt itself tight and unambiguous is worth the extra pass. If you're pasting in a large controller file or a verbose instruction set, running it through Prompt Optimizer in Coding mode first can tighten the constraints before you hand it to the model.

Prompt template

Make this prompt yours

prompt-template
261 tokens
ROLE You are an API documentation specialist who writes precise OpenAPI 3.x specifications strictly from the code provided. CONTEXT Language/framework: [LANGUAGE_AND_FRAMEWORK] Source code for this route group: [PASTE_ROUTE_OR_CONTROLLER_CODE] Existing spec file to extend, if any: [EXISTING_OPENAPI_FILE_OR_NONE] TASK For each endpoint in the provided code: 1. Identify the HTTP method, path, and path/query parameters with their types 2. Infer the request body schema from validation logic, type annotations, or serializers 3. Infer every possible response, including success and all error status codes the handler can return 4. Mark any field you cannot determine with confidence as [NEEDS REVIEW] in a comment rather than guessing CONSTRAINTS - Do not invent fields, parameters, or response codes that are not implied by the code - Use OpenAPI 3.1 syntax unless [OPENAPI_VERSION] specifies otherwise - Reuse and reference shared schemas with $ref instead of duplicating object definitions - Keep descriptions factual and based only on what the code does, not assumed business intent OUTPUT FORMAT Return a single valid YAML OpenAPI document, followed by a short bullet list titled 'Needs Human Review' for anything flagged uncertain.

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
157 tokens
LANGUAGE_AND_FRAMEWORK: Node.js, Express PASTE_ROUTE_OR_CONTROLLER_CODE: router.post('/invoices/:customerId', validateInvoiceBody, async (req, res) => { const { customerId } = req.params; const { items, dueDate, notes } = req.body; if (!items || items.length === 0) return res.status(400).json({ error: 'items required' }); const invoice = await InvoiceService.create(customerId, items, dueDate, notes); if (!invoice) return res.status(404).json({ error: 'customer not found' }); res.status(201).json(invoice); }); EXISTING_OPENAPI_FILE_OR_NONE: none OPENAPI_VERSION: 3.1

When to use it

  • You inherited a REST API with no OpenAPI/Swagger file and need one before onboarding a client team
  • A frontend or mobile team needs an accurate contract to generate typed client SDKs against
  • You're setting up contract testing or a mock server and need a spec that reflects real behavior, not intent
  • You've added or changed several endpoints and the existing spec file has drifted out of sync

Best practices

  • Paste the actual handler/controller code, not a description of it — the model should infer types from real validation and serialization logic
  • Process one resource or route group per prompt run rather than an entire codebase at once, so context limits don't force the model to summarize instead of read carefully
  • Explicitly ask for every error response path (4xx/5xx) the handler can produce, since models tend to document only the happy path unless told otherwise
  • Validate the generated YAML against an OpenAPI linter (such as Spectral) before committing it — treat the model's output as a strong first draft, not a final artifact

Common mistakes

  • Accepting field types the model guessed without checking them against the actual validation or ORM schema in the code
  • Skipping authentication and header requirements because the prompt didn't mention them, leaving the spec incomplete for client generation
  • Feeding in minified or transpiled code instead of the original source, which strips the variable names the model needs to infer meaning
  • Generating the whole spec in one shot for a large API, which causes the model to drop or merge endpoints it ran out of room to document

FAQs

Can ChatGPT generate an OpenAPI spec directly from my code?

Yes, if you paste the actual route or controller code rather than describing it. The model can infer parameter types, request bodies, and status codes from the logic, though it should flag anything it can't confirm instead of guessing.

What's the difference between generating OpenAPI from code versus from an API description?

Generating from code produces a spec that matches real behavior, including edge cases and error responses the handler actually returns. Generating from a description only captures what you remember to mention, which is why drift happens in the first place.

How do I keep an AI-generated OpenAPI spec from drifting out of date again?

Re-run the prompt whenever a route changes and diff the output against the committed spec file, or wire the prompt into a pre-merge check so undocumented endpoint changes get caught before they ship.

Which Cuelara tool can help me tighten this prompt before running it on a large codebase?

Prompt Optimizer — its Coding mode is built for exactly this kind of structured, constraint-heavy developer prompt, and tightens vague instructions before you spend tokens on a long code paste.

Found this prompt useful? Share it.

Share

More in Code Generation & Software Engineering

Code Generation & Software Engineering

AI Prompt to Generate a Regular Expression From a Plain-English Description

This regex generator prompt is for developers who know exactly what pattern they need to match but don't want to hand write and debug regex…

ROLE: You are a regular expression expert who writes precise, well-documented patterns.

CONTEXT:
I need a regular expression for this matching rule: [DESCRIBE WHAT THE PATTERN SHOULD MATCH IN PLAIN ENGLISH].
Target regex flavor/language: [E.G., JAVASCRIPT, PYTHON RE, PCRE, POSIX].

Strings that SHOULD match:
[LIST 3-5 EXAMPLE STRINGS]

Strings that should NOT match:
[LIST 3-5 EXAMPLE STRINGS]

TASK:
1. Write a regular expression that matches all the "should match" strings and rejects all the "should not match" strings.
2. Break down the pattern piece by piece, explaining what each group, anchor, and character class does.
3. Test the pattern mentally against every example I gave and confirm the result for each.
4. List any realistic edge cases my examples didn't cover that could still break this pattern, and note how the pattern handles them.

OUTPUT FORMAT:
- The regex pattern in a code block
- A numbered breakdown of each part of the pattern
- A table confirming match/no-match for each example string
- A short "Edge cases to watch for" list

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Turn a Linear Ticket Into an Implementation Plan Using Linear's MCP Server

This prompt turns a raw Linear ticket into a concrete implementation plan before any code gets written. It's built for developers and tech l…

ROLE
You are a senior software engineer producing an implementation plan from a project management ticket before any code is written.

CONTEXT
- Ticket source: Linear, accessed via the connected MCP server
- Ticket ID or URL: [TICKET_ID_OR_URL]
- Target repository or service: [REPO_OR_SERVICE_NAME]
- Relevant tech stack: [LANGUAGE_FRAMEWORK_STACK]

TASK
1. Read the ticket's title, description, comments, labels, and any linked parent or sub-issues from the connected Linear MCP server.
2. Summarize the current requirements in 3-5 sentences, noting anything that changed from the original description.
3. Propose an implementation approach: the files or modules likely affected, in order of change.
4. List edge cases and error conditions the implementation must handle.
5. List open questions that should be posted back to the ticket before work starts.

CONSTRAINTS
- Do not invent requirements that are not stated in the ticket or its comments.
- If acceptance criteria are missing or ambiguous, say so explicitly instead of assuming an answer.
- Keep the file/module list specific to what the ticket's labels and linked repo indicate; do not list unrelated parts of the codebase.
- Flag any blocking dependency on another open ticket.

OUTPUT FORMAT
## Ticket Summary
[3-5 sentence summary]

## Implementation Approach
- [Ordered list of files/modules and what changes in each]

## Edge Cases
- [List]

## Open Questions
- [List, or "None" if genuinely none]

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Triage Production Errors Using Sentry's MCP Server

This AI prompt is for developers and on call engineers who connect an AI assistant to Sentry's MCP server and want a fast, consistent first…

ROLE: You are a software engineer triaging production error reports retrieved through Sentry's MCP integration.

CONTEXT:
- Project: [PROJECT NAME]
- Time window: [E.G. LAST 24 HOURS]
- Current release/deploy: [VERSION, DEPLOY TIME]
- Known pre-existing low-priority issues to exclude: [LIST OR 'NONE']

TASK:
1. Retrieve open issues for the specified project and time window via the MCP connection, including stack trace, event count, affected users, and first-seen timestamp.
2. Group issues that share the same root exception type and call path as a single item.
3. For each grouped issue, state what the stack trace shows is happening, which file/function is implicated, and your confidence level in that read (high/medium/low).
4. Rank issues by severity using event count, affected user count, and whether first-seen falls after the stated deploy time.
5. Exclude any issue listed as a known pre-existing low-priority issue, but note it was excluded.

CONSTRAINTS:
- Do not propose a specific code fix; describe what the trace indicates and flag it for the responsible engineer.
- Do not rank an issue as high severity solely because of the error message tone; use the stated metrics.
- If stack trace data is incomplete or truncated, say so instead of inferring the missing frames.

OUTPUT FORMAT:
- Triage Summary (total issues reviewed, number flagged as new since deploy)
- Ranked Issue List (issue title, severity, event count, affected users, confidence in root cause read)
- Excluded Known Issues (if any)
- Issues Needing Manual Trace Review (low-confidence reads)

Make this prompt yours