Blenra LogoBlenra
Cloud & DevOps

AI-Powered API Design: Swagger and OpenAPI Generation Prompts

By Naveen Teja Palle5 min read
OpenAPI Swagger specification generation visualization with REST API endpoint cards

Writing comprehensive OpenAPI/Swagger documentation by hand is a massive time sink. See how engineered prompts can instantly convert plain-text requirements or backend code into pristine Swagger YAML.

Why API Documentation Is Universally Hated

There is a running joke in engineering teams that API documentation gets written 3 weeks after the API ships, by a developer who vaguely remembers what the endpoints do, when a customer can't figure out how to integrate. The root cause isn't laziness — it's that writing OpenAPI YAML by hand is genuinely tedious and error-prone.

A single complete OpenAPI 3.0 YAML for a production API with 15–20 endpoints, proper schemas, security definitions, and example payloads can run to 800–1,200 lines. Writing this correctly requires expertise in JSON Schema validation syntax, OpenAPI spec nuances, and deep knowledge of every endpoint's behaviour — usually spread across multiple developers' heads.

AI changes this equation dramatically. A well-prompted model can reverse-engineer a complete, accurate OpenAPI specification from raw controller code in seconds, and generate a “design-first” schema from a plain-English domain description. The prompts below have been tested across Express.js, FastAPI, NestJS, and Spring Boot backends.

What a Complete OpenAPI 3.0 Spec Requires

Before prompting AI, know what “complete” actually means. Many AI-generated specs are missing these critical sections:

openapi + info

Version string, title, description, contact, license

servers

Base URLs for production, staging, local environments

components/schemas

Reusable data model definitions with validation

⚠ Most AI tools omit this

components/securitySchemes

BearerAuth, ApiKey, OAuth2 definitions

⚠ Most AI tools omit this

paths

All endpoints with request bodies and response schemas

⚠ Most AI tools omit this

Error responses

400, 401, 403, 404, 422, 500 documented per path

⚠ Most AI tools omit this

Prompt 1: Reverse-Engineer Existing Code to Swagger YAML

The most immediately valuable use case. Paste your controller code and get complete, production-ready documentation in seconds. The key is explicitly listing every section — otherwise AI will skip security schemes and error responses.

"Act as an API Documentation Specialist with 10 years of OpenAPI 3.0 experience. Read the Express.js controller code I am about to provide and generate a complete OpenAPI 3.0 YAML specification. Requirements — include ALL of the following: 1. info: section with title, version 1.0.0, description 2. servers: production (https://api.myapp.com/v1) and local (http://localhost:3000) 3. components/securitySchemes: BearerAuth (http scheme, bearer format) 4. components/schemas: Reusable object schemas for every request/response body 5. Under each path: - All HTTP verbs present in code - operationId for each in camelCase - security: [{ BearerAuth: [] }] for protected routes - requestBody with full schema reference and application/json content type - responses: 200 with example payload, 400 validation error, 401 unauthorized, 500 server error Output ONLY valid YAML. [PASTE YOUR CONTROLLER CODE HERE]"

💡 Always Validate with editor.swagger.io

Copy any AI-generated Swagger YAML and paste it directly at editor.swagger.io. It renders the full Swagger UI instantly and highlights any malformed YAML or spec violations in the left panel. Copy the error line back to the AI with “Fix this error on line X:” — most spec errors are correctable in one follow-up message.

Prompt 2: Design-First API from a Business Domain

The “API Design First” methodology establishes the contract before writing a single line of backend code. This prompt aligns front-end and back-end teams on the API shape simultaneously.

