Guide to defining an API contract and generating automatic documentation with OpenAPI and Swagger
By Kevin Marcondes · Published on · Updated on · 8 min read
This guide shows, step by step, how to standardize endpoints, errors, and security and how to publish automatic API documentation using OpenAPI and Swagger. You’ll see OpenAPI 3.x structure, response models, versioning strategies, and how to expose living documentation with minimal manual work.
API contract: concept and practical benefits
An API contract is the specification that precisely describes how clients and servers interact. It details endpoints, payloads, errors, and security requirements. Having a contract reduces ambiguity and speeds up integration between teams and systems.
With a clear contract you avoid regressions when releasing new versions. You also gain a basis for automatic request and response validation. Tools can generate mocks, client SDKs, and server stubs from the contract, cutting rework.
Documentation stops being a static artifact. With OpenAPI it stays aligned with the code. Changes become reviewable pull requests, improving governance across your API ecosystem.
- Less rework between backend and consumers.
- Standardized error models and HTTP statuses.
- Automatic schema validation in CI/CD.
- Generation of clients/SDKs and mocks from the contract.
OpenAPI in brief: versions, structure, and best practices
OpenAPI 3.x is the most widely used standard to describe HTTP APIs. A typical specification contains metadata, servers, paths, operations, schemas, and reusable components. It can be written in YAML or JSON.
Organize the document using components for schemas, parameters, responses, and headers to avoid duplication. Keep realistic examples of request and response bodies—good examples are essential for living documentation.
Adopt consistent naming conventions. Use camelCase or snake_case consistently. Define date, number, and identifier formats. Document limits, pagination, and sorting for each resource.
- Use components/schemas for reusable models.
- Include examples and negative examples (errors).
- Centralize enumerations and standard messages.
- Use tags to group endpoints by domain.
Modeling REST endpoints: resources, verbs, and statuses
Think in terms of resources before endpoints. Reflect your domain’s entities and relationships. Use plural nouns and identify resources by IDs. Keep routes predictable and HTTP verbs consistent with the action.
Idempotency matters. GET, PUT, and DELETE should be idempotent. POST creates resources. PATCH applies partial changes. Define pagination and filters via query parameters. Document accepted limits and sorting.
If you’re evaluating alternative styles such as GraphQL, consult the GraphQL vs REST comparison to understand the impacts on contracts and integrations.
- GET /orders, POST /orders, GET /orders/{id}.
- Use 200/201 for success, 202 for asynchronous processing.
- Prefer 204 when there is no response body.
- Use 400 for validation errors, 401/403 for authentication and authorization.
- Return 429 when rate limiting applies.
Schemas, validations, and standardized errors
OpenAPI uses JSON Schema to describe data structures. Define types, formats, required fields, and limits. Use enums for controlled values. Clarify date, currency, and identifier fields with clear descriptions.
Standardize your error model. One approach is to follow the Problem Details (application/problem+json) pattern. Structure fields such as type, title, detail, code, traceId, and violations for validation errors.
Include error examples per scenario: validation, business rules, and downstream failures. Document specific codes for business rules. This helps front-ends and integrations handle failures consistently.
- Describe numeric ranges with minimum/maximum.
- Mark required fields with required.
- Use oneOf/anyOf for payload variations.
- Include pattern to validate custom formats.
Authentication, authorization, and versioning
Model securitySchemes in OpenAPI. Describe OAuth2, API Keys, or mTLS as applicable. Document scopes, authorization flows, and headers. Indicate which operations require authentication.
For deeper security policies, consult the guide on secure APIs with OAuth2 and rate limiting. Integrate requirements such as minimum scopes, per-client limits, and credential rotation best practices.
Plan versioning from the start. Define how versions will be represented, deprecation timelines, and compatibility rules. Document breaking changes and migration paths for consumers.
- Versioning strategies: URL (/v1), header (Accept-Version) or media type (application/vnd.suaapi+json;v=1).
- Standardize deprecation messages and sunset headers.
- Separate permissions by scopes and document them per operation.
Automatic documentation: Swagger UI and alternatives
With an OpenAPI file you can publish automatic documentation. Swagger UI renders endpoints, parameters, and examples and allows executing calls. Other tools produce quick, navigable UIs from the same contract.
Choose a tool based on hosting ease, theme support, search, multi-version support, and try-it-out capabilities. Below is an objective comparison to help you decide.
| Tool | Schema source | UI features | When to use |
|---|---|---|---|
| Swagger UI | OpenAPI 3.x | Try-it-out, simple theming, static hosting | Quick start, basic interactive docs |
| ReDoc | OpenAPI 3.x | Tree navigation, clean layout, search | Readable docs for large contracts |
| Stoplight Elements | OpenAPI 3.x | Try-it-out, rich navigation, theming | Portals with more advanced design |
| Redocly | OpenAPI 3.x | Full portal, multi-version, plugins | Governance and enterprise documentation |
| Postman Docs | OpenAPI 3.x/Collections | Executable examples, Postman environment | Teams already using Postman collections |
Integrating the contract into the flow: CI/CD, mocks, and tests
Adopt contract-first when possible. The contract guides implementation and eases alignment. With code-first, generate and validate OpenAPI in the pipeline. The essential point is to keep the contract as the source of truth and review it via pull requests.
Automate checks in CI/CD: OpenAPI linting, example validation, backward-compatibility checks, and artifact generation. Integrate with your pipelines and CI/CD practices such as CI/CD with GitHub Actions.
Include contract tests and mocks for consumers. Simulate responses according to the OpenAPI file. During code reviews, evaluate security and error handling. When necessary, run a code audit focused on critical endpoints.
- OpenAPI linting (naming, schemas, and examples).
- Request/response validation in integration tests.
- Compatibility testing to detect breaking changes.
- Automatic SDK generation per language.
- Publish documentation on each PR and environment.
Initial steps and governance checklist
Start small but complete. Choose a domain, map resources and versions, write contracts with examples, publish the documentation, and integrate validations into CI. With feedback, evolve standards and compile an internal style guide.
Formalize governance: peer reviews, naming conventions, an API catalog, deprecation cycles, and a compatibility policy. The goal is predictability for consumers and safety for the team.
- Define the API’s business objectives.
- Map resources, relationships, and limits.
- Choose pagination and sorting styles.
- Write the OpenAPI using reusable components.
- Model authentication and scopes per operation.
- Standardize errors and business codes.
- Publish automatic documentation.
- Automate linting, validation, and compatibility checks.
Frequently asked questions
Contract-first or code-first: which should I choose?
Contract-first means writing the API specification before implementing endpoints; it improves alignment between teams, enables mock servers, SDK and client generation, and guides implementation from the start. Code-first generates a contract from existing code and is useful when endpoints already exist. In either approach, treat the OpenAPI file as the source of truth and enforce changes via pull request reviews and CI validations.
How do I keep OpenAPI synchronized with the code?
Keep the OpenAPI file in the same repository as the implementation and publish documentation on every commit or PR. Automate CI checks such as linting, example validation, and backward-compatibility testing to detect mismatches early. Make the contract an artifact reviewed in pull requests and block deployments that would break compatibility unless a new version or documented migration is provided.
Does OpenAPI work with GraphQL or gRPC?
OpenAPI is designed to describe HTTP-style REST APIs. GraphQL and gRPC use different primary contract formats (SDL/introspection for GraphQL and Protobuf/.proto for gRPC). You can document HTTP gateways that expose GraphQL or translate gRPC to HTTP, but each technology’s native contract format remains the authoritative specification for that service.
How should I handle breaking changes in the API?
When you must introduce incompatible changes, create a new API version and document the breaking changes clearly. Publish deprecation timelines, provide migration guidance, and keep previous versions available for a practical period. Prefer avoiding removals or semantic changes without versioning; notify consumers in advance and record changes in the API catalog and documentation to aid migration and governance.
Do I need Swagger to use OpenAPI?
No — Swagger UI is a popular renderer and try‑it‑out tool for OpenAPI, but alternatives such as ReDoc or dedicated portals also render the same contract. The critical practice is to keep the OpenAPI file updated, include realistic examples and error scenarios, publish accessible documentation per release or PR, and align documentation versions with your release cycle.
Want to standardize contracts and publish living documentation?
If you need to move from improvisation to a repeatable OpenAPI process with automated documentation, we can discuss your scenario and outline a practical implementation plan.
Talk about your API contractSee also
- Pre-deploy checklist and quick rollback plan for PHP applications in production
- Security checklist for CI/CD pipelines with self‑hosted runners and secrets management
- Guide: Centralize logs with Fluentd and Elasticsearch for PHP apps on a VPS
- Guide: Organizing PostgreSQL Migrations and Rollbacks for Small Teams