Basic Structure
Swagger definitions can be written in JSON or YAML. In this guide, we only use YAML examples, but JSON works equally well. A sample Swagger specification written in YAML looks like:
Metadata
Every Swagger specification starts with the Swagger version, 2.0 being the latest version. A Swagger version defines the overall structure of an API specification – what you can document and how you document it.
Then, you need to specify the API info
– title
, description
(optional), version
(API version, not file revision or Swagger version).
version
can be a random string. You can use major.minor.patch (as in semantic versioning), or an arbitrary format like 1.0-beta or 2016.11.15. description
can be multiline and supports GitHub Flavored Markdown for rich text representation. info
also supports other fields for contact information, license and other details. Reference: Info Object.
Base URL
The base URL for all API calls is defined using schemes
, host
and basePath
:
All API paths are relative to the base URL. For example, /users actually means https://api.example.com/v1/users. More info: API Host and Base URL.
Consumes, Produces
The consumes
and produces
sections define the MIME types supported by the API. The root-level definition can be overridden in individual operations.
More info: MIME Types.
Paths
The paths
section defines individual endpoints (paths) in your API, and the HTTP methods (operations) supported by these endpoints. For example, GET /users can be described as:
More info: Paths and Operations.
Parameters
Operations can have parameters that can be passed via URL path (/users/{userId}
), query string (/users?role=admin
), headers (X-CustomHeader: Value
) and request body. You can define the parameter types, format, whether they are required or optional, and other details:
More info: Describing Parameters.
Responses
For each operation, you can define possible status codes, such as 200 OK or 404 Not Found, and schema
of the response body. Schemas can be defined inline or referenced from an external definition via $ref
. You can also provide example responses for different content types.
More info: Describing Responses.
Input and Output Models
The global definitions
section lets you define common data structures used in your API. They can be referenced via $ref
whenever a schema
is required – both for request body and response body. For example, this JSON object:
can be represented as:
and then referenced in the request body schema and response body schema as follows:
Authentication
The securityDefinitions
and security
keywords are used to describe the authentication methods used in your API.
Supported authentication methods are:
- Basic authentication
- API key (as a header or query parameter)
- OAuth 2 common flows (implicit, password, application and access code)
More info: Authentication.
Did not find what you were looking for? Ask the community
Found a mistake? Let us know