HOW-TO · DEV
How to write YAML or OpenAPI spec documentation for your REST API using an AI assistant
Target environment
Ubuntu 24.04 · Ollama 0.4.x
PREREQUISITES
API endpoints defined, AI assistant, basic understanding of REST conventions and YAML syntax
What this does
This guide describes how to produce an OpenAPI 3.x specification in YAML format for a REST API using an AI assistant. The spec documents endpoints, HTTP methods, request and response schemas, authentication mechanisms, and error codes. A well-formed OpenAPI spec enables auto-generated client SDKs, interactive API documentation via Swagger UI, and contract testing.
Steps
- Gather the API metadata: name, version, base URL, and authentication scheme (Bearer token, API key, OAuth2).
- List all endpoints with their HTTP methods, URL paths, path parameters, query parameters, and request body schemas.
- Provide the AI with the OpenAPI version target (e.g., 3.0.3) and the collected metadata.
- Issue the generation instruction: "Generate an OpenAPI 3.0 spec in YAML for the following API endpoints. Include request/response schemas, parameter descriptions, and authentication requirements."
- Review the generated YAML structure. Verify all paths are under the
pathskey and each operation hassummary,parameters,requestBody, andresponsesfields. - Check that schema references are consistent: if a request body uses
application/json, the content block must define aschemaunder that media type. - Validate the YAML file using a linter or OpenAPI validator:
npx @redocly/cli lint openapi.yaml. - Render the spec in Swagger Editor or via Redoc to verify the documentation displays correctly.
Verification
npx @redocly/cli lint openapi.yaml 2>&1 | grep -E "(Error|Warning|No issues)" | head -3
# Expected output: No issues found (or linting passed with no errors)
Common failures
- Invalid YAML syntax: Common issues include incorrect indentation, missing colons after keys, or duplicate top-level keys. Solution: run the YAML through a validator (Yamllint or the OpenAPI linter above) before sharing with the AI for correction.
- Missing server URL format: The spec omits or misformats the
serversblock, causing Swagger UI to show a blank base URL. Solution: explicitly includeservers: [{url: "https://api.example.com/v1"}]in the spec. - Schema type mismatches: The AI defines a field as
stringwhen the actual API returns a number or boolean. Solution: provide sample JSON response payloads from the API as reference material for the AI. - Incorrect HTTP status codes: AI assigns wrong codes (e.g., 200 for a failed operation) or omits common error codes like 400, 401, 404. Solution: explicitly list the expected status codes per endpoint in the prompt.