"You are an API Architect. Generate a complete OpenAPI 3.0 YAML for a new 'E-commerce Cart' microservice using API-First design. Domain specification: - Service base URL: /api/v1 - Endpoints: GET /cart, POST /cart/items, PATCH /cart/items/{itemId}, DELETE /cart/items/{itemId}, POST /cart/checkout Data models: - Cart: { id: uuid, userId: uuid, items: CartItem[], totalPrice: number, currency: 'USD' | 'EUR', updatedAt: datetime } - CartItem: { id: uuid, productId: uuid, productName: string, quantity: number min 1 max 99, unitPrice: number } - AddItemRequest: { productId: uuid, quantity: number } - CheckoutRequest: { paymentMethodId: string, shippingAddressId: uuid } Rules: - X-Customer-ID header required on all requests - quantity: minimum 1, maximum 99 - Include page/limit query params on GET /cart - Complete error response schemas (400, 401, 404, 409 out-of-stock)"

Prompt 3: Generating NestJS Decorators from an OpenAPI Schema

The reverse workflow: you have an existing OpenAPI spec and need NestJS controller code with matching decorators. This accelerates implementation against a provided API contract:

"Act as a NestJS Senior Engineer. Read the OpenAPI 3.0 YAML spec I provide and generate the matching NestJS controller. Requirements: 1. @Controller with correct route prefix matching spec paths 2. @ApiTags, @ApiOperation, @ApiResponse on every method 3. @ApiBearerAuth() on protected endpoints 4. @Body() DTOs with @ApiProperty() on all fields matching spec request schemas 5. @Query() with @ApiQuery() for all query parameters in spec 6. class-validator decorators: @IsString, @IsUUID, @Min, @Max matching spec constraints 7. Each DTO in its own dto/ file — output each file as a separate code block labeled with filename [PASTE YOUR OPENAPI YAML HERE]"

⚠️ Always Request YAML, Never JSON

OpenAPI specs can be written in both JSON and YAML, but YAML is dramatically better for AI generation. JSON requires exact quote + comma placement at every level of a deeply nested structure — one missing comma in a 500-line document breaks everything. YAML's whitespace-based nesting is more forgiving and produces far fewer generation errors. Always specify “Output as YAML” in your prompts.

⛔ Don't Generate Entire APIs in One Prompt

For APIs with 20+ endpoints, a single “generate the full spec” prompt will hit the model's output context limit and truncate mid-YAML — producing a broken document. Instead, generate in modules: first the components/schemas section only, then groups of related paths (“all /auth/* paths”, then “all /products/* paths”). Combine sections manually into the final spec file.

Frequently Asked Questions

Q: Should I maintain a swagger.yaml file or use code decorators?

A: For NestJS or Spring Boot with first-class decorator support, generating Swagger from code decorators is highly maintainable — the documentation stays colocated with the implementation and cannot drift out of sync. For lightweight Node.js/Go/Python services without decorator ecosystems, maintaining a separate swagger.yaml file checked into Git, updated via AI prompts, is often cleaner.

Q: Is AI-generated OpenAPI good enough for public developer APIs?

A: With careful prompting and post-generation review, yes. The critical checklist: (1) Validate 100% in editor.swagger.io, (2) Manually verify every example payload against your actual API behavior, (3) Check that all authentication requirements are accurately documented, (4) Confirm error schemas match your actual error response shapes.

Q: Can AI auto-update the spec when I change my code?

A: This is the cutting edge of developer tooling in 2026. GitHub Copilot Workspace and some enterprise AI dev tools offer schema drift detection. For now, a practical workflow is: whenever you add or modify an endpoint, paste just that controller function to the AI and ask it to update only the relevant path section of your YAML, then manually merge it.

Q: What is the difference between Swagger 2.0 and OpenAPI 3.0?

A: Swagger 2.0 uses "swagger: 2.0" at the top. OpenAPI 3.0 (the current IETF standard) uses "openapi: 3.0.x". Key 3.0 improvements: native JSON Schema support, oneOf/anyOf/allOf composition, multiple server definitions, and a cleaner components section. Always request "OpenAPI 3.0 format" in prompts — some models default to Swagger 2.0 from older training data.

NP

Naveen Teja Palle

Cloud & DevOps Engineer specializing in AWS infrastructure, React frontend architecture, and AI workflow automation. I build tools and write tutorials to help developers scale their technical workflows.