How to document APIs with OpenAPI

· Category: API & REST

Short answer

OpenAPI is a machine-readable specification format that describes REST APIs, enabling automated documentation, client generation, and validation.

Steps

  1. Define the API info section with title, version, and description.
  2. List servers and base URLs for different environments.
  3. Document each path with its supported methods, parameters, and responses.
  4. Define reusable components for schemas, parameters, and security schemes.
  5. Publish the spec alongside interactive documentation using tools like Swagger UI.

Tips

  • Generate specs from code annotations to keep documentation synchronized.
  • Use tags to organize endpoints by domain or resource.
  • Include example values for all request and response fields.
  • Validate the spec itself with linting tools to catch structural errors.

Common issues

  • Documentation diverging from implementation when maintained manually.
  • Incomplete error response documentation leaving clients unprepared.
  • Overly permissive schemas that fail to constrain valid inputs.
  • Version mismatches between the spec file and deployed API behavior.

Example

curl -X GET https://api.example.com/users   -H "Accept: application/json"   -H "Authorization: Bearer $TOKEN"

This curl command demonstrates a standard GET request with headers for content negotiation and bearer token authentication.

Additional context

Applying these principles consistently across projects leads to more maintainable systems, clearer team communication, and better outcomes for end users. Regular review and refinement of practices ensure continuous improvement.