Документация API: OpenAPI и Swagger на практике
авг, 17 2026
Представьте ситуацию: вы передали фронтендеру список эндпоинтов в Excel. Через неделю он пишет вам с вопросом, какой тип данных приходит в поле status. А через две недели QA находит баг, потому что никто не обновил описание после изменения контракта. Знакомо? Если да, то вам точно нужен OpenAPI.
OpenAPI Specification (OAS) is a standard format for describing RESTful APIs that allows tools to generate documentation, clients, and servers automatically. This specification was originally created by SmartBear in 2010 as Swagger Specification, but in 2015 it was transferred to the OpenAPI Initiative under the Linux Foundation. Today, it is the de facto standard for API documentation in the industry.
Почему Swagger больше не просто утилита
Многие до сих пор путают понятия. Давайте разберемся. Swagger is a set of tools and libraries used to build, document, test, and consume OpenAPI-compliant APIs. Originally, Swagger was a specific tool for generating interactive docs. Now, "Swagger" often refers to the ecosystem: Swagger Editor, Swagger UI, Swagger Codegen. Meanwhile, OpenAPI is the pure text format (YAML or JSON) that describes your API.
The key difference is simple: OpenAPI is the file (the contract), Swagger is the engine that reads this file and shows you a beautiful interface. You can use other tools instead of Swagger (like Redoc or Stoplight), but they all read the same OpenAPI file.
Структура файла openapi.yaml
Let's look at what a minimal valid OpenAPI file looks like. It consists of several main sections:
- openapi: The version of the specification (currently 3.x).
- info: Metadata about the API (title, version, description).
- servers: List of server URLs where the API is hosted.
- paths: The heart of the document. Describes each endpoint (URL + HTTP method).
- components: Reusable objects (schemas, parameters, responses).
Here is a simplified example of a path definition:
/users/{id}:
get:
summary: Get user by ID
operationId: getUserById
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: User not found
Инструменты для работы с OpenAPI
You don't have to write YAML by hand forever. There are several approaches:
- Code-first: You write code (in Java, Python, Go, etc.) with annotations, and a generator creates the spec. Tools: SpringDoc, Flask-Swagger, Swaggo.
- Design-first: You design the API in a visual editor first, then generate stubs or clients. Tools: Swagger Editor, Stoplight Studio, Postman.
For most backend teams, Code-first is more convenient because it keeps documentation synchronized with the actual implementation. If you change a field in the model, the annotation updates, and the spec regenerates automatically.
Практические советы по написанию качественной документации
Having a file is not enough. The documentation must be useful. Here are some rules we follow in our projects:
- Use examples. For every request and response, provide a real example of the payload. Developers love copying-pasting working JSON.
- Describe error codes clearly. Don't just say "400 Bad Request". Explain *why* it might happen (e.g., "Email already registered").
- Version your API. Use the
versionfield ininfocarefully. Better to use URL paths (/v1/users) than breaking changes in the same endpoint. - Keep descriptions human-readable. Write as if explaining to a colleague who just joined the team.
Сравнение популярных инструментов
| Tool | Type | Main Feature | Best For |
|---|---|---|---|
| Swagger UI | Viewer | Interactive testing in browser | Quick manual testing |
| Redoc | Viewer | Clean, static documentation layout | Public-facing API docs |
| Stoplight | Editor + Viewer | Visual design-first editing | Teams designing API before coding |
| Postman | Client + Generator | Import/Export OpenAPI, collaboration | QA and frontend teams |
Частые ошибки при использовании OpenAPI
Even experienced developers make mistakes. Watch out for these:
- Duplicate schemas. If you define the same object twice, you'll end up maintaining two copies. Use
$refincomponents.schemasinstead. - Missing validation constraints. If a string has a max length, specify
maxLength. This helps generate better client-side validation. - Ignoring async operations. If an endpoint returns 202 Accepted, document how to check the status later (polling or webhook).
Как интегрировать документацию в CI/CD
Documentation shouldn't be a separate task. Integrate it into your pipeline:
- Generate the
openapi.yamlduring the build process. - Validate the file using
swagger-cli validateor similar linters. - Deploy the generated HTML (via Swagger UI or Redoc) to your internal wiki or public domain.
This ensures that if someone breaks the API contract, the build fails immediately, preventing bad releases.
Что лучше: Swagger или Redoc?
Это зависит от цели. Swagger UI позволяет тестировать запросы прямо в браузере, что удобно для разработчиков и QA. Redoc создает более красивую и читаемую статическую страницу, которая лучше подходит для публичной документации. Многие команды используют оба: Swagger UI для внутренней разработки, Redoc для внешнего сайта.
Нужна ли мне отдельная версия спецификации для каждого микросервиса?
Да, обычно каждый микросервис имеет свой файл OpenAPI. Однако можно использовать инструменты агрегации (например, Aggregator или Portal), чтобы объединить все файлы в один общий каталог API для удобства потребителей.
Какая версия OpenAPI актуальна в 2026 году?
Актуальной является версия 3.x (конкретно 3.0.x и 3.1.x). Версия 3.1 добавила поддержку JSON Schema Draft 2020-12, что дает больше возможностей для валидации. Старая версия 2.0 (Swagger 2.0) считается устаревшей, но все еще поддерживается многими инструментами.
Можно ли генерировать клиентский код из OpenAPI?
Да, это одна из главных функций экосистемы. Инструменты вроде OpenAPI Generator, Swagger Codegen или NSwag могут создавать готовые клиенты на JavaScript, TypeScript, Python, Java, C# и других языках. Это экономит часы ручной работы.
Где хранить файл openapi.yaml в репозитории?
Обычно его хранят в корне проекта или в папке docs/api. Если генерация происходит автоматически из кода, файл может быть в .gitignore, но многие команды предпочитают коммитить его, чтобы видеть историю изменений контракта в git blame.