1. Version 3.0.1
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](https://tools.ietf.org/html/bcp14) [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](https://www.apache.org/licenses/LICENSE-2.0.html).
2. 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.
3. Definitions
3.1. OpenAPI Document
A document (or set of documents) that defines or describes an API. An OpenAPI definition uses and conforms to the OpenAPI Specification.3.2. Path Templating
Path templating refers to the usage of curly braces ({}) to mark a section of a URL path as replaceable using path parameters.3.3. 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:
text/plain; charset=utf-8 application/json application/vnd.github+json application/vnd.github.v3+json application/vnd.github.v3.raw+json application/vnd.github.v3.text+json application/vnd.github.v3.html+json application/vnd.github.v3.full+json application/vnd.github.v3.diff application/vnd.github.v3.patch
3.4. 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](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml).4. Specification
4.1. Versions
The OpenAPI Specification is versioned using [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) (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.
Subsequent minor version releases of the OpenAPI Specification (incrementing the `minor` version number) SHOULD NOT interfere with tooling developed to a lower minor version and same major version. Thus a hypothetical `3.1.0` specification SHOULD be usable with tooling designed for `3.0.0`.
An OpenAPI document compatible with OAS 3.\*.\* contains a required [`openapi`](#oasVersion) field which designates the semantic version of the OAS that it uses. (OAS 2.0 documents contain a top-level version field named [`swagger`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swaggerObject) and value `"2.0"`.)
4.2. 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:
{ "field": [ 1, 2, 3 ] }All field names in the specification are **case sensitive**.
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](http://www.yaml.org/spec/1.2/spec.html) is RECOMMENDED along with some additional constraints:
-
Tags MUST be limited to those allowed by the [JSON Schema ruleset](http://www.yaml.org/spec/1.2/spec.html#id2803231).
-
Keys used in YAML maps MUST be limited to a scalar string, as defined by the [YAML Failsafe schema ruleset](http://yaml.org/spec/1.2/spec.html#id2802346).
**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.
4.3. 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](http://json-schema.org) definitions.
It is RECOMMENDED that the root OpenAPI document be named: `openapi.json` or `openapi.yaml`.
4.3.1. Data Types
Primitive data types in the OAS are based on the types supported by the [JSON Schema Specification Wright Draft 00](https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2). 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`](#schemaNullable) for an alternative solution). Models are defined using the [Schema Object](#schemaObject), 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:
Common Name | [`type`](#dataTypes) | [`format`](#dataTypeFormat) | Comments
----------- | ------ | -------- | ------—
4.3.2. 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](http://spec.commonmark.org/0.27/). Tooling MAY choose to ignore some CommonMark features to address security concerns.4.3.3. 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`](#serverObject) as a Base URI.
Relative references used in `$ref` are processed as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03), using the URL of the current document as the base URI. See also the [Reference Object](#referenceObject).
4.3.4. Schema
In the following description, if a field is not explicitly **REQUIRED** or described with a MUST or SHALL, it can be considered OPTIONAL.
4.3.4.1. OpenAPI Object
This is the root document object of the [OpenAPI document](#oasDocument).
4.3.4.1.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.2. 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.
4.3.4.2.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.2.2. Info Object Example:
{ "title": "Sample Pet Store App", "description": "This is a sample server for a pet store.", "termsOfService": "http://example.com/terms/", "contact": { "name": "API Support", "url": "http://www.example.com/support", "email": "support@example.com" }, "license": { "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html" }, "version": "1.0.1" }
title: Sample Pet Store App description: This is a sample server for a pet store. termsOfService: http://example.com/terms/ contact: name: API Support url: http://www.example.com/support email: support@example.com license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html version: 1.0.1
4.3.4.3. Contact Object
Contact information for the exposed API.
4.3.4.3.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.3.2. Contact Object Example:
{ "name": "API Support", "url": "http://www.example.com/support", "email": "support@example.com" }
name: API Support url: http://www.example.com/support email: support@example.com
4.3.4.4. License Object
License information for the exposed API.
4.3.4.4.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.4.2. License Object Example:
{ "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html" }
name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html
4.3.4.5. Server Object
An object representing a Server.
4.3.4.5.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.5.2. Server Object Example
A single server would be described as:
{ "url": "https://development.gigantic-server.com/v1", "description": "Development server" }
url: https://development.gigantic-server.com/v1 description: Development server
The following shows how multiple servers can be described, for example, at the OpenAPI Object’s [`servers`](#oasServers):
{ "servers": [ { "url": "https://development.gigantic-server.com/v1", "description": "Development server" }, { "url": "https://staging.gigantic-server.com/v1", "description": "Staging server" }, { "url": "https://api.gigantic-server.com/v1", "description": "Production server" } ] }
servers: - url: https://development.gigantic-server.com/v1 description: Development server - url: https://staging.gigantic-server.com/v1 description: Staging server - url: https://api.gigantic-server.com/v1 description: Production server
The following shows how variables can be used for a server configuration:
{ "servers": [ { "url": "https://{username}.gigantic-server.com:{port}/{basePath}", "description": "The production API server", "variables": { "username": { "default": "demo", "description": "this value is assigned by the service provider, in this example `gigantic-server.com`" }, "port": { "enum": [ "8443", "443" ], "default": "8443" }, "basePath": { "default": "v2" } } } ] }
servers: - url: https://{username}.gigantic-server.com:{port}/{basePath} description: The production API server variables: username: # note! no enum here means it is an open value default: demo description: this value is assigned by the service provider, in this example `gigantic-server.com` port: enum: - '8443' - '443' default: '8443' basePath: # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2` default: v2
4.3.4.6. Server Variable Object
An object representing a Server Variable for server URL template substitution.
4.3.4.6.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.7. 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.
4.3.4.7.1. Fixed Fields
Field Name | Type | Description
---|:---|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`.
Field Name Examples:
User User_1 User_Name user-name my.org.User
4.3.4.7.2. Components Object Example
"components": { "schemas": { "Category": { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" } } }, "Tag": { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" } } } }, "parameters": { "skipParam": { "name": "skip", "in": "query", "description": "number of items to skip", "required": true, "schema": { "type": "integer", "format": "int32" } }, "limitParam": { "name": "limit", "in": "query", "description": "max records to return", "required": true, "schema" : { "type": "integer", "format": "int32" } } }, "responses": { "NotFound": { "description": "Entity not found." }, "IllegalInput": { "description": "Illegal input for operation." }, "GeneralError": { "description": "General Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/GeneralError" } } } } }, "securitySchemes": { "api_key": { "type": "apiKey", "name": "api_key", "in": "header" }, "petstore_auth": { "type": "oauth2", "flows": { "implicit": { "authorizationUrl": "http://example.org/api/oauth/dialog", "scopes": { "write:pets": "modify pets in your account", "read:pets": "read your pets" } } } } } }
components:
schemas:
Category:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
Tag:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
parameters:
skipParam:
name: skip
in: query
description: number of items to skip
required: true
schema:
type: integer
format: int32
limitParam:
name: limit
in: query
description: max records to return
required: true
schema:
type: integer
format: int32
responses:
NotFound:
description: Entity not found.
IllegalInput:
description: Illegal input for operation.
GeneralError:
description: General Error
content:
application/json:
schema:
$ref: '#/components/schemas/GeneralError'
securitySchemes:
api_key:
type: apiKey
name: api_key
in: header
petstore_auth:
type: oauth2
flows:
implicit:
authorizationUrl: http://example.org/api/oauth/dialog
scopes:
write:pets: modify pets in your account
read:pets: read your pets
4.3.4.8. Paths Object
Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. The Paths MAY be empty, due to [ACL constraints](#securityFiltering).
4.3.4.8.1. Patterned Fields
Field Pattern | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.8.2. Path Templating Matching
Assuming the following paths, the concrete definition, `/pets/mine`, will be matched first if used:
/pets/{petId} /pets/mine
The following paths are considered identical and invalid:
/pets/{petId} /pets/{name}
The following may lead to ambiguous resolution:
/{entity}/me /books/{id}
4.3.4.8.3. Paths Object Example
{ "/pets": { "get": { "description": "Returns all pets from the system that the user has access to", "responses": { "200": { "description": "A list of pets.", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/pet" } } } } } } } } }
/pets: get: description: Returns all pets from the system that the user has access to responses: '200': description: A list of pets. content: application/json: schema: type: array items: $ref: '#/components/schemas/pet'
4.3.4.9. Path Item Object
Describes the operations available on a single path. A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.
4.3.4.9.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.9.2. Path Item Object Example
{ "get": { "description": "Returns pets based on ID", "summary": "Find pets by ID", "operationId": "getPetsById", "responses": { "200": { "description": "pet response", "content": { "*/*": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Pet" } } } } }, "default": { "description": "error payload", "content": { "text/html": { "schema": { "$ref": "#/components/schemas/ErrorModel" } } } } } }, "parameters": [ { "name": "id", "in": "path", "description": "ID of pet to use", "required": true, "schema": { "type": "array", "items": { "type": "string" } }, "style": "simple" } ] }
get: description: Returns pets based on ID summary: Find pets by ID operationId: getPetsById responses: '200': description: pet response content: '*/*' : schema: type: array items: $ref: '#/components/schemas/Pet' default: description: error payload content: 'text/html': schema: $ref: '#/components/schemas/ErrorModel' parameters: - name: id in: path description: ID of pet to use required: true schema: type: array style: simple items: type: string
4.3.4.10. Operation Object
Describes a single API operation on a path.
4.3.4.10.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.10.2. Operation Object Example
{ "tags": [ "pet" ], "summary": "Updates a pet in the store with form data", "operationId": "updatePetWithForm", "parameters": [ { "name": "petId", "in": "path", "description": "ID of pet that needs to be updated", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/x-www-form-urlencoded": { "schema": { "type": "object", "properties": { "name": { "description": "Updated name of the pet", "type": "string" }, "status": { "description": "Updated status of the pet", "type": "string" } }, "required": ["status"] } } } }, "responses": { "200": { "description": "Pet updated.", "content": { "application/json": {}, "application/xml": {} } }, "405": { "description": "Invalid input", "content": { "application/json": {}, "application/xml": {} } } }, "security": [ { "petstore_auth": [ "write:pets", "read:pets" ] } ] }
tags: - pet summary: Updates a pet in the store with form data operationId: updatePetWithForm parameters: - name: petId in: path description: ID of pet that needs to be updated required: true schema: type: string requestBody: content: 'application/x-www-form-urlencoded': schema: properties: name: description: Updated name of the pet type: string status: description: Updated status of the pet type: string required: - status responses: '200': description: Pet updated. content: 'application/json': {} 'application/xml': {} '405': description: Invalid input content: 'application/json': {} 'application/xml': {} security: - petstore_auth: - write:pets - read:pets
4.3.4.11. External Documentation Object
Allows referencing an external resource for extended documentation.
4.3.4.11.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.11.2. External Documentation Object Example
{ "description": "Find more info here", "url": "https://example.com" }
description: Find more info here url: https://example.com
4.3.4.12. Parameter Object
Describes a single operation parameter.
A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn).
4.3.4.12.1. Parameter Locations
There are four possible parameter locations specified by the `in` field:-
path - Used together with [Path Templating](#pathTemplating), 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 is `itemId`.
-
query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`.
-
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.
4.3.4.12.2. Fixed Fields
Field Name | Type | Description ---|:---:|-—- If [`in`](#parameterIn) is `"path"`, the `name` field MUST correspond to the associated path segment from the [path](#pathsPath) field in the [Paths Object](#pathsObject). See [Path Templating](#pathTemplating) for further information.
- If [`in`](#parameterIn) is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored.
- For all other cases, the `name` corresponds to the parameter name used by the [`in`](#parameterIn) property.
The rules for serialization of the parameter are specified in one of two ways. For simpler scenarios, a [`schema`](#parameterSchema) and [`style`](#parameterStyle) can describe the structure and syntax of the parameter.
Field Name | Type | Description
---|:---:|-—
For more complex scenarios, the [`content`](#parameterContent) 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
---|:---:|-—
4.3.4.12.3. Style Values
In order to support common ways of serializing simple parameters, a set of `style` values are defined.
`style` | [`type`](#dataTypes) | `in` | Comments
----------- | ------ | -------- | ------—
4.3.4.12.4. Style Examples
Assume a parameter named `color` has one of the following values:
string -> "blue" array -> ["blue","black","brown"] object -> { "R": 100, "G": 200, "B": 150 }The following table shows examples of rendering differences for each value.
[`style`](#dataTypeFormat) | `explode` | `empty` | `string` | `array` | `object`
----------- | ------ | -------- | -------- | --------|-----—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.12.5. Parameter Object Examples
A header parameter with an array of 64 bit integer numbers:
{ "name": "token", "in": "header", "description": "token to be passed as a header", "required": true, "schema": { "type": "array", "items": { "type": "integer", "format": "int64" } }, "style": "simple" }
name: token in: header description: token to be passed as a header required: true schema: type: array items: type: integer format: int64 style: simple
A path parameter of a string value:
{ "name": "username", "in": "path", "description": "username to fetch", "required": true, "schema": { "type": "string" } }
name: username in: path description: username to fetch required: true schema: type: string
An optional query parameter of a string value, allowing multiple values by repeating the query parameter:
{ "name": "id", "in": "query", "description": "ID of the object to fetch", "required": false, "schema": { "type": "array", "items": { "type": "string" } }, "style": "form", "explode": true }
name: id in: query description: ID of the object to fetch required: false schema: type: array items: type: string style: form explode: true
A free-form query parameter, allowing undefined parameters of a specific type:
{ "in": "query", "name": "freeForm", "schema": { "type": "object", "additionalProperties": { "type": "integer" }, }, "style": "form" }
in: query name: freeForm schema: type: object additionalProperties: type: integer style: form
A complex parameter using `content` to define serialization:
{ "in": "query", "name": "coordinates", "content": { "application/json": { "schema": { "type": "object", "required": [ "lat", "long" ], "properties": { "lat": { "type": "number" }, "long": { "type": "number" } } } } } }
in: query name: coordinates content: application/json: schema: type: object required: - lat - long properties: lat: type: number long: type: number
4.3.4.13. Request Body Object
Describes a single request body.
4.3.4.13.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.13.2. Request Body Examples
A request body with a referenced model definition.
{ "description": "user to add to the system", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/User" }, "examples": { "user" : { "summary": "User Example", "externalValue": "http://foo.bar/examples/user-example.json" } } }, "application/xml": { "schema": { "$ref": "#/components/schemas/User" }, "examples": { "user" : { "summary": "User example in XML", "externalValue": "http://foo.bar/examples/user-example.xml" } } }, "text/plain": { "examples": { "user" : { "summary": "User example in Plain text", "externalValue": "http://foo.bar/examples/user-example.txt" } } }, "*/*": { "examples": { "user" : { "summary": "User example in other format", "externalValue": "http://foo.bar/examples/user-example.whatever" } } } } }
description: user to add to the system content: 'application/json': schema: $ref: '#/components/schemas/User' examples: user: summary: User Example externalValue: 'http://foo.bar/examples/user-example.json' 'application/xml': schema: $ref: '#/components/schemas/User' examples: user: summary: User Example in XML externalValue: 'http://foo.bar/examples/user-example.xml' 'text/plain': examples: user: summary: User example in text plain format externalValue: 'http://foo.bar/examples/user-example.txt' '*/*': examples: user: summary: User example in other format externalValue: 'http://foo.bar/examples/user-example.whatever'
A body parameter that is an array of string values:
{ "description": "user to add to the system", "content": { "text/plain": { "schema": { "type": "array", "items": { "type": "string" } } } } }
description: user to add to the system required: true content: text/plain: schema: type: array items: type: string
4.3.4.14. Media Type Object
Each Media Type Object provides schema and examples for the media type identified by its key.4.3.4.14.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.14.2. Media Type Examples
{ "application/json": { "schema": { "$ref": "#/components/schemas/Pet" }, "examples": { "cat" : { "summary": "An example of a cat", "value": { "name": "Fluffy", "petType": "Cat", "color": "White", "gender": "male", "breed": "Persian" } }, "dog": { "summary": "An example of a dog with a cat’s name", "value" : { "name": "Puma", "petType": "Dog", "color": "Black", "gender": "Female", "breed": "Mixed" }, "frog": { "$ref": "#/components/examples/frog-example" } } } } }
application/json: schema: $ref: "#/components/schemas/Pet" examples: cat: summary: An example of a cat value: name: Fluffy petType: Cat color: White gender: male breed: Persian dog: summary: An example of a dog with a cat’s name value: name: Puma petType: Dog color: Black gender: Female breed: Mixed frog: $ref: "#/components/examples/frog-example"
4.3.4.14.3. 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:
# content transferred with base64 encoding
schema:
type: string
format: base64
# content transferred in binary (octet-stream):
schema:
type: string
format: binary
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:
requestBody: content: application/octet-stream: # any media type is accepted, functionally equivalent to `*/*` schema: # a binary file of any type type: string format: binary
In addition, specific media types MAY be specified:
# multiple, specific media types may be specified: requestBody: content: # a binary file of type png or jpeg 'image/jpeg': schema: type: string format: binary 'image/png': schema: type: string format: binary
To upload multiple files, a `multipart` media type MUST be used:
requestBody:
content:
multipart/form-data:
schema:
properties:
# The property name 'file' will be used for all files.
file:
type: array
items:
type: string
format: binary
4.3.4.14.4. Support for x-www-form-urlencoded Request Bodies
To submit content using form url encoding via [RFC2854], the following definition may be used:
requestBody:
content:
application/x-www-form-urlencoded:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
# complex types are stringified to support RFC 1866
type: object
properties: {}
In this example, the contents in the `requestBody` MUST be stringified per [RFC2854] 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`](#encodingObject)'s [`style`](#encodingStyle) property as `form`.
4.3.4.14.5. 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` with `format: binary` or `format: base64` (aka a file object), the default Content-Type is `application/octet-stream`
Examples:
requestBody: content: multipart/form-data: schema: type: object properties: id: type: string format: uuid address: # default Content-Type for objects is `application/json` type: object properties: {} profileImage: # default Content-Type for string/binary is `application/octet-stream` type: string format: binary children: # default Content-Type for arrays is based on the `inner` type (text/plain here) type: array items: type: string addresses: # default Content-Type for arrays is based on the `inner` type (object shown, so `application/json` in this example) type: array items: type: '#/components/schemas/Address'
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.
4.3.4.15. Encoding Object
A single encoding definition applied to a single schema property.
4.3.4.15.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.15.2. Encoding Object Example
requestBody: content: multipart/mixed: schema: type: object properties: id: # default is text/plain type: string format: uuid address: # default is application/json type: object properties: {} historyMetadata: # need to declare XML format! description: metadata in XML format type: object properties: {} profileImage: # default is application/octet-stream, need to declare an image type only! type: string format: binary encoding: historyMetadata: # require XML Content-Type in utf-8 encoding contentType: application/xml; charset=utf-8 profileImage: # only accept png/jpeg contentType: image/png, image/jpeg headers: X-Rate-Limit-Limit: description: The number of allowed requests in the current period schema: type: integer
4.3.4.16. 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.
4.3.4.16.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—4.3.4.16.2. Patterned Fields
Field Pattern | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.16.3. Responses Object Example
A 200 response for a successful operation and a default response for others (implying an error):
{ "200": { "description": "a pet to be returned", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Pet" } } } }, "default": { "description": "Unexpected error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorModel" } } } } }
'200': description: a pet to be returned content: application/json: schema: $ref: '#/components/schemas/Pet' default: description: Unexpected error content: application/json: schema: $ref: '#/components/schemas/ErrorModel'
4.3.4.17. Response Object
Describes a single response from an API Operation, including design-time, static `links` to operations based on the response.4.3.4.17.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.17.2. Response Object Examples
Response of an array of a complex type:
{ "description": "A complex object array response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/VeryComplexType" } } } } }
description: A complex object array response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/VeryComplexType'
Response with a string type:
{ "description": "A simple string response", "content": { "text/plain": { "schema": { "type": "string" } } } }
description: A simple string response content: text/plain: schema: type: string
Plain text response with headers:
{ "description": "A simple string response", "content": { "text/plain": { "schema": { "type": "string" } } }, "headers": { "X-Rate-Limit-Limit": { "description": "The number of allowed requests in the current period", "schema": { "type": "integer" } }, "X-Rate-Limit-Remaining": { "description": "The number of remaining requests in the current period", "schema": { "type": "integer" } }, "X-Rate-Limit-Reset": { "description": "The number of seconds left in the current period", "schema": { "type": "integer" } } } }
description: A simple string response
content:
text/plain:
schema:
type: string
example: 'whoa!'
headers:
X-Rate-Limit-Limit:
description: The number of allowed requests in the current period
schema:
type: integer
X-Rate-Limit-Remaining:
description: The number of remaining requests in the current period
schema:
type: integer
X-Rate-Limit-Reset:
description: The number of seconds left in the current period
schema:
type: integer
Response with no return value:
{ "description": "object created" }
description: object created
4.3.4.18. 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](#pathItemObject) 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 callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
4.3.4.18.1. Patterned Fields
Field Pattern | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.18.2. Key Expression
The key that identifies the [Path Item Object](#pathItemObject) is a [runtime expression](#runtimeExpression) 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](#runtimeExpression) 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:
POST /subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning HTTP/1.1 Host: example.org Content-Type: application/json Content-Length: 187 { "failedUrl" : "http://clientdomain.com/failed", "successUrls" : [ "http://clientdomain.com/fast", "http://clientdomain.com/medium", "http://clientdomain.com/slow" ] } 201 Created Location: http://example.org/subscription/1
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
---|:-—
4.3.4.18.3. Callback Object Example
The following example shows a callback to the URL specified by the `id` and `email` property in the request body.
myWebhook: 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}': post: requestBody: description: Callback payload content: 'application/json': schema: $ref: '#/components/schemas/SomePayload' responses: '200': description: webhook successfully processed and no retries will be performed
4.3.4.19. Example Object
4.3.4.19.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
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.
4.3.4.19.2. Example Object Example
# in a model schemas: properties: name: type: string examples: name: $ref: http://example.org/petapi-examples/openapi.json#/components/examples/name-example # in a request body: requestBody: content: 'application/json': schema: $ref: '#/components/schemas/Address' examples: foo: summary: A foo example value: {"foo": "bar"} bar: summary: A bar example value: {"bar": "baz"} 'application/xml': examples: xmlExample: summary: This is an example in XML externalValue: 'http://example.org/examples/address-example.xml' 'text/plain': examples: textExample: summary: This is a text example externalValue: 'http://foo.bar/examples/address-example.txt' # in a parameter parameters: - name: 'zipCode' in: 'query' schema: type: 'string' format: 'zip-code' examples: zip-example: $ref: '#/components/examples/zip-example' # in a response responses: '200': description: your car appointment has been booked content: application/json: schema: $ref: '#/components/schemas/SuccessResponse' examples: confirmation-success: $ref: '#/components/examples/confirmation-success'
4.3.4.20. 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](#runtimeExpression) is used for accessing values in an operation and using them as parameters while invoking the linked operation.
4.3.4.20.1. Fixed Fields
Field Name | Type | Description
---|:---:|-—
This object MAY be extended with [Specification Extensions](#specificationExtensions).
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.
4.3.4.20.2. Examples
Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation.
paths: /users/{id}: parameters: - name: id in: path required: true description: the user identifier, as userId schema: type: string get: responses: '200': description: the user being returned content: application/json: schema: type: object properties: uuid: # the unique user id type: string format: uuid links: address: # the target link operationId operationId: getUserAddress parameters: # get the `id` field from the request path parameter named `id` userId: $request.path.id # the path item of the linked operation /users/{userid}/address: parameters: - name: userid in: path required: true description: the user identifier, as userId schema: type: string # linked operation get: operationId: getUserAddress responses: '200': description: the user’s address
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.
links:
address:
operationId: getUserAddressByUUID
parameters:
# get the `uuid` field from the `uuid` field in the response body
userUuid: $response.body#/uuid
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.
4.3.4.20.3. OperationRef Examples
As references to `operationId` MAY NOT be possible (the `operationId` is an optional value), references MAY also be made through a relative `operationRef`:
links: UserRepositories: # returns array of '#/components/schemas/repository' operationRef: '#/paths/~12.0~1repositories~1{username}/get' parameters: username: $response.body#/username
or an absolute `operationRef`:
links: UserRepositories: # returns array of '#/components/schemas/repository' operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get' parameters: username: $response.body#/username
Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when using JSON references.
4.3.4.20.4. 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](#linkObject) and [Callback Objects](#callbackObject).
The runtime expression is defined by the following [ABNF](https://tools.ietf.org/html/rfc5234) syntax
expression = ( "$url" | "$method" | "$statusCode" | "$request." source | "$response." source ) source = ( header-reference | query-reference | path-reference | body-reference ) header-reference = "header." token query-reference = "query." name path-reference = "path." name body-reference = "body" ["#" fragment] fragment = a JSON Pointer [[RFC 6901]] name = *( char ) char = as per RFC [[7159]] token = as per 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:
4.3.4.20.5. Examples
Source Location | example expression | notes ---|:---|:---| HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. Requested media type | `$request.header.accept` | Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. Request URL | `$url` | Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. Response header | `$response.header.Server` | 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.
4.3.4.21. Header Object
The Header Object follows the structure of the \[Parameter Object](#parameterObject) with the following changes:
-
`name` MUST NOT be specified, it is given in the corresponding `headers` map.
-
`in` MUST NOT be specified, it is implicitly in `header`.
-
All traits that are affected by the location MUST be applicable to a location of `header` (for example, \[`style`](#parameterStyle)).
4.3.4.21.1. Header Object Example
A simple header of type `integer`:
{ "description": "The number of allowed requests in the current period", "schema": { "type": "integer" } }
description: The number of allowed requests in the current period schema: type: integer
4.3.4.22. Tag Object
Adds metadata to a single tag that is used by the [Operation Object](#operationObject). It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.
4.3.4.22.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.22.2. Tag Object Example
{ "name": "pet", "description": "Pets operations" }
name: pet description: Pets operations
4.3.4.23. Reference Object
A simple object to allow referencing other components in the specification, internally and externally.
The Reference Object is defined by [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) 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.
4.3.4.23.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object cannot be extended with additional properties and any properties added SHALL be ignored.
4.3.4.23.2. Reference Object Example
{ "$ref": "#/components/schemas/Pet" }
$ref: '#/components/schemas/Pet'
4.3.4.23.3. Relative Schema Document Example
{ "$ref": "Pet.json" }
$ref: Pet.yaml
4.3.4.23.4. Relative Documents With Embedded Schema Example
{ "$ref": "definitions.json#/Pet" }
$ref: definitions.yaml#/Pet
4.3.4.24. 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](http://json-schema.org/).
For more information about the properties, see [JSON Schema Core](https://tools.ietf.org/html/draft-wright-json-schema-00) and [JSON Schema Validation](https://tools.ietf.org/html/draft-wright-json-schema-validation-00). Unless stated otherwise, the property definitions follow the JSON Schema.
4.3.4.24.1. 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 regular expression](https://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5) 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](#schemaObject) and not a standard JSON Schema.
-
oneOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema.
-
anyOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema.
-
not - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) 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](#schemaObject) and not a standard JSON Schema. `items` MUST be present if the `type` is `array`.
-
properties - Property definitions MUST be a [Schema Object](#schemaObject) 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](#schemaObject) and not a standard JSON Schema.
-
description - [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation.
-
format - See \[Data Type Formats](#dataTypeFormat) 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` is `string`, then `default` can be `"foo"` but cannot be `1`.
Alternatively, any time a Schema Object can be used, a [Reference Object](#referenceObject) 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:
4.3.4.24.2. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
###### Composition and Inheritance (Polymorphism) ###### {#schemaComposition}
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](#schemaXml) property allows extra definitions when translating the JSON definition to XML. The [XML Object](#xmlObject) contains additional information about the available options.
4.3.4.24.3. Schema Object Examples
###### Primitive Sample
{ "type": "string", "format": "email" }
type: string format: email
###### Simple Model
{ "type": "object", "required": [ "name" ], "properties": { "name": { "type": "string" }, "address": { "$ref": "#/components/schemas/Address" }, "age": { "type": "integer", "format": "int32", "minimum": 0 } } }
type: object
required:
- name
properties:
name:
type: string
address:
$ref: '#/components/schemas/Address'
age:
type: integer
format: int32
minimum: 0
###### Model with Map/Dictionary Properties
For a simple string to string mapping:
{ "type": "object", "additionalProperties": { "type": "string" } }
type: object additionalProperties: type: string
For a string to model mapping:
{ "type": "object", "additionalProperties": { "$ref": "#/components/schemas/ComplexModel" } }
type: object
additionalProperties:
$ref: '#/components/schemas/ComplexModel'
###### Model with Example
{ "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" } }, "required": [ "name" ], "example": { "name": "Puma", "id": 1 } }
type: object properties: id: type: integer format: int64 name: type: string required: - name example: name: Puma id: 1
###### Models with Composition
{ "components": { "schemas": { "ErrorModel": { "type": "object", "required": [ "message", "code" ], "properties": { "message": { "type": "string" }, "code": { "type": "integer", "minimum": 100, "maximum": 600 } } }, "ExtendedErrorModel": { "allOf": [ { "$ref": "#/components/schemas/ErrorModel" }, { "type": "object", "required": [ "rootCause" ], "properties": { "rootCause": { "type": "string" } } } ] } } } }
components:
schemas:
ErrorModel:
type: object
required:
- message
- code
properties:
message:
type: string
code:
type: integer
minimum: 100
maximum: 600
ExtendedErrorModel:
allOf:
- $ref: '#/components/schemas/ErrorModel'
- type: object
required:
- rootCause
properties:
rootCause:
type: string
###### Models with Polymorphism Support
{ "components": { "schemas": { "Pet": { "type": "object", "discriminator": { "propertyName": "petType" }, "properties": { "name": { "type": "string" }, "petType": { "type": "string" } }, "required": [ "name", "petType" ] }, "Cat": { "description": "A representation of a cat. Note that `Cat` will be used as the discriminator value.", "allOf": [ { "$ref": "#/components/schemas/Pet" }, { "type": "object", "properties": { "huntingSkill": { "type": "string", "description": "The measured skill for hunting", "default": "lazy", "enum": [ "clueless", "lazy", "adventurous", "aggressive" ] } }, "required": [ "huntingSkill" ] } ] }, "Dog": { "description": "A representation of a dog. Note that `Dog` will be used as the discriminator value.", "allOf": [ { "$ref": "#/components/schemas/Pet" }, { "type": "object", "properties": { "packSize": { "type": "integer", "format": "int32", "description": "the size of the pack the dog is from", "default": 0, "minimum": 0 } }, "required": [ "packSize" ] } ] } } } }
components: schemas: Pet: type: object discriminator: propertyName: petType properties: name: type: string petType: type: string required: - name - petType Cat: ## "Cat" will be used as the discriminator value description: A representation of a cat allOf: - $ref: '#/components/schemas/Pet' - type: object properties: huntingSkill: type: string description: The measured skill for hunting enum: - clueless - lazy - adventurous - aggressive required: - huntingSkill Dog: ## "Dog" will be used as the discriminator value description: A representation of a dog allOf: - $ref: '#/components/schemas/Pet' - type: object properties: packSize: type: integer format: int32 description: the size of the pack the dog is from default: 0 minimum: 0 required: - packSize
4.3.4.25. 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.
4.3.4.25.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—The discriminator attribute 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:
MyResponseType: oneOf: - $ref: '#/components/schemas/Cat' - $ref: '#/components/schemas/Dog' - $ref: '#/components/schemas/Lizard'
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:
MyResponseType: oneOf: - $ref: '#/components/schemas/Cat' - $ref: '#/components/schemas/Dog' - $ref: '#/components/schemas/Lizard' discriminator: propertyName: pet_type
The expectation now is that a property with name `pet_type` _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:
{ "id": 12345, "pet_type": "Cat" }
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:
MyResponseType: oneOf: - $ref: '#/components/schemas/Cat' - $ref: '#/components/schemas/Dog' - $ref: '#/components/schemas/Lizard' - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json' discriminator: propertyName: pet_type mapping: dog: '#/components/schemas/Dog' monster: 'https://gigantic-server.com/schemas/Monster/schema.json'
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:
components: schemas: Pet: type: object required: - pet_type properties: pet_type: type: string discriminator: propertyName: pet_type mapping: cachorro: Dog Cat: allOf: - $ref: '#/components/schemas/Pet' - type: object # all other properties specific to a `Cat` properties: name: type: string Dog: allOf: - $ref: '#/components/schemas/Pet' - type: object # all other properties specific to a `Dog` properties: bark: type: string Lizard: allOf: - $ref: '#/components/schemas/Pet' - type: object # all other properties specific to a `Lizard` properties: lovesRocks: type: boolean
a payload like this:
{ "pet_type": "Cat", "name": "misty" }
will indicate that the `Cat` schema be used. Likewise this schema:
{ "pet_type": "cachorro", "bark": "soft" }
will map to `Dog` because of the definition in the `mappings` element.
4.3.4.26. 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.
4.3.4.26.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.26.2. XML Object Examples
The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schemaObject) with a sample of the XML representation of it.
###### No XML Element
Basic string property:
{ "animals": { "type": "string" } }
animals: type: string
<animals>...</animals>
Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default):
{ "animals": { "type": "array", "items": { "type": "string" } } }
animals: type: array items: type: string
<animals>...</animals> <animals>...</animals> <animals>...</animals>
###### XML Name Replacement
{ "animals": { "type": "string", "xml": { "name": "animal" } } }
animals: type: string xml: name: animal
<animal>...</animal>
###### XML Attribute, Prefix and Namespace
In this example, a full model definition is shown.
{ "Person": { "type": "object", "properties": { "id": { "type": "integer", "format": "int32", "xml": { "attribute": true } }, "name": { "type": "string", "xml": { "namespace": "http://example.com/schema/sample", "prefix": "sample" } } } } }
Person: type: object properties: id: type: integer format: int32 xml: attribute: true name: type: string xml: namespace: http://example.com/schema/sample prefix: sample
<Person id="123"> <sample:name xmlns:sample="http://example.com/schema/sample">example</sample:name> </Person>
###### XML Arrays
Changing the element names:
{ "animals": { "type": "array", "items": { "type": "string", "xml": { "name": "animal" } } } }
animals: type: array items: type: string xml: name: animal
<animal>value</animal> <animal>value</animal>
The external `name` property has no effect on the XML:
{ "animals": { "type": "array", "items": { "type": "string", "xml": { "name": "animal" } }, "xml": { "name": "aliens" } } }
animals: type: array items: type: string xml: name: animal xml: name: aliens
<animal>value</animal> <animal>value</animal>
Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally:
{ "animals": { "type": "array", "items": { "type": "string" }, "xml": { "wrapped": true } } }
animals: type: array items: type: string xml: wrapped: true
<animals> <animals>value</animals> <animals>value</animals> </animals>
To overcome the naming problem in the example above, the following definition can be used:
{ "animals": { "type": "array", "items": { "type": "string", "xml": { "name": "animal" } }, "xml": { "wrapped": true } } }
animals: type: array items: type: string xml: name: animal xml: wrapped: true
<animals> <animal>value</animal> <animal>value</animal> </animals>
Affecting both internal and external names:
{ "animals": { "type": "array", "items": { "type": "string", "xml": { "name": "animal" } }, "xml": { "name": "aliens", "wrapped": true } } }
animals: type: array items: type: string xml: name: animal xml: name: aliens wrapped: true
<aliens> <animal>value</animal> <animal>value</animal> </aliens>
If we change the external element but not the internal ones:
{ "animals": { "type": "array", "items": { "type": "string" }, "xml": { "name": "aliens", "wrapped": true } } }
animals: type: array items: type: string xml: name: aliens wrapped: true
<aliens> <aliens>value</aliens> <aliens>value</aliens> </aliens>
4.3.4.27. 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 or as a query parameter), OAuth2’s common flows (implicit, password, application and access code) as defined in [RFC6749], and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06).
4.3.4.27.1. Fixed Fields
Field Name | Type | Applies To | Description ---|:---:|---|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.27.2. Security Scheme Object Example
###### Basic Authentication Sample
{ "type": "http", "scheme": "basic" }
type: http scheme: basic
###### API Key Sample
{ "type": "apiKey", "name": "api_key", "in": "header" }
type: apiKey name: api_key in: header
###### JWT Bearer Sample
{ "type": "http", "scheme": "bearer", "bearerFormat": "JWT", }
type: http scheme: bearer bearerFormat: JWT
###### Implicit OAuth2 Sample
{ "type": "oauth2", "flows": { "implicit": { "authorizationUrl": "https://example.com/api/oauth/dialog", "scopes": { "write:pets": "modify pets in your account", "read:pets": "read your pets" } } } }
type: oauth2 flows: implicit: authorizationUrl: https://example.com/api/oauth/dialog scopes: write:pets: modify pets in your account read:pets: read your pets
4.3.4.28. OAuth Flows Object
Allows configuration of the supported OAuth Flows.
4.3.4.28.1. Fixed Fields
Field Name | Type | Description ---|:---:|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.29. OAuth Flow Object
Configuration details for a supported OAuth Flow
4.3.4.29.1. Fixed Fields
Field Name | Type | Applies To | Description ---|:---:|---|-—This object MAY be extended with [Specification Extensions](#specificationExtensions).
4.3.4.29.2. OAuth Flow Object Examples
{ "type": "oauth2", "flows": { "implicit": { "authorizationUrl": "https://example.com/api/oauth/dialog", "scopes": { "write:pets": "modify pets in your account", "read:pets": "read your pets" } }, "authorizationCode": { "authorizationUrl": "https://example.com/api/oauth/dialog", "tokenUrl": "https://example.com/api/oauth/token", "scopes": { "write:pets": "modify pets in your account", "read:pets": "read your pets" } } } }
type: oauth2 flows: implicit: authorizationUrl: https://example.com/api/oauth/dialog scopes: write:pets: modify pets in your account read:pets: read your pets authorizationCode: authorizationUrl: https://example.com/api/oauth/dialog tokenUrl: https://example.com/api/oauth/token scopes: write:pets: modify pets in your account read:pets: read your pets
4.3.4.30. 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](#componentsSecuritySchemes) under the [Components Object](#componentsObject).
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 [Open API object](#oasObject) or [Operation Object](#operationObject), only one of Security Requirement Objects in the list needs to be satisfied to authorize the request.
4.3.4.30.1. Patterned Fields
Field Pattern | Type | Description
---|:---:|-—
4.3.4.30.2. Security Requirement Object Examples
###### Non-OAuth2 Security Requirement
{ "api_key": [] }
api_key: []
###### OAuth2 Security Requirement
{ "petstore_auth": [ "write:pets", "read:pets" ] }
petstore_auth: - write:pets - read:pets
4.3.5. Specification Extensions
While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points.
The extensions properties are implemented as patterned fields that are always prefixed by `"x-"`.
Field Pattern | Type | Description
---|:---:|-—
The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced).
4.3.6. Security Filtering
Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation.
The reasoning is to allow an additional layer of access control over the documentation. While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization.
Two examples of this:
-
The [Paths Object](#pathsObject) MAY be empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can’t access any documentation. They’d still have access to the [Info Object](#infoObject) which may contain additional information regarding authentication.
-
The [Path Item Object](#pathItemObject) MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different than hiding the path itself from the [Paths Object](#pathsObject), so the user will not be aware of its existence. This allows the documentation provider to finely control what the viewer can see.
Appendix A: Revision History
Version | Date | Notes
--- | --- | -—