Swagger OPEN API SPECIFICATION
Swagger UI Express
Statements | Branches | Functions | Lines |
---|---|---|---|
This module allows you to serve auto-generated swagger-ui generated API docs from express, based on a swagger.json
file. The result is living documentation for your API hosted from your API server via a route.
Swagger version is pulled from npm module swagger-ui-dist. Please use a lock file or specify the version of swagger-ui-dist you want to ensure it is consistent across environments.
You may be also interested in:
swagger-jsdoc: Allows you to markup routes with jsdoc comments. It then produces a full swagger yml config dynamically, which you can pass to this module to produce documentation. See below under the usage section for more info.
swagger tools: Various tools, including swagger editor, swagger code gen etc.
Usage
Install using npm:
Express setup app.js
or if you are using Express router
Open http://<app_host>
:<app_port>
/api-docs in your browser to view the documentation.
If you want to set up routing based on the swagger document checkout swagger-express-router
If you are using swagger-jsdoc simply pass the swaggerSpec into the setup function:
Swagger Explorer
By default the Swagger Explorer bar is hidden, to display it pass true as the 'explorer' property of the options to the setup function:
Custom swagger options
To pass custom options e.g. validatorUrl, to the SwaggerUi client pass an object as the 'swaggerOptions' property of the options to the setup function:
For all the available options, refer to Swagger UI Configuration
Custom CSS styles
To customize the style of the swagger page, you can pass custom CSS as the 'customCss' property of the options to the setup function.
E.g. to hide the swagger header:
Custom CSS styles from Url
You can also pass the url to a custom css file, the value must be the public url of the file and can be relative or absolute to the swagger path.
Custom JS
If you would like to have full control over your HTML you can provide your own javascript file, value accepts absolute or relative path. Value must be the public url of the js file.
Load swagger from url
To load your swagger from a url instead of injecting the document, pass null
as the first parameter, and pass the relative or absolute URL as the 'url' property to 'swaggerOptions' in the setup function.
To load multiple swagger documents from urls as a dropdown in the explorer bar, pass an array of object with name
and url
to 'urls' property to 'swaggerOptions' in the setup function.
Make sure 'explorer' option is set to 'true' in your setup options for the dropdown to be visible.
Load swagger from yaml file
To load your swagger specification yaml file you need to use a module able to convert yaml to json; for instance yamljs
.
Modify swagger file on the fly before load
To dynamically set the host, or any other content, in the swagger file based on the incoming request object you may pass the json via the req object; to achieve this just do not pass the the swagger json to the setup function and it will look for swaggerDoc
in the req
object.
Two swagger documents
To run 2 swagger ui instances with different swagger documents, use the serveFiles function instead of the serve function. The serveFiles function has the same signature as the setup function.
Requirements
Node v0.10.32 or above
Express 4 or above
Testing
Install phantom
npm install
npm test
OpenAPI Specification
Version 3.0.3
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 RFC2119 RFC8174 when, and only when, they appear in all capitals, as shown here.
This document is licensed under The Apache License, Version 2.0.
Introduction
The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.
An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases.
Definitions
OpenAPI Document
A document (or set of documents) that defines or describes an API. An OpenAPI definition uses and conforms to the OpenAPI Specification.
Path Templating
Path templating refers to the usage of template expressions, delimited by curly braces ({}), to mark a section of a URL path as replaceable using path parameters.
Each template expression in the path MUST correspond to a path parameter that is included in the Path Item itself and/or in each of the Path Item's Operations.
Media Types
Media type definitions are spread across several resources. The media type definitions SHOULD be in compliance with RFC6838.
Some examples of possible media type definitions:
HTTP Status Codes
The HTTP Status Codes are used to indicate the status of the executed operation. The available status codes are defined by RFC7231 and registered status codes are listed in the IANA Status Code Registry.
Specification
Versions
The OpenAPI Specification is versioned using Semantic Versioning 2.0.0 (semver) and follows the semver specification.
The major
.minor
portion of the semver (for example 3.0
) SHALL designate the OAS feature set. Typically, .patch
versions address errors in this document, not the feature set. Tooling which supports OAS 3.0 SHOULD be compatible with all OAS 3.0.* versions. The patch version SHOULD NOT be considered by tooling, making no distinction between 3.0.0
and 3.0.1
for example.
Each new minor version of the OpenAPI Specification SHALL allow any OpenAPI document that is valid against any previous minor version of the Specification, within the same major version, to be updated to the new Specification version with equivalent semantics. Such an update MUST only require changing the openapi
property to the new minor version.
For example, a valid OpenAPI 3.0.2 document, upon changing its openapi
property to 3.1.0
, SHALL be a valid OpenAPI 3.1.0 document, semantically equivalent to the original OpenAPI 3.0.2 document. New minor versions of the OpenAPI Specification MUST be written to ensure this form of backward compatibility.
An OpenAPI document compatible with OAS 3.*.* contains a required openapi
field which designates the semantic version of the OAS that it uses. (OAS 2.0 documents contain a top-level version field named swagger
and value "2.0"
.)
Format
An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format.
For example, if a field has an array value, the JSON array representation will be used:
All field names in the specification are case sensitive. This includes all fields that are used as keys in a map, except where explicitly noted that keys are case insensitive.
The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name.
Patterned fields MUST have unique names within the containing object.
In order to preserve the ability to round-trip between YAML and JSON formats, YAML version 1.2 is RECOMMENDED along with some additional constraints:
Tags MUST be limited to those allowed by the JSON Schema ruleset.
Keys used in YAML maps MUST be limited to a scalar string, as defined by the YAML Failsafe schema ruleset.
Note: While APIs may be defined by OpenAPI documents in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML.
Document Structure
An OpenAPI document MAY be made up of a single document or be divided into multiple, connected parts at the discretion of the user. In the latter case, $ref
fields MUST be used in the specification to reference those parts as follows from the JSON Schema definitions.
It is RECOMMENDED that the root OpenAPI document be named: openapi.json
or openapi.yaml
.
Data Types
Primitive data types in the OAS are based on the types supported by the JSON Schema Specification Wright Draft 00. Note that integer
as a type is also supported and is defined as a JSON number without a fraction or exponent part. null
is not supported as a type (see nullable
for an alternative solution). Models are defined using the Schema Object, which is an extended subset of JSON Schema Specification Wright Draft 00.
Primitives have an optional modifier property: format
. OAS uses several known formats to define in fine detail the data type being used. However, to support documentation needs, the format
property is an open string
-valued property, and can have any value. Formats such as "email"
, "uuid"
, and so on, MAY be used even though undefined by this specification. Types that are not accompanied by a format
property follow the type definition in the JSON Schema. Tools that do not recognize a specific format
MAY default back to the type
alone, as if the format
is not specified.
The formats defined by the OAS are:
Comments | ||
|
| signed 32 bits |
|
| signed 64 bits (a.k.a long) |
|
| |
|
| |
| ||
|
| base64 encoded characters |
|
| any sequence of octets |
| ||
|
| As defined by |
|
| As defined by |
|
| A hint to UIs to obscure input. |
Rich Text Formatting
Throughout the specification description
fields are noted as supporting CommonMark markdown formatting. Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by CommonMark 0.27. Tooling MAY choose to ignore some CommonMark features to address security concerns.
Relative References in URLs
Unless specified otherwise, all properties that are URLs MAY be relative references as defined by RFC3986. Relative references are resolved using the URLs defined in the Server Object
as a Base URI.
Relative references used in $ref
are processed as per JSON Reference, using the URL of the current document as the base URI. See also the Reference Object.
Schema
In the following description, if a field is not explicitly REQUIRED or described with a MUST or SHALL, it can be considered OPTIONAL.
OpenAPI Object
This is the root document object of the OpenAPI document.
Fixed Fields
Field Name | Type | Description |
---|---|---|
openapi |
| REQUIRED. This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses. The |
info | REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required. | |
servers | An array of Server Objects, which provide connectivity information to a target server. If the | |
paths | REQUIRED. The available paths and operations for the API. | |
components | An element to hold various schemas for the specification. | |
security | A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement ( | |
tags | A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. | |
externalDocs | Additional external documentation. |
This object MAY be extended with Specification Extensions.
Info Object
The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.
Fixed Fields
Field Name | Type | Description |
---|---|---|
title |
| REQUIRED. The title of the API. |
description |
| A short description of the API. CommonMark syntax MAY be used for rich text representation. |
termsOfService |
| A URL to the Terms of Service for the API. MUST be in the format of a URL. |
contact | The contact information for the exposed API. | |
license | The license information for the exposed API. | |
version |
| REQUIRED. The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version). |
This object MAY be extended with Specification Extensions.
Info Object Example
Contact Object
Contact information for the exposed API.
Fixed Fields
Field Name | Type | Description |
---|---|---|
name |
| The identifying name of the contact person/organization. |
url |
| The URL pointing to the contact information. MUST be in the format of a URL. |
| The email address of the contact person/organization. MUST be in the format of an email address. |
This object MAY be extended with Specification Extensions.
Contact Object Example
License Object
License information for the exposed API.
Fixed Fields
Field Name | Type | Description |
---|---|---|
name |
| REQUIRED. The license name used for the API. |
url |
| A URL to the license used for the API. MUST be in the format of a URL. |
This object MAY be extended with Specification Extensions.
License Object Example
Server Object
An object representing a Server.
Fixed Fields
Field Name | Type | Description |
---|---|---|
url |
| REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in |
description |
| An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation. |
variables | Map[ | A map between a variable name and its value. The value is used for substitution in the server's URL template. |
This object MAY be extended with Specification Extensions.
Server Object Example
A single server would be described as:
The following shows how multiple servers can be described, for example, at the OpenAPI Object's servers
:
The following shows how variables can be used for a server configuration:
Server Variable Object
An object representing a Server Variable for server URL template substitution.
Fixed Fields
Field Name | Type | Description |
---|---|---|
enum | [ | An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty. |
default |
| REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is not supplied. Note this behavior is different than the Schema Object's treatment of default values, because in those cases parameter values are optional. If the |
description |
| An optional description for the server variable. CommonMark syntax MAY be used for rich text representation. |
This object MAY be extended with Specification Extensions.
Components Object
Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.
Fixed Fields
Field Name | Type | Description |
---|---|---|
schemas | Map[ | An object to hold reusable Schema Objects. |
responses | Map[ | An object to hold reusable Response Objects. |
parameters | Map[ | An object to hold reusable Parameter Objects. |
examples | Map[ | An object to hold reusable Example Objects. |
requestBodies | Map[ | An object to hold reusable Request Body Objects. |
headers | Map[ | An object to hold reusable Header Objects. |
securitySchemes | Map[ | An object to hold reusable Security Scheme Objects. |
links | Map[ | An object to hold reusable Link Objects. |
callbacks | Map[ | An object to hold reusable Callback Objects. |
This object MAY be extended with Specification Extensions.
All the fixed fields declared above are objects that MUST use keys that match the regular expression: ^[a-zA-Z0-9\.\-_]+$
.
Field Name Examples:
Components Object Example
Paths Object
Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the Server Object
in order to construct the full URL. The Paths MAY be empty, due to ACL constraints.
Patterned Fields
Field Pattern | Type | Description |
---|---|---|
/{path} | A relative path to an individual endpoint. The field name MUST begin with a forward slash ( |
This object MAY be extended with Specification Extensions.
Path Templating Matching
Assuming the following paths, the concrete definition, /pets/mine
, will be matched first if used:
The following paths are considered identical and invalid:
The following may lead to ambiguous resolution:
Paths Object Example
Path Item Object
Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.
Fixed Fields
Field Name | Type | Description |
---|---|---|
$ref |
| Allows for an external definition of this path item. The referenced structure MUST be in the format of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. |
summary |
| An optional, string summary, intended to apply to all operations in this path. |
description |
| An optional, string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation. |
get | A definition of a GET operation on this path. | |
put | A definition of a PUT operation on this path. | |
post | A definition of a POST operation on this path. | |
delete | A definition of a DELETE operation on this path. | |
options | A definition of a OPTIONS operation on this path. | |
head | A definition of a HEAD operation on this path. | |
patch | A definition of a PATCH operation on this path. | |
trace | A definition of a TRACE operation on this path. | |
servers | An alternative | |
parameters | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters. |
This object MAY be extended with Specification Extensions.
Path Item Object Example
Operation Object
Describes a single API operation on a path.
Fixed Fields
Field Name | Type | Description |
---|---|---|
tags | [ | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. |
summary |
| A short summary of what the operation does. |
description |
| A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation. |
externalDocs | Additional external documentation for this operation. | |
operationId |
| Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. |
parameters | A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters. | |
requestBody | The request body applicable for this operation. The | |
responses | REQUIRED. The list of possible responses as they are returned from executing this operation. | |
callbacks | Map[ | A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses. |
deprecated |
| Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is |
security | A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement ( | |
servers | An alternative |
This object MAY be extended with Specification Extensions.
Operation Object Example
External Documentation Object
Allows referencing an external resource for extended documentation.
Fixed Fields
Field Name | Type | Description |
---|---|---|
description |
| A short description of the target documentation. CommonMark syntax MAY be used for rich text representation. |
url |
| REQUIRED. The URL for the target documentation. Value MUST be in the format of a URL. |
This object MAY be extended with Specification Extensions.
External Documentation Object Example
Parameter Object
Describes a single operation parameter.
A unique parameter is defined by a combination of a name and location.
Parameter Locations
There are four possible parameter locations specified by the in
field:
path - Used together with Path Templating, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in
/items/{itemId}
, the path parameter isitemId
.query - Parameters that are appended to the URL. For example, in
/items?id=###
, the query parameter isid
.header - Custom headers that are expected as part of the request. Note that RFC7230 states header names are case insensitive.
cookie - Used to pass a specific cookie value to the API.
Fixed Fields
Field Name | Type | Description |
---|---|---|
name |
| REQUIRED. The name of the parameter. Parameter names are case sensitive.
|
in |
| REQUIRED. The location of the parameter. Possible values are |
description |
| A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation. |
required |
| Determines whether this parameter is mandatory. If the parameter location is |
deprecated |
| Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is |
allowEmptyValue |
| Sets the ability to pass empty-valued parameters. This is valid only for |
The rules for serialization of the parameter are specified in one of two ways. For simpler scenarios, a schema
and style
can describe the structure and syntax of the parameter.
Field Name | Type | Description |
---|---|---|
style |
| Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of |
explode |
| When this is true, parameter values of type |
allowReserved |
| Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 |
schema | The schema defining the type used for the parameter. | |
example | Any | Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The |
examples | Map[ | Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The |
For more complex scenarios, the content
property can define the media type and schema of the parameter. A parameter MUST contain either a schema
property, or a content
property, but not both. When example
or examples
are provided in conjunction with the schema
object, the example MUST follow the prescribed serialization strategy for the parameter.
Field Name | Type | Description |
---|---|---|
content | Map[ | A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. |
Style Values
In order to support common ways of serializing simple parameters, a set of style
values are defined.
|
| Comments | |
matrix |
|
| Path-style parameters defined by RFC6570 |
label |
|
| Label style parameters defined by RFC6570 |
form |
|
| Form style parameters defined by RFC6570. This option replaces |
simple |
|
| Simple style parameters defined by RFC6570. This option replaces |
spaceDelimited |
|
| Space separated array values. This option replaces |
pipeDelimited |
|
| Pipe separated array values. This option replaces |
deepObject |
|
| Provides a simple way of rendering nested objects using form parameters. |
Style Examples
Assume a parameter named color
has one of the following values:
The following table shows examples of rendering differences for each value.
|
|
|
|
| |
matrix | false | ;color | ;color=blue | ;color=blue,black,brown | ;color=R,100,G,200,B,150 |
matrix | true | ;color | ;color=blue | ;color=blue;color=black;color=brown | ;R=100;G=200;B=150 |
label | false | . | .blue | .blue.black.brown | .R.100.G.200.B.150 |
label | true | . | .blue | .blue.black.brown | .R=100.G=200.B=150 |
form | false | color= | color=blue | color=blue,black,brown | color=R,100,G,200,B,150 |
form | true | color= | color=blue | color=blue&color=black&color=brown | R=100&G=200&B=150 |
simple | false | n/a | blue | blue,black,brown | R,100,G,200,B,150 |
simple | true | n/a | blue | blue,black,brown | R=100,G=200,B=150 |
spaceDelimited | false | n/a | n/a | blue%20black%20brown | R%20100%20G%20200%20B%20150 |
pipeDelimited | false | n/a | n/a | blue|black|brown | R|100|G|200|B|150 |
deepObject | true | n/a | n/a | n/a | color[R]=100&color[G]=200&color[B]=150 |
This object MAY be extended with Specification Extensions.
Parameter Object Examples
A header parameter with an array of 64 bit integer numbers:
A path parameter of a string value:
An optional query parameter of a string value, allowing multiple values by repeating the query parameter:
A free-form query parameter, allowing undefined parameters of a specific type:
A complex parameter using content
to define serialization:
Request Body Object
Describes a single request body.
Fixed Fields
Field Name | Type | Description |
---|---|---|
description |
| A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation. |
content | Map[ | REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* |
required |
| Determines if the request body is required in the request. Defaults to |
This object MAY be extended with Specification Extensions.
Request Body Examples
A request body with a referenced model definition.
A body parameter that is an array of string values:
Media Type Object
Each Media Type Object provides schema and examples for the media type identified by its key.
Fixed Fields
Field Name | Type | Description |
---|---|---|
schema | The schema defining the content of the request, response, or parameter. | |
example | Any | Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The |
examples | Map[ | Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The |
encoding | Map[ | A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to |
This object MAY be extended with Specification Extensions.
Media Type Examples
Considerations for File Uploads
In contrast with the 2.0 specification, file
input/output content in OpenAPI is described with the same semantics as any other schema type. Specifically:
These examples apply to either input payloads of file uploads or response payloads.
A requestBody
for submitting a file in a POST
operation may look like the following example:
In addition, specific media types MAY be specified:
To upload multiple files, a multipart
media type MUST be used:
Support for x-www-form-urlencoded Request Bodies
To submit content using form url encoding via RFC1866, the following definition may be used:
In this example, the contents in the requestBody
MUST be stringified per RFC1866 when passed to the server. In addition, the address
field complex object will be stringified.
When passing complex objects in the application/x-www-form-urlencoded
content type, the default serialization strategy of such properties is described in the Encoding Object
's style
property as form
.
Special Considerations for multipart Content
It is common to use multipart/form-data
as a Content-Type
when transferring request bodies to operations. In contrast to 2.0, a schema
is REQUIRED to define the input parameters to the operation when using multipart
content. This supports complex structures as well as supporting mechanisms for multiple file uploads.
When passing in multipart
types, boundaries MAY be used to separate sections of the content being transferred — thus, the following default Content-Type
s are defined for multipart
:
If the property is a primitive, or an array of primitive values, the default Content-Type is
text/plain
If the property is complex, or an array of complex values, the default Content-Type is
application/json
If the property is a
type: string
withformat: binary
orformat: base64
(aka a file object), the default Content-Type isapplication/octet-stream
Examples:
An encoding
attribute is introduced to give you control over the serialization of parts of multipart
request bodies. This attribute is only applicable to multipart
and application/x-www-form-urlencoded
request bodies.
Encoding Object
A single encoding definition applied to a single schema property.
Fixed Fields
Field Name | Type | Description |
---|---|---|
contentType |
| The Content-Type for encoding a specific property. Default value depends on the property type: for |
headers | Map[ | A map allowing additional information to be provided as headers, for example |
style |
| Describes how a specific property value will be serialized depending on its type. See Parameter Object for details on the |
explode |
| When this is true, property values of type |
allowReserved |
| Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 |
This object MAY be extended with Specification Extensions.
Encoding Object Example
Responses Object
A container for the expected responses of an operation. The container maps a HTTP response code to the expected response.
The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. However, documentation is expected to cover a successful operation response and any known errors.
The default
MAY be used as a default response object for all HTTP codes that are not covered individually by the specification.
The Responses Object
MUST contain at least one response code, and it SHOULD be the response for a successful operation call.
Fixed Fields
Field Name | Type | Description |
---|---|---|
default | The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. A Reference Object can link to a response that the OpenAPI Object's components/responses section defines. |
Patterned Fields
Field Pattern | Type | Description |
---|---|---|
Any HTTP status code can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. A Reference Object can link to a response that is defined in the OpenAPI Object's components/responses section. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character |
This object MAY be extended with Specification Extensions.
Responses Object Example
A 200 response for a successful operation and a default response for others (implying an error):
Response Object
Describes a single response from an API Operation, including design-time, static links
to operations based on the response.
Fixed Fields
Field Name | Type | Description |
---|---|---|
description |
| REQUIRED. A short description of the response. CommonMark syntax MAY be used for rich text representation. |
headers | Map[ | Maps a header name to its definition. RFC7230 states header names are case insensitive. If a response header is defined with the name |
content | Map[ | A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* |
links | Map[ | A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects. |
This object MAY be extended with Specification Extensions.
Response Object Examples
Response of an array of a complex type:
Response with a string type:
Plain text response with headers:
Response with no return value:
Callback Object
A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
Patterned Fields
Field Pattern | Type | Description |
---|---|---|
{expression} | A Path Item Object used to define a callback request and expected responses. A complete example is available. |
This object MAY be extended with Specification Extensions.
Key Expression
The key that identifies the Path Item Object is a runtime expression that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. A simple example might be $request.body#/url
. However, using a runtime expression the complete HTTP message can be accessed. This includes accessing any part of a body that a JSON Pointer RFC6901 can reference.
For example, given the following HTTP request:
The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named eventType
and a query parameter named queryUrl
.
Expression | Value |
---|---|
$url | |
$method | POST |
$request.path.eventType | myevent |
$request.query.queryUrl | |
$request.header.content-Type | application/json |
$request.body#/failedUrl | |
$request.body#/successUrls/2 | |
$response.header.Location |
Callback Object Examples
The following example uses the user provided queryUrl
query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook.
The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the id
and email
property in the request body.
Example Object
Fixed Fields
Field Name | Type | Description |
---|---|---|
summary |
| Short description for the example. |
description |
| Long description for the example. CommonMark syntax MAY be used for rich text representation. |
value | Any | Embedded literal example. The |
externalValue |
| A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The |
This object MAY be extended with Specification Extensions.
In all cases, the example value is expected to be compatible with the type schema of its associated value. Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible.
Example Object Examples
In a request body:
In a parameter:
In a response:
Link Object
The Link object
represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations.
Unlike dynamic links (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response.
For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.
Fixed Fields
Field Name | Type | Description |
---|---|---|
operationRef |
| A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the |
operationId |
| The name of an existing, resolvable OAS operation, as defined with a unique |
parameters | Map[ | A map representing parameters to pass to an operation as specified with |
requestBody | Any | {expression} | A literal value or {expression} to use as a request body when calling the target operation. |
description |
| A description of the link. CommonMark syntax MAY be used for rich text representation. |
server | A server object to be used by the target operation. |
This object MAY be extended with Specification Extensions.
A linked operation MUST be identified using either an operationRef
or operationId
. In the case of an operationId
, it MUST be unique and resolved in the scope of the OAS document. Because of the potential for name clashes, the operationRef
syntax is preferred for specifications with external references.
Examples
Computing a link from a request operation where the $request.path.id
is used to pass a request parameter to the linked operation.
When a runtime expression fails to evaluate, no parameter value is passed to the target operation.
Values from the response body can be used to drive a linked operation.
Clients follow all links at their discretion. Neither permissions, nor the capability to make a successful call to that link, is guaranteed solely by the existence of a relationship.
OperationRef Examples
As references to operationId
MAY NOT be possible (the operationId
is an optional field in an Operation Object), references MAY also be made through a relative operationRef
:
or an absolute operationRef
:
Note that in the use of operationRef
, the escaped forward-slash is necessary when using JSON references.
Runtime Expressions
Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. This mechanism is used by Link Objects and Callback Objects.
The runtime expression is defined by the following ABNF syntax
Here, json-pointer
is taken from RFC 6901, char
from RFC 7159 and token
from RFC 7230.
The name
identifier is case-sensitive, whereas token
is not.
The table below provides examples of runtime expressions and examples of their use in a value:
Examples
Source Location | example expression | notes |
---|---|---|
HTTP Method |
| The allowable values for the |
Requested media type |
| |
Request parameter |
| Request parameters MUST be declared in the |
Request body property |
| In operations which accept payloads, references may be made to portions of the |
Request URL |
| |
Response value |
| In operations which return payloads, references may be made to portions of the response body or the entire body. |
Response header |
| Single header values only are available |
Runtime expressions preserve the type of the referenced value. Expressions can be embedded into string values by surrounding the expression with {}
curly braces.
Header Object
The Header Object follows the structure of the Parameter Object with the following changes:
name
MUST NOT be specified, it is given in the correspondingheaders
map.in
MUST NOT be specified, it is implicitly inheader
.All traits that are affected by the location MUST be applicable to a location of
header
(for example,style
).
Header Object Example
A simple header of type integer
:
Tag Object
Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.
Fixed Fields
Field Name | Type | Description |
---|---|---|
name |
| REQUIRED. The name of the tag. |
description |
| A short description for the tag. CommonMark syntax MAY be used for rich text representation. |
externalDocs | Additional external documentation for this tag. |
This object MAY be extended with Specification Extensions.
Tag Object Example
Reference Object
A simple object to allow referencing other components in the specification, internally and externally.
The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules.
For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification.
Fixed Fields
Field Name | Type | Description |
---|---|---|
$ref |
| REQUIRED. The reference string. |
This object cannot be extended with additional properties and any properties added SHALL be ignored.
Reference Object Example
Relative Schema Document Example
Relative Documents With Embedded Schema Example
Schema Object
The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the JSON Schema Specification Wright Draft 00.
For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated otherwise, the property definitions follow the JSON Schema.
Properties
The following properties are taken directly from the JSON Schema definition and follow the same specifications:
title
multipleOf
maximum
exclusiveMaximum
minimum
exclusiveMinimum
maxLength
minLength
pattern (This string SHOULD be a valid regular expression, according to the Ecma-262 Edition 5.1 regular expression dialect)
maxItems
minItems
uniqueItems
maxProperties
minProperties
required
enum
The following properties are taken from the JSON Schema definition but their definitions were adjusted to the OpenAPI Specification.
type - Value MUST be a string. Multiple types via an array are not supported.
allOf - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
oneOf - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
anyOf - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
not - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
items - Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
items
MUST be present if thetype
isarray
.properties - Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced).
additionalProperties - Value can be boolean or object. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. Consistent with JSON Schema,
additionalProperties
defaults totrue
.description - CommonMark syntax MAY be used for rich text representation.
format - See Data Type Formats for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats.
default - The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level. For example, if
type
isstring
, thendefault
can be"foo"
but cannot be1
.
Alternatively, any time a Schema Object can be used, a Reference Object can be used in its place. This allows referencing definitions instead of defining them inline.
Additional properties defined by the JSON Schema specification that are not mentioned here are strictly unsupported.
Other than the JSON Schema subset fields, the following fields MAY be used for further schema documentation:
Fixed Fields
Field Name | Type | Description |
---|---|---|
nullable |
| A |
discriminator | Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See Composition and Inheritance for more details. | |
readOnly |
| Relevant only for Schema |
writeOnly |
| Relevant only for Schema |
xml | This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. | |
externalDocs | Additional external documentation for this schema. | |
example | Any | A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. |
deprecated |
| Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is |
This object MAY be extended with Specification Extensions.
Composition and Inheritance (Polymorphism)
The OpenAPI Specification allows combining and extending model definitions using the allOf
property of JSON Schema, in effect offering model composition. allOf
takes an array of object definitions that are validated independently but together compose a single object.
While composition offers model extensibility, it does not imply a hierarchy between the models. To support polymorphism, the OpenAPI Specification adds the discriminator
field. When used, the discriminator
will be the name of the property that decides which schema definition validates the structure of the model. As such, the discriminator
field MUST be a required field. There are two ways to define the value of a discriminator for an inheriting instance.
Use the schema name.
Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name. As such, inline schema definitions, which do not have a given id, cannot be used in polymorphism.
XML Modeling
The xml property allows extra definitions when translating the JSON definition to XML. The XML Object contains additional information about the available options.
Schema Object Examples
Primitive Sample
Simple Model
Model with Map/Dictionary Properties
For a simple string to string mapping:
For a string to model mapping:
Model with Example
Models with Composition
Models with Polymorphism Support
Discriminator Object
When request bodies or response payloads may be one of a number of different schemas, a discriminator
object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it.
When using the discriminator, inline schemas will not be considered.
Fixed Fields
Field Name | Type | Description |
---|---|---|
propertyName |
| REQUIRED. The name of the property in the payload that will hold the discriminator value. |
mapping | Map[ | An object to hold mappings between payload values and schema names or references. |
The discriminator object is legal only when using one of the composite keywords oneOf
, anyOf
, allOf
.
In OAS 3.0, a response payload MAY be described to be exactly one of any number of types:
which means the payload MUST, by validation, match exactly one of the schemas described by Cat
, Dog
, or Lizard
. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use:
The expectation now is that a property with name petType
MUST be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload:
Will indicate that the Cat
schema be used in conjunction with this payload.
In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional mapping
definition MAY be used:
Here the discriminator value of dog
will map to the schema #/components/schemas/Dog
, rather than the default (implicit) value of Dog
. If the discriminator value does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison.
When used in conjunction with the anyOf
construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload.
In both the oneOf
and anyOf
use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an allOf
construct may be used as an alternate schema.
For example:
a payload like this:
will indicate that the Cat
schema be used. Likewise this schema:
will map to Dog
because of the definition in the mappings
element.
XML Object
A metadata object that allows for more fine-tuned XML model definitions.
When using arrays, XML element names are not inferred (for singular/plural forms) and the name
property SHOULD be used to add that information. See examples for expected behavior.
Fixed Fields
Field Name | Type | Description |
---|---|---|
name |
| Replaces the name of the element/attribute used for the described schema property. When defined within |
namespace |
| The URI of the namespace definition. Value MUST be in the form of an absolute URI. |
prefix |
| The prefix to be used for the name. |
attribute |
| Declares whether the property definition translates to an attribute instead of an element. Default value is |
wrapped |
| MAY be used only for an array definition. Signifies whether the array is wrapped (for example, |
This object MAY be extended with Specification Extensions.
XML Object Examples
The examples of the XML object definitions are included inside a property definition of a Schema Object with a sample of the XML representation of it.
No XML Element
Basic string property:
Basic string array property (wrapped
is false
by default):
XML Name Replacement
XML Attribute, Prefix and Namespace
In this example, a full model definition is shown.
XML Arrays
Changing the element names:
The external name
property has no effect on the XML:
Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally:
To overcome the naming problem in the example above, the following definition can be used:
Affecting both internal and external names:
If we change the external element but not the internal ones:
Security Scheme Object
Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in RFC6749, and OpenID Connect Discovery.
Fixed Fields
Field Name | Type | Applies To | Description |
---|---|---|---|
type |
| Any | REQUIRED. The type of the security scheme. Valid values are |
description |
| Any | A short description for security scheme. CommonMark syntax MAY be used for rich text representation. |
name |
|
| REQUIRED. The name of the header, query or cookie parameter to be used. |
in |
|
| REQUIRED. The location of the API key. Valid values are |
scheme |
|
| REQUIRED. The name of the HTTP Authorization scheme to be used in the Authorization header as defined in RFC7235. The values used SHOULD be registered in the IANA Authentication Scheme registry. |
bearerFormat |
|
| A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. |
flows |
| REQUIRED. An object containing configuration information for the flow types supported. | |
openIdConnectUrl |
|
| REQUIRED. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. |
This object MAY be extended with Specification Extensions.
Security Scheme Object Example
Basic Authentication Sample
API Key Sample
JWT Bearer Sample
Implicit OAuth2 Sample
OAuth Flows Object
Allows configuration of the supported OAuth Flows.
Fixed Fields
Field Name | Type | Description |
---|---|---|
implicit | Configuration for the OAuth Implicit flow | |
password | Configuration for the OAuth Resource Owner Password flow | |
clientCredentials | Configuration for the OAuth Client Credentials flow. Previously called | |
authorizationCode | Configuration for the OAuth Authorization Code flow. Previously called |
This object MAY be extended with Specification Extensions.
OAuth Flow Object
Configuration details for a supported OAuth Flow
Fixed Fields
Field Name | Type | Applies To | Description |
---|---|---|---|
authorizationUrl |
|
| REQUIRED. The authorization URL to be used for this flow. This MUST be in the form of a URL. |
tokenUrl |
|
| REQUIRED. The token URL to be used for this flow. This MUST be in the form of a URL. |
refreshUrl |
|
| The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. |
scopes | Map[ |
| REQUIRED. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. |
This object MAY be extended with Specification Extensions.
OAuth Flow Object Examples
Security Requirement Object
Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object.
Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information.
When a list of Security Requirement Objects is defined on the OpenAPI Object or Operation Object, only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request.
Patterned Fields
Field Pattern | Type | Description |
---|---|---|
{name} | [ | Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object. If the security scheme is of type |
Security Requirement Object Examples
Non-OAuth2 Security Requirement
OAuth2 Security Requirement
Optional OAuth2 Security
Optional OAuth2 security as would be defined in an OpenAPI Object or an Operation Object:
Last updated