Copyright © 2025 the Linux Foundation
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 inBCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.
This document is licensed underThe Apache License, Version 2.0.
The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to HTTP 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 byparsing and serializing HTTP messages to and from adata model with a minimal amount of implementation logic.
AnOpenAPI Description (OAD) 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.
For examples of OpenAPI usage and additional documentation, please visit [OpenAPI-Learn].
For extension registries and other specifications published by the OpenAPI Initiative, as well as the authoritative rendering of this specification, please visitspec.openapis.org.
The OpenAPI Specification is versioned using amajor.minor.patch versioning scheme. Themajor.minor portion of the version string (for example3.1)SHALL designate the OAS feature set..patch versions address errors in, or provide clarifications to, this document, not the feature set. Tooling which supports OAS 3.1SHOULD be compatible with all OAS 3.1.* versions. The patch versionSHOULD NOT be considered by tooling, making no distinction between3.1.0 and3.1.1 for example.
Certain fields or features may be markedDeprecated.These fields and features remain part of the specification and can be used like any other field or feature.However, OpenAPI Description authors should use newer fields and features documented to replace the deprecated ones whenever possible.
At this time, such elements are expected to remain part of the OAS until the next major version, although a future minor version of this specification may define a policy for later removal of deprecated elements.
Occasionally, non-backwards compatible changes may be made inminor versions of the OAS where impact is believed to be low relative to the benefit provided.
This specification deems certain situations to have eitherundefined orimplementation-defined behavior.
Behavior described asundefined is likely, at least in some circumstances, to result in outcomes that contradict the specification.This description is used when detecting the contradiction is impossible or impractical.ImplementationsMAY support undefined scenarios for historical reasons, including ambiguous text in prior versions of the specification.This support might produce correct outcomes in many cases, but relying on it isNOT RECOMMENDED as there is no guarantee that it will work across all tools or with future specification versions, even if those versions are otherwise strictly compatible with this one.
Behavior described asimplementation-defined allows implementations to choose which of several different-but-compliant approaches to a requirement to implement.This documents ambiguous requirements that API description authors areRECOMMENDED to avoid in order to maximize interoperability.Unlike undefined behavior, it is safe to rely on implementation-defined behavior ifand only if it can be guaranteed that all relevant tools support the same behavior.
An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either inJSON orYAML format.Examples in this specification will be shown in YAML for brevity.
All field names in the specification arecase-sensitive.This includes all fields that are used as keys in a map, except where explicitly noted that keys arecase-insensitive.
OASObjects expose two types of fields:fixed fields, which have a declared name, andpatterned fields, which have a declared pattern for the field name.
Patterned fieldsMUST have unique names within the containing object.
Note: While APIs may be described by OpenAPI Descriptions in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML.
In order to preserve the ability to round-trip between YAML and JSON formats,YAML version 1.2 isRECOMMENDED along with the additional constraints listed in [RFC9512]Section 3.4.
The recommendation in previous versions of this specification to restrict YAML to its “JSON”schema ruleset allowed for the inclusion of certain values that (despite the name) cannot be represented in JSON.OAD authorsSHOULD NOT rely on any such JSON-incompatible YAML values.
As most field names and values in the OpenAPI Specification are case-sensitive, this document endeavors to call out any case-insensitive names and values.However, the case sensitivity of field names and values that map directly to HTTP concepts follow the case sensitivity rules of HTTP, even if this document does not make a note of every concept.
Throughout the specificationdescription fields are noted as supporting [CommonMark] markdown formatting.Where OpenAPI tooling renders rich text itMUST support, at a minimum, markdown syntax as described by [CommonMark-0.27]. ToolingMAY choose to ignore some CommonMark or extension features to address security concerns.
While the framing of CommonMark 0.27 as a minimum requirement means that toolingMAY choose to implement extensions on top of it, note that any such extensions are by definition implementation-defined and will not be interoperable.OpenAPI Description authorsSHOULD consider how text using such extensions will be rendered by tools that offer only the minimum support.
This section describes the structure of the OpenAPI Description format.This text is the only normative description of the format.A JSON Schema is hosted onspec.openapis.org for informational purposes.If the JSON Schema differs from this section, then this sectionMUST be considered authoritative.
In the following description, if a field is not explicitlyREQUIRED or described with aMUST orSHALL, it can be consideredOPTIONAL.
This is the root object of theOpenAPI Description.
In addition to the required fields, at least one of thecomponents,paths, orwebhooks fieldsMUST be present.
| Field Name | Type | Description |
|---|---|---|
| openapi | string | REQUIRED. This stringMUST be theversion number of the OpenAPI Specification that the OpenAPI document uses. Theopenapi fieldSHOULD be used by tooling to interpret the OpenAPI document. This isnot related to theinfo.version string, which describes the OpenAPI document’s version. |
| $self | string | This stringMUST be in the form of a URI reference as defined by [RFC3986]Section 4.1. The$self field provides the self-assigned URI of this document, which also serves as its base URI in accordance with [RFC3986]Section 5.1.1. ImplementationsMUST support identifying the targets ofAPI description URIs using the URI defined by this field when it is present. SeeEstablishing the Base URI for the base URI behavior when$self is absent or relative, and seeAppendix F for examples of using$self to resolve references. |
| info | Info Object | REQUIRED. Provides metadata about the API. The metadataMAY be used by tooling as required. |
| jsonSchemaDialect | string | The default value for the$schema keyword withinSchema Objects contained within this OAS document. ThisMUST be in the form of a URI. |
| servers | [Server Object] | An array of Server Objects, which provide connectivity information to a target server. If theservers field is not provided, or is an empty array, the default value would be an array consisting of a singleServer Object with aurl value of/. |
| paths | Paths Object | The available paths and operations for the API. |
| webhooks | Map[string,Path Item Object] | The incoming webhooks thatMAY be received as part of this API and that the API consumerMAY choose to implement. Closely related to thecallbacks feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. Anexample is available. |
| components | Components Object | An element to hold various Objects for the OpenAPI Description. |
| security | [Security Requirement Object] | 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. The list can be incomplete, up to being empty or absent. To make security explicitly optional, an empty security requirement ({}) can be included in the array. |
| tags | [Tag Object] | A list of tags used by the OpenAPI Description 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 theOperation Object must be declared. The tags that are not declaredMAY be organized randomly or based on the tools’ logic. Each tag name in the listMUST be unique. |
| externalDocs | External Documentation Object | Additional external documentation. |
This objectMAY be extended withSpecification Extensions.
To ensure interoperability, referencesMUST use the target document’s$self URI if the$self field is present.ImplementationsMAY choose to support referencing by other URIs such as the retrieval URI even when$self is present, however this behavior is not interoperable and relying on it isNOT RECOMMENDED.
AnOpenAPI Description (OAD) formally describes the surface of an API and its semantics.An OADMAY be made up of a single document, or be distributed across multiple documents that are connected by various fields usingURI references andimplicit connections.
In order for parsing behavior to be well-defined, all documents in an OADMUST have either an OpenAPI Object or a Schema Object at the root, andMUST be parsed as complete documents, as described in the next section.
Documents with a different Object at the root, or that mix OAD content with other content,MAY be supported, but will have implementation-defined or, potentially, undefined behavior as described inAppendix G: Parsing and Resolution Guidance.Throughout this specification, documents are assumed to have either an OpenAPI Object or Schema Object at the root unless otherwise specified.
In a multi-document OAD, the document containing the OpenAPI Object where parsing begins is known as that OAD’sentry document.It isRECOMMENDED that the entry document of an OAD be namedopenapi.json oropenapi.yaml.
An OpenAPI ObjectMAY be embedded in another format, called theembedding format, just as JSON Schema is embedded in the OAS in the form of Schema Objects.It is the responsibility of an embedding format to define how to parse embedded content, and OAS implementations that do not document support for an embedding format cannot be expected to parse embedded OAS content correctly.
Each document in an OADMUST be fully parsed in order to locate possible reference targets.This includes the parsing requirements ofJSON Schema Specification Draft 2020-12, with appropriate modifications regarding base URIs as specified inRelative References In URIs.Reference targets are defined by fields including the OpenAPI Object’s$self field and theSchema Object’s$id,$anchor, and$dynamicAnchor keywords.
ImplementationsMUST NOT treat a reference as unresolvable before completely parsing all documents provided to the implementation as possible parts of the OAD.
If only the referenced part of the document is parsed when resolving a reference, the resulting behavior can be implementation-defined or undefined; seeWarnings Regarding Fragmentary Parsing inAppendix G for details.
URIs used as references within an OpenAPI Description, or to external documentation or other supplementary information such as a license, are resolved asidentifiers, and described by this specification asURIs, in contrast withAPI URLs.Note that some URI fields are namedurl for historical reasons, but the descriptive text for those fields uses the correct “URI” terminology.
As noted underParsing Documents, several fields can be used to associate an OpenAPI document or a Schema Object with a URI, which might not match the document’s or schema’s location.This allows the same references to be used in different deployment environments, including local filesystems or networks restricted by security policies or connectivity limitations.
Unless specified otherwise, all fields that are URIsMAY be relative references as defined by [RFC3986]Section 4.2.
Relative URI references are resolved using the appropriate base URI, whichMUST be determined in accordance with [RFC3986]Section 5.1.1 – 5.1.4 and, for Schema objects,JSON Schema draft 2020-12 Section 8.2, as illustrated by the examples inAppendix F: Examples of Base URI Determination and Reference Resolution.
If$self is a relative URI reference, it is resolved against the next possible base URI source ([RFC3986]Section 5.1.2 – 5.1.4) before being used for the resolution of other relative URI references.
The most common base URI source that is used in the event of a missing or relative$self (in theOpenAPI Object) and (forSchema Object)$id is the retrieval URI.ImplementationsMAY support document retrieval, although see theSecurity Considerations sections for additional guidance.Even if retrieval is supported, it may be impossible due to network configuration or server unavailability (including the server hosting an older version while a new version is in development), or undesirable due to performance impacts.Therefore, all implementationsSHOULD allow users to provide documents with their intended retrieval URIs so that references can be resolved as if retrievals were performed.
If a URI contains a fragment identifier, then the fragment should be resolved per the fragment resolution mechanism of the referenced document. If the representation of the referenced document is JSON or YAML, then the fragment identifierSHOULD be interpreted as a JSON Pointer as per [RFC6901].
Relative references in CommonMark hyperlinks are resolved in their rendered context, which might differ from the context of the API description.
Several features of this specification require resolution of non-URI-based connections to some other part of the OpenAPI Description (OAD).
These connections are unambiguously resolved in single-document OADs, but the resolution process in multi-document OADs isimplementation-defined, within the constraints described in this section.In some cases, an unambiguous URI-based alternative is available, and OAD authors areRECOMMENDED to use the alternative to maximize interoperability.
For resolvingComponents Object andTag Object names from a referenced (non-entry) document, it isRECOMMENDED that tools resolve from the entry document, rather than the current document.For resolving anOperation Object based on anoperationId, it isRECOMMENDED to consider all Operation Objects from all parsed documents.
Note that no aspect of implicit connection resolution changes howURIs are resolved, or restricts their possible targets.
SeeAppendix G: Parsing and Resolution Guidance for more details, including a list of Objects and fields using implicit connections.
The object provides metadata about the API.The metadataMAY be used by the clients if needed, andMAY be presented in editing or documentation generation tools for convenience.
| Field Name | Type | Description |
|---|---|---|
| title | string | REQUIRED. The title of the API. |
| summary | string | A short summary of the API. |
| description | string | A description of the API. [CommonMark] syntaxMAY be used for rich text representation. |
| termsOfService | string | A URI for the Terms of Service for the API. ThisMUST be in the form of a URI. |
| contact | Contact Object | The contact information for the exposed API. |
| license | License Object | The license information for the exposed API. |
| version | string | REQUIRED. The version of the OpenAPI document (which is distinct from theOpenAPI Specification version or the version of the API being described or the version of the OpenAPI Description). |
This objectMAY be extended withSpecification Extensions.
title:ExamplePetStoreAppsummary:Apetstoremanager.description:Thisisanexampleserverforapetstore.termsOfService:https://example.com/terms/contact:name:APISupporturl:https://www.example.com/supportemail:support@example.comlicense:name:Apache2.0url:https://www.apache.org/licenses/LICENSE-2.0.htmlversion:1.0.1Contact information for the exposed API.
| Field Name | Type | Description |
|---|---|---|
| name | string | The identifying name of the contact person/organization. |
| url | string | The URI for the contact information. ThisMUST be in the form of a URI. |
string | The email address of the contact person/organization. ThisMUST be in the form of an email address. |
This objectMAY be extended withSpecification Extensions.
name:APISupporturl:https://www.example.com/supportemail:support@example.comLicense information for the exposed API.
| Field Name | Type | Description |
|---|---|---|
| name | string | REQUIRED. The license name used for the API. |
| identifier | string | An [SPDX-Licenses] expression for the API. Theidentifier field is mutually exclusive of theurl field. |
| url | string | A URI for the license used for the API. ThisMUST be in the form of a URI. Theurl field is mutually exclusive of theidentifier field. |
This objectMAY be extended withSpecification Extensions.
name:Apache2.0identifier:Apache-2.0An object representing a Server.
| Field Name | Type | Description |
|---|---|---|
| url | string | REQUIRED. A URL to the target host. This URL supports Server Variables andMAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served. Query and fragmentMUST NOT be part of this URL. Variable substitutions will be made when a variable is named in{braces}. |
| description | string | An optional string describing the host designated by the URL. [CommonMark] syntaxMAY be used for rich text representation. |
| name | string | An optional unique string to refer to the host designated by the URL. |
| variables | Map[string,Server Variable Object] | A map between a variable name and its value. The value is used for substitution in the server’s URL template. |
This objectMAY be extended withSpecification Extensions.
API endpoints are by definition accessed as locations, and are described by this specification asURLs.
Unless specified otherwise, all fields that are URLsMAY be relative references as defined by [RFC3986]Section 4.2.
Because the API is a distinct entity from the OpenAPI document, RFC3986’s base URI rules for the OpenAPI document do not apply.Unless specified otherwise, relative references are resolved using the URLs defined in theServer Object as a base URL. Note that these themselvesMAY be relative to the referring document.
Assume a retrieval URI ofhttps://device1.example.com for the following OpenAPI document:
openapi:3.2.0$self:https://apidescriptions.example.com/fooinfo:title:ExampleAPIversion:1.0servers:-url:.description:TheproductionAPIonthisdevice-url:./testdescription:ThetestAPIonthisdeviceFor API URLs the$self field, which identifies the OpenAPI document, is ignored and the retrieval URI is used instead. This produces a normalized production URL ofhttps://device1.example.com, and a normalized test URL ofhttps://device1.example.com/test.
A single server would be described as:
url:https://development.gigantic-server.com/v1description:Developmentservername:devThe following shows how multiple servers can be described, for example, at the OpenAPI Object’sservers:
servers:-url:https://development.gigantic-server.com/v1description:Developmentservername:dev-url:https://staging.gigantic-server.com/v1description:Stagingservername:staging-url:https://api.gigantic-server.com/v1description:Productionservername:prodThe following shows how variables can be used for a server configuration:
servers:-url:https://{username}.gigantic-server.com:{port}/{basePath}description:TheproductionAPIservername:prodvariables:username:# note! no enum here means it is an open valuedefault:demodescription:Auser-specificsubdomain.Use`demo`forafreesandboxenvironment.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:v2An object representing a Server Variable for server URL template substitution.
The server URL templating is defined by the following [ABNF] syntax.
server-url-template=1*( literals / server-variable )server-variable="{" server-variable-name"}"server-variable-name=1*(%x00-7A /%x7C /%x7E-10FFFF ); every Unicode character except { and }literals=1*(%x21 /%x23-24 /%x26-3B /%x3D /%x3F-5B /%x5D /%x5F /%x61-7A /%x7E / ucschar / iprivate / pct-encoded); any Unicode character except: CTL, SP,; DQUOTE, "%" (aside from pct-encoded),; "<", ">", "\", "^", "`", "{", "|", "}"pct-encoded="%"HEXDIGHEXDIGucschar=%xA0-D7FF /%xF900-FDCF /%xFDF0-FFEF /%x10000-1FFFD /%x20000-2FFFD /%x30000-3FFFD /%x40000-4FFFD /%x50000-5FFFD /%x60000-6FFFD /%x70000-7FFFD /%x80000-8FFFD /%x90000-9FFFD /%xA0000-AFFFD /%xB0000-BFFFD /%xC0000-CFFFD /%xD0000-DFFFD /%xE1000-EFFFDiprivate=%xE000-F8FF /%xF0000-FFFFD /%x100000-10FFFDHere,literals,pct-encoded,ucschar andiprivate definitions are taken from [RFC6570], incorporating the corrections specified inErrata 6937 forliterals.
Each server variableMUST NOT appear more than once in the URL template.
See thePaths Object for guidance on constructing full request URLs.
| Field Name | Type | Description |
|---|---|---|
| enum | [string] | An enumeration of string values to be used if the substitution options are from a limited set. The arrayMUST NOT be empty. |
| default | string | REQUIRED. The default value to use for substitution, whichSHALL be sent if an alternate value isnot supplied. If theenum is defined, the valueMUST exist in the enum’s values. Note that this behavior is different from theSchema Object’sdefault keyword, which documents the receiver’s behavior rather than inserting the value into the data. |
| description | string | An optional description for the server variable. [CommonMark] syntaxMAY be used for rich text representation. |
This objectMAY be extended withSpecification Extensions.
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 outside the Components Object.
| Field Name | Type | Description |
|---|---|---|
| schemas | Map[string,Schema Object] | An object to hold reusableSchema Objects. |
| responses | Map[string,Response Object |Reference Object] | An object to hold reusableResponse Objects. |
| parameters | Map[string,Parameter Object |Reference Object] | An object to hold reusableParameter Objects. |
| examples | Map[string,Example Object |Reference Object] | An object to hold reusableExample Objects. |
| requestBodies | Map[string,Request Body Object |Reference Object] | An object to hold reusableRequest Body Objects. |
| headers | Map[string,Header Object |Reference Object] | An object to hold reusableHeader Objects. |
| securitySchemes | Map[string,Security Scheme Object |Reference Object] | An object to hold reusableSecurity Scheme Objects. |
| links | Map[string,Link Object |Reference Object] | An object to hold reusableLink Objects. |
| callbacks | Map[string,Callback Object |Reference Object] | An object to hold reusableCallback Objects. |
| pathItems | Map[string,Path Item Object] | An object to hold reusablePath Item Objects. |
| mediaTypes | Map[string,Media Type Object |Reference Object] | An object to hold reusableMedia Type Objects. |
This objectMAY be extended withSpecification Extensions.
All the fixed fields declared above are objects thatMUST use keys that match the regular expression:^[a-zA-Z0-9\.\-_]+$.
Field Name Examples:
UserUser_1User_Nameuser-namemy.org.Usercomponents:schemas:GeneralError:type:objectproperties:code:type:integerformat:int32message:type:stringCategory:type:objectproperties:id:type:integerformat:int64name:type:stringTag:type:objectproperties:id:type:integerformat:int64name:type:stringparameters:skipParam:name:skipin:querydescription:numberofitemstoskiprequired:trueschema:type:integerformat:int32limitParam:name:limitin:querydescription:maxrecordstoreturnrequired:trueschema:type:integerformat:int32responses:NotFound:description:Entitynotfound.IllegalInput:description:Illegalinputforoperation.GeneralError:description:GeneralErrorcontent:application/json:schema:$ref:'#/components/schemas/GeneralError'securitySchemes:api_key:type:apiKeyname:api-keyin:headerpetstore_auth:type:oauth2flows:implicit:authorizationUrl:https://example.org/api/oauth/dialogscopes:write:pets:modifypetsinyouraccountread:pets:readyourpetsHolds the relative paths to the individual endpoints and their operations.The path is appended to the URL from theServer Object in order to construct the full URL. The Paths ObjectMAY be empty, due toAccess Control List (ACL) constraints.
| Field Pattern | Type | Description |
|---|---|---|
| /{path} | Path Item Object | A relative path to an individual endpoint. The field nameMUST begin with a forward slash (/). The URL from theServer Object’surl field, resolved and with template variables substituted, has the pathappended (no relative URL resolution) to it in order to construct the full URL.Path templating is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated namesMUST NOT exist as they are identical. In case of ambiguous matching, it’s up to the tooling to decide which one to use. |
This objectMAY be extended withSpecification Extensions.
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 pathMUST correspond to a path parameter that is included in thePath Item itself and/or in each of the Path Item’sOperations. An exception is if the path item is empty, for example due to ACL constraints, matching path parameters are not required.
The value for these path parametersMUST NOT contain any unescaped “generic syntax” characters described by [RFC3986]Section 3: forward slashes (/), question marks (?), or hashes (#).SeeURL Percent-Encoding for additional guidance on escaping characters.
The path templating is defined by the following [ABNF] syntax
path-template="/" *( path-segment"/" ) [ path-segment ]path-segment=1*( path-literal / template-expression )path-literal=1*pchartemplate-expression="{" template-expression-param-name"}"template-expression-param-name=1*(%x00-7A /%x7C /%x7E-10FFFF ); every Unicode character except { and }pchar= unreserved / pct-encoded / sub-delims /":" /"@"unreserved=ALPHA /DIGIT /"-" /"." /"_" /"~"pct-encoded="%"HEXDIGHEXDIGsub-delims="!" /"$" /"&" /"'" /"(" /")" /"*" /"+" /"," /";" /"="Here,pchar,unreserved,pct-encoded andsub-delims definitions are taken from [RFC3986]. Thepath-template is directly derived fromRFC 3986, section 3.3.
Each template expressionMUST NOT appear more than once in a single path template.
See alsoAppendix C: Using RFC6570-Based Serialization for additional guidance.
Assuming the following paths, the concrete definition,/pets/mine, will be matched first if used:
/pets/{petId} /pets/mineThe following paths are considered identical and invalid:
/pets/{petId} /pets/{name}The following may lead to ambiguous resolution:
/{entity}/me /books/{id}/pets:get:description:Returnsallpetsfromthesystemthattheuserhasaccesstoresponses:'200':description:Alistofpets.content:application/json:schema:type:arrayitems:$ref:'#/components/schemas/pet'Describes the operations available on a single path.A Path ItemMAY be empty, due toACL constraints.The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.
| Field Name | Type | Description |
|---|---|---|
| $ref | string | Allows for a referenced definition of this path item. The valueMUST be in the form of a URI, and the referenced structureMUST be in the form of aPath Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolvingRelative References. Note: The behavior of $ref with adjacent properties is likely to change in future versions of this specification to bring it into closer alignment with the behavior of theReference Object. |
| summary | string | An optional string summary, intended to apply to all operations in this path. |
| description | string | An optional string description, intended to apply to all operations in this path. [CommonMark] syntaxMAY be used for rich text representation. |
| get | Operation Object | A definition of a GET operation on this path. |
| put | Operation Object | A definition of a PUT operation on this path. |
| post | Operation Object | A definition of a POST operation on this path. |
| delete | Operation Object | A definition of a DELETE operation on this path. |
| options | Operation Object | A definition of a OPTIONS operation on this path. |
| head | Operation Object | A definition of a HEAD operation on this path. |
| patch | Operation Object | A definition of a PATCH operation on this path. |
| trace | Operation Object | A definition of a TRACE operation on this path. |
| query | Operation Object | A definition of a QUERY operation, as defined in the most recent IETF draft (draft-ietf-httpbis-safe-method-w-body-08 as of this writing) or its RFC successor, on this path. |
| additionalOperations | Map[string,Operation Object] | A map of additional operations on this path. The map key is the HTTP method with the same capitalization that is to be sent in the request. This mapMUST NOT contain any entry for the methods that can be defined by other fixed fields with Operation Object values (e.g. noPOST entry, as thepost field is used for this method). |
| servers | [Server Object] | An alternativeservers array to service all operations in this path. If aservers array is specified at theOpenAPI Object level, it will be overridden by this value. |
| parameters | [Parameter Object |Reference Object] | 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 listMUST NOT include duplicated parameters. A unique parameter is defined by a combination of aname andlocation. The list can use theReference Object to link to parameters that are defined in theOpenAPI Object’scomponents.parameters. |
This objectMAY be extended withSpecification Extensions.
get:description:ReturnspetsbasedonIDsummary:FindpetsbyIDoperationId:getPetsByIdresponses:'200':description:petresponsecontent:'*/*':schema:type:arrayitems:$ref:'#/components/schemas/Pet'default:description:errorpayloadcontent:text/html:schema:$ref:'#/components/schemas/ErrorModel'parameters:-name:idin:pathdescription:IDofpettouserequired:trueschema:type:arrayitems:type:stringstyle:simpleadditionalOperations:COPY:description:CopiespetinformationbasedonIDsummary:CopiespetsbyIDoperationId:copyPetsByIdresponses:'200':description:petresponsecontent:'*/*':schema:type:arrayitems:$ref:'#/components/schemas/Pet'default:description:errorpayloadcontent:text/html:schema:$ref:'#/components/schemas/ErrorModel'Describes a single API operation on a path.
| Field Name | Type | Description |
|---|---|---|
| tags | [string] | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. |
| summary | string | A short summary of what the operation does. |
| description | string | A verbose explanation of the operation behavior. [CommonMark] syntaxMAY be used for rich text representation. |
| externalDocs | External Documentation Object | Additional external documentation for this operation. |
| operationId | string | Unique string used to identify the operation. The idMUST be unique among all operations described in the API. The operationId value iscase-sensitive. Tools and librariesMAY use the operationId to uniquely identify an operation, therefore, it isRECOMMENDED to follow common programming naming conventions. |
| parameters | [Parameter Object |Reference Object] | A list of parameters that are applicable for this operation. If a parameter is already defined at thePath Item, the new definition will override it but can never remove it. The listMUST NOT include duplicated parameters. A unique parameter is defined by a combination of aname andlocation. The list can use theReference Object to link to parameters that are defined in theOpenAPI Object’scomponents.parameters. |
| requestBody | Request Body Object |Reference Object | The request body applicable for this operation. TherequestBody is fully supported in HTTP methods where the HTTP specification [RFC9110]Section 9.3 has explicitly defined semantics for request bodies. In other cases where the HTTP spec discourages message content (such asGET andDELETE),requestBody is permitted but does not have well-defined semantics andSHOULD be avoided if possible. |
| responses | Responses Object | The list of possible responses as they are returned from executing this operation. |
| callbacks | Map[string,Callback Object |Reference Object] | 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 aCallback Object that describes a request that may be initiated by the API provider and the expected responses. |
| deprecated | boolean | Declares this operation to be deprecated. ConsumersSHOULD refrain from usage of the declared operation. Default value isfalse. |
| security | [Security Requirement Object] | 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 ({}) can be included in the array. This definition overrides any declared top-levelsecurity. To remove a top-level security declaration, an empty array can be used. |
| servers | [Server Object] | An alternativeservers array to service this operation. If aservers array is specified at thePath Item Object orOpenAPI Object level, it will be overridden by this value. |
This objectMAY be extended withSpecification Extensions.
tags:-petsummary:UpdatesapetinthestorewithformdataoperationId:updatePetWithFormparameters:-name:petIdin:pathdescription:IDofpetthatneedstobeupdatedrequired:trueschema:type:stringrequestBody:content:application/x-www-form-urlencoded:schema:type:objectproperties:name:description:Updatednameofthepettype:stringstatus:description:Updatedstatusofthepettype:stringrequired:-statusresponses:'200':description:Petupdated.content:application/json: {}application/xml: {}'405':description:MethodNotAllowedcontent:application/json: {}application/xml: {}security:-petstore_auth:-write:pets-read:petsAllows referencing an external resource for extended documentation.
| Field Name | Type | Description |
|---|---|---|
| description | string | A description of the target documentation. [CommonMark] syntaxMAY be used for rich text representation. |
| url | string | REQUIRED. The URI for the target documentation. ThisMUST be in the form of a URI. |
This objectMAY be extended withSpecification Extensions.
description:Findmoreinfohereurl:https://example.comDescribes a single operation parameter.
A unique parameter is defined by a combination of aname andlocation.
SeeAppendix E for a detailed examination of percent-encoding concerns, including interactions with theapplication/x-www-form-urlencoded query string format.
There are five possible parameter locations specified by thein field:
/items/{itemId}, the path parameter isitemId./items?id=###, the query parameter isid;MUST NOT appear in the same operation (or in the operation’s path-item) as anin: "querystring" parameter.content field, most often with media typeapplication/x-www-form-urlencoded usingEncoding Objects in the same way as with request bodies of that media type;MUST NOT appear more than once, andMUST NOT appear in the same operation (or in the operation’s path-item) as anyin: "query" parameters.The rules for serialization of the parameter are specified in one of two ways.Parameter ObjectsMUST include either acontent field or aschema field, but not both.SeeAppendix B for a discussion of converting values of various types to string representations.
These fieldsMAY be used with eithercontent orschema.
Theexample andexamples fields are mutually exclusive; seeWorking with Examples for guidance on validation requirements.
| Field Name | Type | Description |
|---|---|---|
| name | string | REQUIRED. The name of the parameter. Parameter names arecase-sensitive.
|
| in | string | REQUIRED. The location of the parameter. Possible values are"query","querystring","header","path" or"cookie". |
| description | string | A brief description of the parameter. This could contain examples of use. [CommonMark] syntaxMAY be used for rich text representation. |
| required | boolean | Determines whether this parameter is mandatory. If theparameter location is"path", this field isREQUIRED and its valueMUST betrue. Otherwise, the fieldMAY be included and its default value isfalse. |
| deprecated | boolean | Specifies that a parameter is deprecated andSHOULD be transitioned out of usage. Default value isfalse. |
| allowEmptyValue | boolean | Iftrue, clientsMAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the serverSHOULD interpret as the parameter being unused. Default value isfalse. Ifstyle is used, and ifbehavior isn/a (cannot be serialized), the value ofallowEmptyValueSHALL be ignored. Interactions between this field and the parameter’sSchema Object are implementation-defined. This field is valid only forquery parameters.Deprecated: Use of this field isNOT RECOMMENDED, and it is likely to be removed in a later revision. |
| example | Any | Example of the parameter’s potential value; seeWorking With Examples. |
| examples | Map[string,Example Object |Reference Object] | Examples of the parameter’s potential value; seeWorking With Examples. |
This objectMAY be extended withSpecification Extensions.
Note that while"Cookie" as aname is not forbidden ifin is"header", the effect of defining a cookie parameter that way is undefined; usein: "cookie" instead.
For simpler scenarios, aschema andstyle can describe the structure and syntax of the parameter.
These fieldsMUST NOT be used within: "querystring".
Care is needed for parameters withschema that havein: "header" orin: "cookie", style: "cookie":
In these cases, implementationsMUST pass values through unchanged rather than attempting to quote or escape them, as the quoting rules for headers and escaping conventions for cookies vary too widely to be performed automatically; seeAppendix D for guidance on quoting and escaping.
| Field Name | Type | Description |
|---|---|---|
| style | string | Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value ofin): for"query" -"form"; for"path" -"simple"; for"header" -"simple"; for"cookie" -"form" (for compatibility reasons; note thatstyle: "cookie"SHOULD be used within: "cookie"; seeAppendix D for details). |
| explode | boolean | When this is true, parameter values of typearray orobject generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters, or whenstyle is"deepObject", this field has no effect. Whenstyle is"form" or"cookie", the default value istrue. For all other styles, the default value isfalse. |
| allowReserved | boolean | When this is true, parameter values are serialized using reserved expansion, as defined by [RFC6570]Section 3.2.3, which allowsRFC3986’s reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including% outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed by the rules of thein destination or media type, or arenot allowed in the path by this specification; seeURL Percent-Encoding for details. The default value isfalse. This field only applies toin andstyle values that automatically percent-encode. |
| schema | Schema Object | The schema defining the type used for the parameter. |
See alsoAppendix C: Using RFC6570-Based Serialization for additional guidance.
For more complex scenarios, thecontent field can define the media type and schema of the parameter, as well as give examples of its use.
For use within: "querystring" andapplication/x-www-form-urlencoded, seeEncoding thex-www-form-urlencoded Media Type.
| Field Name | Type | Description |
|---|---|---|
| content | Map[string,Media Type Object |Reference Object] | A map containing the representations for the parameter. The key is the media type and the value describes it. The mapMUST only contain one entry. |
In order to support common ways of serializing simple parameters, a set ofstyle values are defined. Combinations not represented in this table are not permitted.
style | type | in | Comments |
|---|---|---|---|
matrix | primitive,array,object | path | Path-style parameters defined by [RFC6570]Section 3.2.7 |
label | primitive,array,object | path | Label style parameters defined by [RFC6570]Section 3.2.5 |
simple | primitive,array,object | path,header | Simple style parameters defined by [RFC6570]Section 3.2.2. This option replacescollectionFormat with acsv value from OpenAPI 2.0. |
form | primitive,array,object | query,cookie | Form style parameters defined by [RFC6570]Section 3.2.8. This option replacescollectionFormat with acsv (whenexplode is false) ormulti (whenexplode is true) value from OpenAPI 2.0. |
spaceDelimited | array,object | query | Space separated array values or object properties and values. This option replacescollectionFormat equal tossv from OpenAPI 2.0. |
pipeDelimited | array,object | query | Pipe separated array values or object properties and values. This option replacescollectionFormat equal topipes from OpenAPI 2.0. |
deepObject | object | query | Allows objects with scalar properties to be represented using form parameters. The representation of array or object properties is not defined (but seeExtending Support for Querystring Formats for alternatives). |
cookie | primitive,array,object | cookie | Analogous toform, but following [RFC6265]Cookie syntax rules, meaning that name-value pairs are separated by a semicolon followed by a single space (e.g.n1=v1; n2=v2), and no percent-encoding or other escaping is applied; data values that require any sort of escapingMUST be provided in escaped form. |
All API URLsMUST successfully parse and percent-decode using [RFC3986] rules.
Content in theapplication/x-www-form-urlencoded format, including query strings produced byParameter Objects within: "query",MUST also successfully parse and percent-decode using [WHATWG-URL] rules, including treating non-percent-encoded+ as an escaped space character.
These requirements are specified in terms of percent-decoding rules, which are consistently tolerant across different versions of the various standards that apply to URIs.
Percent-encoding is performed in several places:
When percent-encoding, the safest approach is to percent-encode all characters not in RFC3986’s “unreserved” set, and forform-urlencoded to also percent-encode the tilde character (~) to align with historical requirements that are traced back to [RFC1738], the URI RFC at the timeform-urlencoded was created.This approach is used in examples in this specification.
Forform-urlencoded, while the encoding algorithm given by [WHATWG-URL] requires escaping the space character as+, percent-encoding it as%20 also meets the above requirements.Examples in this specification will prefer%20 when using RFC6570’s default (non-reserved) form-style expansion, and+ otherwise.
Reserved charactersMUST NOT be percent-encoded when being used for reserved purposes such as&=+ forform-urlencoded or, for delimiting non-exploded array and object values in RFC6570 expansions.The result of inserting non-percent-encoded delimiters into data using manual percent-encoding, including via RFC6570’s reserved expansion rules, is undefined and will likely prevent implementations from parsing the results back into the correct data structures.In some cases, such as inserting/ into path parameter values, doing so isexplicitly forbidden by this specification.
See also:
The rules in this section apply to both the Parameter andHeader Objects, both of which use the same mechanisms.
When showing serialized examples, such as with theExample Object’sserializedValue orexternalValue fields, in most cases the value to show is just the value, with all relevant percent-encoding or other encoding/escaping applied, and also including any delimiters produced by thestyle andexplode configuration.
In cases where the name is an inherent part of constructing the serialization, such as thename=value pairs produced bystyle: "form" or the combination ofstyle: "simple", explode: true, the name and any delimiter between the name and valueMUST be included.
Thematrix andlabel styles produce a leading delimiter which is always a valid part of the serialization andMUST be included.The RFC6570 operators corresponding tostyle: "form" produce a leading delimiter of either? or& depending on the exact syntax used.As the suitability of either delimiter depends on where in the query string the parameter occurs, as well as whether it is in a URI or inapplication/x-www-form-urlencoded content, this leading delimiterMUST NOT be included in examples of individual parameters or media type documents.Forin: "cookie", style: "form", neither the& nor? delimiters are ever correct; seeAppendix D: Serializing Headers and Cookies for more details.
For headers, the header nameMUST NOT be included as part of the serialization, as it is never part of the RFC6570-derived result.However, names produced bystyle: "simple", explode: "true" are included as they appear within the header value, not as separate headers.See theHeader Object for special rules for showing examples of theSet-Cookie response header, which violates the normal rules for multiple header values.
Assume a parameter namedcolor has one of the following values, where the value to the right of the-> is what would be shown in thedataValue field of an Example Object:
string ->"blue" array -> ["blue","black","brown"] object -> {"R":100,"G":200,"B":150 }The following table shows serialized examples, as would be shown with theserializedValue field of an Example Object, of the different serializations for each value.
allowEmptyValue field.undefined column replaces theempty column in previous versions of this specification in order to better align with [RFC6570]Section 2.3 terminology, which describes certain values including but not limited tonull as “undefined” values with special handling; notably, the empty string isnot undefined.form and the non-RFC6570 query string stylesspaceDelimited,pipeDelimited, anddeepObject, seeAppendix C for more information on constructing query strings from multiple parameters, andAppendix D for warnings regardingform andcookie parameters.| (%7C),[ (%5B), and] (%5D) seem to work in some environments despite not being compliant.style | explode | undefined | string | array | object |
|---|---|---|---|---|---|
| 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 |
| simple | false | empty | blue | blue,black,brown | R,100,G,200,B,150 |
| simple | true | empty | 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 |
| spaceDelimited | false | n/a | n/a | color=blue%20black%20brown | color=R%20100%20G%20200%20B%20150 |
| spaceDelimited | true | n/a | n/a | n/a | n/a |
| pipeDelimited | false | n/a | n/a | color=blue%7Cblack%7Cbrown | color=R%7C100%7CG%7C200%7CB%7C150 |
| pipeDelimited | true | n/a | n/a | n/a | n/a |
| deepObject | n/a | n/a | n/a | n/a | color%5BR%5D=100&color%5BG%5D=200&color%5BB%5D=150 |
| cookie | false | color= | color=blue | color=blue,black,brown | color=R,100,G,200,B,150 |
| cookie | true | color= | color=blue | color=blue; color=black; color=brown | R=100; G=200; B=150 |
Many frameworks define query string syntax for complex values, such as appending array indices to parameter names or indicating multiple levels of of nested objects, which go well beyond the capabilities of thedeepObject style.
As these are not standards, and often contradict each other, the OAS does not attempt to support them directly.Two avenues are available for supporting such formats within: "querystring":
content andtext/plain with a schema oftype: "string" and define the format outside of OpenAPI. While this requires more work to document and construct or parse the format, which is seen as a plain string from the OpenAPI perspective, it provides the easiest flexible optionA header parameter with an array of 64-bit integer numbers:
name:X-Tokenin:headerdescription:tokentobepassedasaheaderrequired:trueschema:type:arrayitems:type:integerformat:int64style:simpleexamples:Tokens:dataValue:-12345678-90099serializedValue:"12345678,90099"A cookie parameter with an exploded object (the default forstyle: "cookie"):
name:cookiein:cookiestyle:cookieschema:type:objectproperties:greeting:type:stringcode:type:integerminimum:0examples:Object:description:| Note that the comma (,) has been pre-percent-encoded to "%2C" in the data, as it is forbidden in cookie values. However, the exclamation point (!) is legal in cookies, so it can be left unencoded.dataValue:greeting:Hello%2Cworld!code:42serializedValue:"greeting=Hello%2C world!; code=42"A cookie parameter relying on the percent-encoding behavior of the defaultstyle: "form":
name:greetingin:cookieschema:type:stringexamples:Greeting:description:| Note that in this approach, RFC6570's percent-encoding process applies, so unsafe characters are not pre-percent-encoded. This results in all non-URL-safe characters, rather than just the one non-cookie-safe character, getting percent-encoded.dataValue:Hello,world!serializedValue:"greeting=Hello%2C%20world%21"A path parameter of a string value:
name:usernamein:pathdescription:usernametofetchrequired:trueschema:type:stringexamples:"Edsger Dijkstra":dataValue:edijkstraserializedValue:edijkstraDiṅnāga:dataValue:diṅnāgaserializedValue:di%E1%B9%85n%C4%81gaAl-Khwarizmi:dataValue:"الخوارزميّ"serializedValue:"%D8%A7%D9%84%D8%AE%D9%88%D8%A7%D8%B1%D8%B2%D9%85%D9%8A%D9%91"An optional query parameter of a string value, allowing multiple values by repeating the query parameter(Note that we use"%20" in place of" " (space) because that is how RFC6570 handles it; for guidance on using+ to represent the space character, seeAppendix E for more guidance on these escaping options):
name:thingin:queryrequired:falseschema:type:arrayitems:type:stringstyle:formexplode:trueexamples:ObjectList:dataValue:-onething-anotherthingserializedValue:"thing=one%20thing&thing=another%20thing"A free-form query parameter, allowing arbitrary parameters oftype: "integer":
in:queryname:freeFormschema:type:objectadditionalProperties:type:integerstyle:formexamples:Pagination:dataValue:page:4pageSize:50serializeValue:page=4&pageSize=50A complex parameter usingcontent to define serialization, with multiple levels and types of examples shown to make the example usage options clear — note thatdataValue is the same at both levels and does not need to be shown in both places in normal usage, butserializedValue is different:
in:queryname:coordinatescontent:application/json:schema:type:objectrequired:-lat-longproperties:lat:type:numberlong:type:numberexamples:dataValue:lat:10long:60serializedValue:'{"lat":10,"long":60}'examples:dataValue:lat:10long:60serializedValue:coordinates=%7B%22lat%22%3A10%2C%22long%22%3A60%7DA querystring parameter using regular form encoding, but managed with a Media Type Object.This shows spaces being handled per theapplication/x-www-form-urlencoded media type rules (encode as+) rather than the RFC6570 process (encode as%20); seeAppendix E for further guidance on this distinction.Examples are shown at both the media type and parameter level to emphasize that, sinceapplication/x-www-form-urlencoded is suitable for use in query strings by definition, no further encoding or escaping is applied to the serialized media type value:
in:querystringcontent:application/x-www-form-urlencoded:schema:type:objectproperties:foo:type:stringbar:type:booleanexamples:spacesAndPluses:description:Notehandlingofspacesand"+"permediatype.dataValue:foo:a+bbar:trueserializedValue:foo=a+%2B+b&bar=trueexamples:spacesAndPluses:description:| Note that no additional percent encoding is done, as this media type is URI query string-ready by definition.dataValue:foo:a+bbar:trueserializedValue:foo=a+%2B+b&bar=trueA querystring parameter that uses JSON for the entire string (not as a single query parameter value).ThedataValue field is shown at both levels to fully illustrate both ways of providing an example.As seen below, this is redundant and need not be done in practice:
in:querystringname:jsoncontent:application/json:schema:type:objectproperties:numbers:type:arrayitems:type:integerflag:type: [boolean,"null"]examples:TwoNoFlag:description:SerializewithminimizedwhitespacedataValue:numbers:-1-2flag:nullserializedValue:'{"numbers":[1,2],"flag":null}'examples:TwoNoFlag:dataValue:numbers:-1-2flag:nullserializedValue:"%7B%22numbers%22%3A%5B1%2C2%5D%2C%22flag%22%3Anull%7D"Assuming a path of/foo, a server ofhttps://example.com, the full URL incorporating the value fromserializedValue would be:
https://example.com/foo?%7B%22numbers%22%3A%5B1%2C2%5D%2C%22flag%22%3Anull%7DA querystring parameter that usesJSONPath.Note that in this example we not only do not repeatdataValue, but we use the shorthandexample because theapplication/jsonpath value is a string that, at the media type level, is serialized as-is:
in:querystringname:selectorcontent:application/jsonpath:schema:type:stringexample:$.a.b[1:1]examples:Selector:serializedValue:"%24.a.b%5B1%3A1%5D"As there is not, as of this writing, aregistered mapping between the JSON Schema data model and JSONPath, the details of the string’s allowed structure would need to be conveyed either in a human-readabledescription field, or through a mechanism outside of the OpenAPI Description, such as a JSON Schema for the data structure to be queried.
Assuming a path of/foo and a server ofhttps://example.com, the full URL incorporating the value fromserializedValue would be:
https://example.com/foo?%24.a.b%5B1%3A1%5DDescribes a single request body.
| Field Name | Type | Description |
|---|---|---|
| description | string | A brief description of the request body. This could contain examples of use. [CommonMark] syntaxMAY be used for rich text representation. |
| content | Map[string,Media Type Object |Reference Object] | REQUIRED. The content of the request body. The key is a media type ormedia type range and the value describes it. The mapSHOULD have at least one entry; if it does not, the behavior is implementation-defined. For requests that match multiple keys, only the most specific key is applicable. e.g."text/plain" overrides"text/*" |
| required | boolean | Determines if the request body is required in the request. Defaults tofalse. |
This objectMAY be extended withSpecification Extensions.
A request body with a referenced schema definition.
description:usertoaddtothesystemcontent:application/json:schema:$ref:'#/components/schemas/User'examples:user:summary:UserexampleexternalValue:https://foo.bar/examples/user-example.jsonapplication/xml:schema:$ref:'#/components/schemas/User'examples:user:summary:UserexampleinXMLexternalValue:https://foo.bar/examples/user-example.xmltext/plain:examples:user:summary:UserexampleinplaintextexternalValue:https://foo.bar/examples/user-example.txt'*/*':examples:user:summary:UserexampleinotherformatexternalValue:https://foo.bar/examples/user-example.whateverEach Media Type Object describes content structured in accordance with the media type identified by its key.Multiple Media Type Objects can be used to describe content that can appear in any of several different media types.
Whenexample orexamples are provided, the exampleSHOULD match the specified schema and be in the correct format as specified by the media type and its encoding.Theexample andexamples fields are mutually exclusive.SeeWorking With Examples for further guidance regarding the different ways of specifying examples, including non-JSON/YAML values.
| Field Name | Type | Description |
|---|---|---|
| schema | Schema Object | A schema describing the complete content of the request, response, parameter, or header. |
| itemSchema | Schema Object | A schema describing each item within asequential media type. |
| example | Any | Example of the media type; seeWorking With Examples. |
| examples | Map[string,Example Object |Reference Object] | Examples of the media type; seeWorking With Examples. |
| encoding | Map[string,Encoding Object] | A map between a property name and its encoding information, as defined underEncoding By Name. Theencoding fieldSHALL only apply when the media type ismultipart orapplication/x-www-form-urlencoded. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object. This fieldMUST NOT be present ifprefixEncoding oritemEncoding are present. |
| prefixEncoding | [Encoding Object] | An array of positional encoding information, as defined underEncoding By Position. TheprefixEncoding fieldSHALL only apply when the media type ismultipart. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object. This fieldMUST NOT be present ifencoding is present. |
| itemEncoding | Encoding Object | A single Encoding Object that provides encoding information for multiple array items, as defined underEncoding By Position. TheitemEncoding fieldSHALL only apply when the media type ismultipart. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object. This fieldMUST NOT be present ifencoding is present. |
This objectMAY be extended withSpecification Extensions.
Media types are publicly registered with theIANA media types registry, through process documented in [RFC6838].
APIs also sometimes define private media types such as GitHub’sapplication/vnd.github.v3+json, which are not registered, and other media types such asapplication/schema+json become widely used before an intended registration.
SeeParsing and Serializing under theSchema Object for guidance on using schemas with a variety of media types.
The OpenAPI Initiative maintains aMedia Type Registry summarizing media type support expected by this specification and providing an index to which sections address which media types.It also links to IANA registrations (where they exist) and to the most notable specification document(s) related to each media type.Any additional media types added to this registry as extensions or for later versions of this or other OpenAPI specificationsMAY be supported by implementations of this version of the OAS.
Theschema fieldMUST be applied to the complete content, as defined by the media type and the context (Request Body Object,Response Object,Parameter Object, orHeader Object.Because this requires loading the content into memory in its entirety, it poses a challenge for streamed content.Use cases where clients are intended to choose when to stop reading are particularly challenging as there is no well-defined end to the stream.
Within this specification, asequential media type is defined as any media type that consists of a repeating structure, without any sort of header, footer, envelope, or other metadata in addition to the sequence.
Some examples of sequential media types (including some that are not IANA-registered but are in common use) are:
application/jsonl application/x-ndjson application/json-seq application/geo+json-seq text/event-stream multipart/mixedIn the first three above, the repeating structure is anyJSON value.The fourth repeatsapplication/geo+json-structured values, whiletext/event-stream repeats a custom text format related to Server-Sent Events.The final media type listed above,multipart/mixed, provides an ordered list of documents of any media type, and is sometimes streamed.Note that whilemultipart formats technically allow a preamble and an epilogue, the RFC directs that they are to be ignored, making them effectively comments, and this specification does not model them.
ImplementationsMUST support mapping sequential media types into the JSON Schema data model by treating them as if the values were in an array in the same order.
SeeComplete vs Streaming Content for more information on handling sequential media types in a streaming context, including special considerations fortext/event-stream content.Formultipart types, see alsoEncoding By Position.
TheitemSchema field is provided to support streaming use cases for sequential media types, withitemEncoding as a corresponding encoding mechanism for streamingpositionalmultipart media types.
Unlikeschema, which is applied to the complete content (treated as an array as described in thesequential media types section),itemSchemaMUST be applied to each item in the stream independently, which supports processing each item as it is read from the stream.
Bothschema anditemSchemaMAY be used in the same Media Type Object.However, doing so is unlikely to have significant advantages over using theitems keyword within theschema field.
ThemaxLength keywordMAY be used to set an expected upper bound on the length of a streaming payload that consists of either string data, including encoded binary data, or unencoded binary data.For unencoded binary data, the length is the number of octets.For this use case,maxLengthMAY be implemented outside of regular JSON Schema evaluation as JSON Schema does not directly apply to binary data, and an encoded binary stream may be impractical to store in memory in its entirety.
Fortext/event-stream, implementationsMUST work with event data after it has been parsed according to thetext/event-stream specification, including all guidance on ignoring certain fields (including comments) and/or values, and on combining values split across multiple lines.
Field value typesMUST be handled as specified by thetext/event-stream specification (e.g. theretry field value is modeled as a JSON number that is expected to be of JSON Schematype: integer), and fields not given an explicit value typeMUST be handled as strings.
Some users oftext/event-stream use a format such as JSON for field values, particularly thedata field.Use JSON Schema’s keywords for working with thecontents of string-encoded data, particularlycontentMediaType andcontentSchema, to describe and validate such fields with more detail than string-related validation keywords such aspattern can support.Note thatcontentSchema isnot automatically validated by default (see also theNon-validating constraint keywords section of this specification).
The following Schema Object is a generic schema for thetext/event-stream media type as documented by the [HTML] specification as of the time of this writing:
type:objectrequired:-dataproperties:data:type:stringevent:type:stringid:type:stringretry:type:integerminimum:0These encoding fields define how to map eachEncoding Object to a specific value in the data.Each field has its own set of media types with which it can be used; for all other media types all three fieldsSHALL be ignored.
The behavior of theencoding field is designed to support web forms, and is therefore only defined for media types structured as name-value pairs that allow repeat values, most notablyapplication/x-www-form-urlencoded andmultipart/form-data.
To use theencoding field, each key under the fieldMUST exist as a property;encoding entries with no corresponding propertySHALL be ignored.Array propertiesMUST be handled by applying the given Encoding Object to produce one encoded value per array item, each with the samename, as is recommended by [RFC7578]Section 4.3 for supplying multiple values per form field.For all other value types for both top-level non-array properties and for values, including array values, within a top-level array, the Encoding ObjectMUST be applied to the entire value.The order of these name-value pairs in the target media type is implementation-defined.
Forapplication/x-www-form-urlencoded, the encoding keysMUST map to parameter names, with the values produced according to the rules of theEncoding Object.SeeEncoding thex-www-form-urlencoded Media Type for guidance and examples, both with and without theencoding field.
Formultipart, the encoding keysMUST map to thename parameter of theContent-Disposition: form-data header of each part, as is defined formultipart/form-data in [RFC7578].See [RFC7578]Section 5 for guidance regarding non-ASCII part names.
SeeEncodingmultipart Media Types for further guidance and examples, both with and without theencoding field.
Mostmultipart media types, includingmultipart/mixed which defines the underlying rules for parsing allmultipart types, do not have named parts.Data for these media types are modeled as an array, with one item per part, in order.
To use theprefixEncoding and/oritemEncoding fields, eitheritemSchema or an arrayschemaMUST be present.These fields are analogous to theprefixItems anditems JSON Schema keywords, withprefixEncoding (if present) providing an array of Encoding Objects that are each applied to the value at the same position in the data array, anditemEncoding applying its single Encoding Object to all remaining items in the array.As withprefixItems, it isnot an error if the instance array is shorter than theprefixEncoding array; the additional Encoding ObjectsSHALL be ignored.
TheitemEncoding field can also be used withitemSchema to support streamingmultipart content.
TheprefixEncoding field can be used with anymultipart content to require a fixed part order.This includesmultipart/form-data, for which the Encoding Object’sheaders fieldMUST be used to provide theContent-Disposition and part name, as no property names exist to provide the names automatically.
Prior versions of this specification advised using thename parameter of theContent-Disposition: form-data header of each part withmultipart media types other thanmultipart/form-data in order to work around the limitations of theencoding field.ImplementationsMAY choose to support this workaround, but as this usage is not common, implementations of non-form-datamultipart media types are unlikely to support it.
For form-related andmultipart media type examples, see theEncoding Object.
Note that since this example is written in YAML, the Example Object’svalue field can be formatted as YAML due to the trivial conversion to JSON.This avoids needing to embed JSON as a string.
application/json:schema:$ref:'#/components/schemas/Pet'examples:cat:summary:Anexampleofacatvalue:name:FluffypetType:Catcolor:Whitegender:malebreed:Persiandog:summary:Anexampleofadogwithacat'snamevalue:name:PumapetType:Dogcolor:Blackgender:Femalebreed:Mixedfrog:$ref:'#/components/examples/frog-example'Alternatively, since all JSON is valid YAML, the example value can use JSON syntax within a YAML document:
application/json:schema:$ref:'#/components/schemas/Pet'examples:cat:summary:Anexampleofacatvalue: {"name":"Fluffy","petType":"Cat","color":"White","gender":"male","breed":"Persian" }dog:summary:Anexampleofadogwithacat'snamevalue: {"name":"Puma","petType":"Dog","color":"Black","gender":"Female","breed":"Mixed" }frog:$ref:'#/components/examples/frog-example'For anysequential media type where the items in the sequence are JSON values, no conversion of each value is required.JSON Text Sequences ([RFC7464]application/json-seq and [RFC8091] the+json-seq structured suffix),JSON Lines (application/jsonl), andNDJSON (application/x-ndjson) are all in this category.Note that the media types for JSON Lines and NDJSON are not registered with the IANA, but are in common use.
The following example shows Media Type Objects for both streaming log entries and returning a fixed-length set in response to a query.This shows the relationship betweenschema anditemSchema, and when to use each even though theexamples field is the same either way.
components:schemas:LogEntry:type:objectproperties:timestamp:type:stringformat:date-timelevel:type:integerminimum:0message:type:stringLog:type:arrayitems:$ref:"#/components/schemas/LogEntry"maxItems:100examples:LogJSONSeq:summary:Logentriesinapplication/json-seq# JSON Text Sequences require an unprintable character# that cannot be escaped in a YAML string, and therefore# must be placed in an external document shown belowexternalValue:examples/log.json-seqLogJSONPerLine:summary:Logentriesinapplication/jsonlorapplication/x-ndjsondescription:JSONLandNDJSONareidenticalforthisexample# Note that the value must be written as a string with newlines,# as JSONL and NDJSON are not valid YAMLvalue:| {"timestamp": "1985-04-12T23:20:50.52Z", "level": 1, "message": "Hi!"} {"timestamp": "1985-04-12T23:20:51.37Z", "level": 1, "message": "Bye!"}responses:LogStream:description:| A stream of JSON-format log messages that can be read for as long as the application is running, and is available in any of the sequential JSON media types.content:application/json-seq:itemSchema:$ref:"#/components/schemas/LogEntry"examples:JSON-SEQ:$ref:"#/components/examples/LogJSONSeq"application/jsonl:itemSchema:$ref:"#/components/schemas/LogEntry"examples:JSONL:$ref:"#/components/examples/LogJSONPerLine"application/x-ndjson:itemSchema:$ref:"#/components/schemas/LogEntry"examples:NDJSON:$ref:"#/components/examples/LogJSONPerLine"LogExcerpt:description:| A response consisting of no more than 100 log records, generally as a result of a query of the historical log, available in any of the sequential JSON media types.content:application/json-seq:schema:$ref:"#/components/schemas/Log"examples:JSON-SEQ:$ref:"#/components/examples/LogJSONSeq"application/jsonl:schema:$ref:"#/components/schemas/Log"examples:JSONL:$ref:"#/components/examples/LogJSONPerLine"application/x-ndjson:schema:$ref:"#/components/schemas/Log"examples:NDJSON:$ref:"#/components/examples/LogJSONPerLine"Ourapplication/json-seq example has to be an external document because of the use of both newlines and of the unprintable Record Separator (0x1E) character, which cannot be escaped in YAML block literals:
0x1E{"timestamp":"1985-04-12T23:20:50.52Z","level":1,"message":"Hi!"}0x1E{"timestamp":"1985-04-12T23:20:51.37Z","level":1,"message":"Bye!"}For this example, assume that the generic event schema provided in theSpecial Considerations for Server-Sent Events section is available at#/components/schemas/Event:
description:Arequestbodytoaddastreamoftypeddata.required:truecontent:text/event-stream:itemSchema:$ref:"#/components/schemas/Event"required: [event]oneOf:-properties:event:const:addString-properties:event:const:addInt64data:$comment:| Since the `data` field is a string, we need a format to signal that it should be handled as a 64-bit integer.format:int64-properties:event:const:addJsondata:$comment:| These content fields indicate that the string value should be parsed and validated as a JSON document (since JSON is not a binary format, `contentEncoding` is not needed)contentMediaType:application/jsoncontentSchema:type:objectrequired: [foo]properties:foo:type:integerThe followingtext/event-stream document is an example of a valid request body for the above example:
event: addStringdata: This data is formatteddata: across two linesretry: 5event: addInt64data: 1234.5678unknownField: this is ignored: This is a commentevent: addJSONdata: {"foo": 42}To more clearly see how this stream is handled, the following is the equivalent JSON Lines document, which shows how the numeric and JSON data are handled as strings, and how unknown fields and comments are ignored and not passed to schema validation:
{"event":"addString","data":"This data is formatted\nacross two lines","retry":5}{"event":"addInt64","data":"1234.5678"}{"event":"addJSON","data":"{\"foo\": 42}"}In contrast to OpenAPI 2.0,file input/output content in OAS 3.x is described with the same semantics as any other schema type.
In contrast to OAS 3.0, theformat keyword has no effect on the content-encoding of the schema in OAS 3.1. Instead, JSON Schema’scontentEncoding andcontentMediaType keywords are used. SeeWorking With Binary Data for how to model various scenarios with these keywords, and how to migrate from the previousformat usage.
Examples:
Content transferred in binary (octet-stream)MAY omitschema:
# a PNG image as a binary file:content:image/png: {}# an arbitrary binary file:content:application/octet-stream: {}# arbitrary JSON without constraints beyond being syntactically valid:content:application/json: {}These examples apply to either input payloads of file uploads or response payloads.
ArequestBody for submitting a file in aPOST operation may look like the following example:
requestBody:content:application/octet-stream: {}In addition, specific media typesMAY be specified:
# multiple, specific media types may be specified:requestBody:content:# a binary file of type png or jpegimage/jpeg: {}image/png: {}To upload multiple files, amultipart media typeMUST be used as shown underExample: Multipart Form with Multiple Files.
A single encoding definition applied to a single value, with the mapping of Encoding Objects to values determined by theMedia Type Object as described underEncoding Usage and Restrictions.
SeeAppendix B for a discussion of converting values of various types to string representations.
SeeAppendix E for a detailed examination of percent-encoding concerns for form media types.
These fieldsMAY be used either with or without the RFC6570-style serialization fields defined in the next section below.
| Field Name | Type | Description |
|---|---|---|
| contentType | string | TheContent-Type for encoding a specific property. The value is a comma-separated list, each element of which is either a specific media type (e.g.image/png) or a wildcard media type (e.g.image/*). The default value depends on the type as shown in the table below. |
| headers | Map[string,Header Object |Reference Object] | A map allowing additional information to be provided as headers.Content-Type is described separately andSHALL be ignored in this section. This fieldSHALL be ignored if the media type is not amultipart. |
| encoding | Map[string,Encoding Object] | Applies nested Encoding Objects in the same manner as theMedia Type Object’sencoding field. |
| prefixEncoding | [Encoding Object] | Applies nested Encoding Objects in the same manner as theMedia Type Object’sprefixEncoding field. |
| itemEncoding | Encoding Object | Applies nested Encoding Objects in the same manner as theMedia Type Object’sitemEncoding field. |
This objectMAY be extended withSpecification Extensions.
The default values forcontentType are as follows, where ann/a in thecontentEncoding column means that the presence or value ofcontentEncoding is irrelevant.This table is based on the value to which the Encoding Object is being applied as defined underEncoding Usage and Restrictions.Note that in the case ofEncoding By Name, this value is the array item for properties of type"array", and the entire value for all other types.Therefore thearray row in this table applies only to array values inside of a top-level array when encoding by name.
type | contentEncoding | DefaultcontentType |
|---|---|---|
| absent | n/a | application/octet-stream |
string | present | application/octet-stream |
string | absent | text/plain |
number,integer, orboolean | n/a | text/plain |
object | n/a | application/json |
array | n/a | application/json |
Determining how to handle atype value ofnull depends on hownull values are being serialized.Ifnull values are entirely omitted, then thecontentType is irrelevant.SeeAppendix B for a discussion of data type conversion options.
| Field Name | Type | Description |
|---|---|---|
| style | string | Describes how a specific property value will be serialized depending on its type. SeeParameter Object for details on thestyle field. The behavior follows the same values asquery parameters, including the default value of"form" which applies only whencontentType isnot being used due to one or both ofexplode orallowReserved being explicitly specified. Note that the initial? used in query strings is not used inapplication/x-www-form-urlencoded message bodies, andMUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually). This fieldSHALL be ignored if the media type is notapplication/x-www-form-urlencoded ormultipart/form-data. If a value is explicitly defined, then the value ofcontentType (implicit or explicit)SHALL be ignored. |
| explode | boolean | When this is true, property values of typearray orobject generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties, or whenstyle is"deepObject", this field has no effect. Whenstyle is"form", the default value istrue. For all other styles, the default value isfalse. This fieldSHALL be ignored if the media type is notapplication/x-www-form-urlencoded ormultipart/form-data. If a value is explicitly defined, then the value ofcontentType (implicit or explicit)SHALL be ignored. |
| allowReserved | boolean | When this is true, parameter values are serialized using reserved expansion, as defined by [RFC6570]Section 3.2.3, which allowsRFC3986’s reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including% outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the target media type; seeURL Percent-Encoding for details. The default value isfalse. This fieldSHALL be ignored if the media type is notapplication/x-www-form-urlencoded ormultipart/form-data. If a value is explicitly defined, then the value ofcontentType (implicit or explicit)SHALL be ignored. |
When using RFC6570-style serialization formultipart/form-data, URI percent-encodingMUST NOT be applied, and the value ofallowReserved has no effect.See alsoAppendix C: Using RFC6570 Implementations for additional guidance.
Note that the presence of at least one ofstyle,explode, orallowReserved with an explicit value is equivalent to usingschema within: "query" Parameter Objects.The absence of all three of those fields is the equivalent of usingcontent, but with the media type specified incontentType rather than through a Media Type Object.
Nested formats requiring encoding, most notably nestedmultipart/mixed, can be supported with this Object’sencoding,prefixEncoding, and / oritemEncoding fields.ImplementationsMUST support one level of nesting, andMAY support additional levels.
To work with content using form url encoding via [WHATWG-URL], use theapplication/x-www-form-urlencoded media type in theMedia Type Object.This configuration means that the contentMUST be percent-encoded per [WHATWG-URL]'s rules for that media type, after any complex objects have been serialized to a string representation.
SeeAppendix E for a detailed examination of percent-encoding concerns for form media types.
When there is noencoding field, the serialization strategy is based on the Encoding Object’s default values:
requestBody:content:application/x-www-form-urlencoded:schema:type:objectproperties:id:type:stringformat:uuidaddress:type:objectproperties: {}With this example, consider anid off81d4fae-7dec-11d0-a765-00a0c91e6bf6 and a US-style address (with ZIP+4) as follows:
{"streetAddress":"123 Example Dr.","city":"Somewhere","state":"CA","zip":"99999+1234"}Assuming the most compact representation of the JSON value (with unnecessary whitespace removed), we would expect to see the following request body, where space characters have been replaced with+ and+,",:,,,{, and} have been percent-encoded to%2B,%22,%3A,%2C,%7B, and%7D, respectively:
id=f81d4fae-7dec-11d0-a765-00a0c91e6bf6&address=%7B%22streetAddress%22%3A%22123+Example+Dr.%22%2C%22city%22%3A%22Somewhere%22%2C%22state%22%3A%22CA%22%2C%22zip%22%3A%2299999%2B1234%22%7DNote that theid keyword is treated astext/plain per theEncoding Object’s default behavior, and is serialized as-is.If it were treated asapplication/json, then the serialized value would be a JSON string including quotation marks, which would be percent-encoded as%22.
Here is theid parameter (withoutaddress) serialized asapplication/json instead oftext/plain, and then encoded per [WHATWG-URL]'sform-urlencoded rules:
id=%22f81d4fae-7dec-11d0-a765-00a0c91e6bf6%22Note thatapplication/x-www-form-urlencoded is a text format, which requires base64-encoding any binary data:
requestBody:content:application/x-www-form-urlencoded:schema:type:objectproperties:name:type:stringicon:# The default content type with `contentEncoding` present# is `application/octet-stream`, so we need to set the correct# image media type(s) in the Encoding Object.type:stringcontentEncoding:base64urlencoding:icon:contentType:image/png,image/jpegGiven a name ofexample and a solid red 2x2-pixel PNG foricon, thiswould produce a request body of:
name=example&icon=iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAABGdBTUEAALGPC_xhBQAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAAqADAAQAAAABAAAAAgAAAADO0J6QAAAAEElEQVQIHWP8zwACTGCSAQANHQEDqtPptQAAAABJRU5ErkJggg%3D%3DNote that the= padding characters at the end need to be percent-encoded, even with the “URL safe”contentEncoding: base64url.Some base64-decoding implementations may be able to use the string without the padding per [RFC4648]Section 3.2.However, this is not guaranteed, so it may be more interoperable to keep the padding and rely on percent-decoding.
SeeEncoding Usage and Restrictions for guidance on correlating schema properties with parts.
Note that there are significant restrictions on what headers can be used withmultipart media types in general ([RFC2046]Section 5.1) andmulti-part/form-data in particular ([RFC7578]Section 4.8).
When multiple values are provided forcontentType, parsing remains straightforward as the part’s actualContent-Type is included in the document.
For encoding and serialization, implementationsMUST provide a mechanism for applications to indicate which media type is intended.ImplementationsMAY choose to offer media type sniffing ([SNIFF]) as an alternative, but thisMUST NOT be the default behavior due to the security risks inherent in the process.
UsingcontentEncoding for a multipart field is equivalent to specifying anEncoding Object with aheaders field containingContent-Transfer-Encoding with a schema that requires the value used incontentEncoding.IfcontentEncoding is used for a multipart field that has an Encoding Object with aheaders field containingContent-Transfer-Encoding with a schema that disallows the value fromcontentEncoding, the result is undefined for serialization and parsing.
Note that as stated inWorking with Binary Data, if the Encoding Object’scontentType, whether set explicitly or implicitly through its default value rules, disagrees with thecontentMediaType in a Schema Object, thecontentMediaTypeSHALL be ignored.Because of this, and because the Encoding Object’scontentType defaulting rules do not take the Schema Object’scontentMediaType into account, the use ofcontentMediaType with an Encoding Object isNOT RECOMMENDED.
Note also thatContent-Transfer-Encoding is deprecated formultipart/form-data ([RFC7578]Section 4.7) where binary data is supported, as it is in HTTP.
SeeAppendix E for a detailed examination of percent-encoding concerns for form media types.
When theencoding field isnot used, the encoding is determined by the Encoding Object’s defaults:
requestBody:content:multipart/form-data:schema:type:objectproperties:# default content type for a string without `contentEncoding`# is `text/plain`id:type:stringformat:uuid# default content type for a schema without `type`# is `application/octet-stream`profileImage: {}# for arrays, the `encoding` field applies the Encoding Object# to each item individually and determines the default content type# based on the type in the `items` subschema, which in this example# is an object, so the default content type for each item is# `application/json`addresses:type:arrayitems:$ref:'#/components/schemas/Address'Usingencoding, we can set more specific types for binary data, or non-JSON formats for complex values.We can also describe headers for each part:
requestBody:content:multipart/form-data:schema:type:objectproperties:# No Encoding Object, so use default `text/plain`id:type:stringformat:uuid# Encoding Object overrides the default `application/json` content type# for each item in the array with `application/xml; charset=utf-8`addresses:description:addressesinXMLformattype:arrayitems:$ref:'#/components/schemas/Address'# Encoding Object accepts only PNG or JPEG, and also describes# a custom header for just this part in the multipart formatprofileImage: {}encoding:addresses:contentType:application/xml;charset=utf-8profileImage:contentType:image/png,image/jpegheaders:X-Rate-Limit-Limit:description:Thenumberofallowedrequestsinthecurrentperiodschema:type:integerIn accordance with [RFC7578]Section 4.3, multiple files for a single form field are uploaded using the same name (file in this example) for each file’s part:
requestBody:content:multipart/form-data:schema:properties:# The property name `file` will be used for all files.file:type:arrayitems: {}As seen in theEncoding Object’scontentType field documentation, the empty schema foritems indicates a media type ofapplication/octet-stream.
Amultipart/mixed payload consisting of a JSON metadata document followed by an image which the metadata describes:
multipart/mixed:schema:type:arrayprefixItems:-# default content type for objects# is `application/json`type:objectproperties:author:type:stringcreated:type:stringformat:datetimecopyright:type:stringlicense:type:string-# default content type for a schema without `type`# is `application/octet-stream`, which we need# to override. {}prefixEncoding:-# Encoding Object defaults are correct for JSON {}-contentType:image/*As described in [RFC2557], a set of resources making up a web page can be sent in amultipart/related payload, preserving links from thetext/html document to subsidiary resources such as scripts, style sheets, and images by defining aContent-Location header for each page.The first part is used as the root resource (unless usingContent-ID, which RFC2557 advises against and is forbidden in this example), so we useprefixItems andprefixEncoding to define that it must be an HTML resource, and then allow any of several different types of resources in any order to follow.
TheContent-Location header is defined usingcontent: {text/plain: {...}} to avoid percent-encoding its URI value; seeAppendix D for further details.
components:headers:RFC2557NoContentId:description:UseContent-LocationinsteadofContent-IDschema:falseRFC2557ContentLocation:required:truecontent:text/plain:schema:$comment:UseafullURI(notarelativereference)type:stringformat:urirequestBodies:RFC2557:content:multipart/related;type=text/html:schema:prefixItems:-type:stringitems:anyOf:-type:string-$comment:Toallowbinary,thismustalwayspassprefixEncoding:-contentType:text/htmlheaders:Content-ID:$ref:'#/components/headers/RFC2557NoContentId'Content-Location:$ref:'#/components/headers/RFC2557ContentLocation'itemEncoding:contentType:text/css,text/javascript,image/*headers:Content-ID:$ref:'#/components/headers/RFC2557NoContentId'Content-Location:$ref:'#/components/headers/RFC2557ContentLocation'This example assumes a device that takes large sets of pictures and streams them to the caller.Unlike the previous example, we useitemSchema here because the expectation is that each image is processed as it arrives (or in small batches), since we know that buffering the entire stream will take too much memory.
multipart/mixed:itemSchema:$comment:AsingledataimagefromthedeviceitemEncoding:contentType:image/jpgFormultipart/byteranges [RFC9110]Section 14.6, aContent-Range header is required:
SeeAppendix D for an explanation of whycontent: {text/plain: {...}} is used to describe the header value.
multipart/byteranges:itemSchema:$comment:AsinglerangeofbytesfromavideoitemEncoding:contentType:video/mp4headers:Content-Range:required:truecontent:text/plain:schema:# The `pattern` regular expression that would# be included in practice is omitted for simplicitytype:stringThis defines a two-partmultipart/mixed where the first part is a JSON array and the second part is a nestedmultipart/mixed document.The nested parts are XML, plain text, and a PNG image.
multipart/mixed:schema:type:arrayprefixItems:-type:array-type:arrayprefixItems:-type:object-type:string- {}prefixEncoding:- {}# Accept the default application/json-contentType:multipart/mixedprefixEncoding:-contentType:application/xml- {}# Accept the default text/plain-contentType:image/pngA 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.
ThedefaultMAY be used as a default Response Object for all HTTP codesthat are not covered individually by the Responses Object.
The Responses ObjectMUST contain at least one response code, and if only oneresponse code is provided itSHOULD be the response for a successful operationcall.
| Field Name | Type | Description |
|---|---|---|
| default | Response Object |Reference Object | The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. |
| Field Pattern | Type | Description |
|---|---|---|
| HTTP Status Code | Response Object |Reference Object | AnyHTTP 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. This fieldMUST be enclosed in quotation marks (for example, “200”) for compatibility between JSON and YAML. To define a range of response codes, this fieldMAY contain the uppercase wildcard characterX. For example,2XX represents all response codes between200 and299. Only the following range definitions are allowed:1XX,2XX,3XX,4XX, and5XX. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. |
This objectMAY be extended withSpecification Extensions.
The HTTP Status Codes are used to indicate the status of the executed operation.Status codesSHOULD be selected from the available status codes registered in theIANA Status Code Registry.
A 200 response for a successful operation and a default response for others (implying an error):
'200':description:apettobereturnedcontent:application/json:schema:$ref:'#/components/schemas/Pet'default:description:Unexpectederrorcontent:application/json:schema:$ref:'#/components/schemas/ErrorModel'Describes a single response from an API operation, including design-time, staticlinks to operations based on the response.
| Field Name | Type | Description |
|---|---|---|
| summary | string | A short summary of the meaning of the response. |
| description | string | A description of the response. [CommonMark] syntaxMAY be used for rich text representation. |
| headers | Map[string,Header Object |Reference Object] | Maps a header name to its definition. [RFC9110]Section 5.1 states header names are case-insensitive. If a response header is defined with the name"Content-Type", itSHALL be ignored. |
| content | Map[string,Media Type Object |Reference Object] | A map containing descriptions of potential response payloads. The key is a media type ormedia 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[string,Link Object |Reference Object] | 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 forComponent Objects. |
This objectMAY be extended withSpecification Extensions.
Response of an array of a complex type:
description:Acomplexobjectarrayresponsecontent:application/json:schema:type:arrayitems:$ref:'#/components/schemas/VeryComplexType'Response with a string type:
description:Asimplestringresponsecontent:text/plain:schema:type:stringPlain text response with headers:
description:Asimplestringresponsecontent:text/plain:schema:type:stringexample:'whoa!'headers:X-Rate-Limit-Limit:description:Thenumberofallowedrequestsinthecurrentperiodschema:type:integerX-Rate-Limit-Remaining:description:Thenumberofremainingrequestsinthecurrentperiodschema:type:integerX-Rate-Limit-Reset:description:Thenumberofsecondsleftinthecurrentperiodschema:type:integerResponse with no return value:
description:objectcreatedA map of possible out-of band callbacks related to the parent operation.Each value in the map is aPath 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.
To describe incoming requests from the API provider independent from another API call, use thewebhooks field.
| Field Pattern | Type | Description |
|---|---|---|
| {expression} | Path Item Object | A Path Item Object used to define a callback request and expected responses. Acomplete example is available. |
This objectMAY be extended withSpecification Extensions.
The key that identifies thePath Item Object is aruntime 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 aruntime 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:
POST/subscribe/myevent?queryUrl=https://clientdomain.com/stillrunningHTTP/1.1Host:example.orgContent-Type:application/jsonContent-Length:188{ "failedUrl": "https://clientdomain.com/failed", "successUrls": [ "https://clientdomain.com/fast", "https://clientdomain.com/medium", "https://clientdomain.com/slow" ]}resulting in:
201 CreatedLocation:https://example.org/subscription/1The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter namedeventType and a query parameter namedqueryUrl.
| Expression | Value |
|---|---|
| $url | https://example.org/subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning |
| $method | POST |
| $request.path.eventType | myevent |
| $request.query.queryUrl | https://clientdomain.com/stillrunning |
| $request.header.content-type | application/json |
| $request.body#/failedUrl | https://clientdomain.com/failed |
| $request.body#/successUrls/1 | https://clientdomain.com/medium |
| $response.header.Location | https://example.org/subscription/1 |
The following example uses the user providedqueryUrl query string parameter to define the callback URL. This is similar to awebhook, but differs in that the callback only occurs because of the initial request that sent thequeryUrl.
myCallback:'{$request.query.queryUrl}':post:requestBody:description:Callbackpayloadcontent:application/json:schema:$ref:'#/components/schemas/SomePayload'responses:'200':description:callbacksuccessfullyprocessedThe following example shows a callback where the server is hard-coded, but the query string parameters are populated from theid andemail property in the request body.
transactionCallback:'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}':post:requestBody:description:Callbackpayloadcontent:application/json:schema:$ref:'#/components/schemas/SomePayload'responses:'200':description:callbacksuccessfullyprocessedAn object grouping an internal or external example value with basicsummary anddescription metadata.The examples can show either data suitable for schema validation, or serialized data as required by the containingMedia Type Object,Parameter Object, orHeader Object.This object is typically used in fields namedexamples (plural), and is areferenceable alternative to olderexample (singular) fields that do not support referencing or metadata.The various fields and types of examples are explained in more detail underWorking With Examples.
| Field Name | Type | Description |
|---|---|---|
| summary | string | Short description for the example. |
| description | string | Long description for the example. [CommonMark] syntaxMAY be used for rich text representation. |
| dataValue | Any | An example of the data structure thatMUST be valid according to the relevantSchema Object. If this field is present,valueMUST be absent. |
| serializedValue | string | An example of the serialized form of the value, including encoding and escaping as described underValidating Examples. IfdataValue is present, then this fieldSHOULD contain the serialization of the given data. Otherwise, itSHOULD be the valid serialization of a data value that itselfMUST be valid as described fordataValue. This fieldSHOULD NOT be used if the serialization format is JSON, as the data form is easier to work with. If this field is present,value, andexternalValueMUST be absent. |
| externalValue | string | A URI that identifies the serialized example in a separate document, allowing for values not easily or readably expressed as a Unicode string. IfdataValue is present, then this fieldSHOULD identify a serialization of the given data. Otherwise, the valueSHOULD be the valid serialization of a data value that itselfMUST be valid as described fordataValue. If this field is present,serializedValue andvalueMUST be absent. See also the rules for resolvingRelative References. |
| value | Any | Embedded literal example. Thevalue field andexternalValue field are mutually exclusive. To represent examples of media types that cannot naturally be represented in JSON or YAML, use a string value to contain the example, escaping where necessary.Deprecated for non-JSON serialization targets: Use dataValue and/orserializedValue, which both have unambiguous syntax and semantics, instead. |
This objectMAY be extended withSpecification Extensions.
In all cases, the example valueSHOULD be compatible with the schema of its associated value.Tooling implementationsMAY choose to validate compatibility automatically, and reject the example value(s) if incompatible.SeeValidating Examples for the exact meaning of “compatible” for each field in this Object.
Example Objects can be used inParameter Objects,Header Objects, andMedia Type Objects.In all three Objects, this is done through theexamples (plural) field.However, there are several other ways to provide examples: Theexample (singular) field that is mutually exclusive withexamples in all three Objects, and two keywords (the deprecated singularexample and the current pluralexamples, which takes an array of examples) in theSchema Object that appears in theschema field of all three Objects.We will refer to the singularexample field in the Parameter, Header, or Media Type Object, which has the same behavior as a single Example Object with only thevalue field, as the “shorthandexample” field.Each of these fields has slightly different considerations.
Thevalue and the shorthandexample field are intended to have the samesemantics asserializedValue (orexternalValue), while allowing a more convenientsyntax when there is no difference between a JSON (orJSON-compatible YAML) representation and the final serialized form.When using this syntax forapplication/json or any+json media type, these fields effectively behave likedataValue, as the serialization is trivial, and they are safe to use.
For data that consists of a single string, and a serialization target such astext/plain where the string is guaranteed to be serialized without any further escaping, these fields are also safe to use.
For other serialization targets, the ambiguity of the phrase “naturally be represented in JSON or YAML,” as well as past errors in the parameter style examples table, have resulted in inconsistencies in the support and usage of these fields.In practice, this has resulted in thevalue and shorthandexample fields having implementation-defined behavior for non-JSON targets; OAD authorsSHOULD use other fields to ensure interoperability.
Keeping in mind the caveats from the previous section, and that the shorthandexample can be used in place ofvalue if there is only one Example Object involved, use the following guidelines to determine which field to use.
To show an example as it would be validated by a Schema Object:
examples array (from JSON Schema draft 2020-12) if the intent is to keep the example with the validating schema.example (singular) only if compatibility with OAS v3.0 or earlier is required.dataValue field if the intent is to associate the example with an example of its serialization, or if it is desirable to maintain it separately from the schema.value field only if compatibility with OAS v3.1 or earlier is needed and the value can be “naturally represented in JSON or YAML” without any changes (such as percent-encoding) between the validation-ready value and the serialized representation.To show an example as it would be serialized in order to construct an HTTP/1.1 message:
serializedValue if the serialization can be represented as a valid Unicode string, and there is no need to demonstrate the exact character encoding to be used.value only if compatibility with OAS v3.1 or earlier is needed.externalValue for all other values, or if it is desirable to maintain the example separately from the OpenAPI document.TheserializedValue andexternalValue fields bothMUST show the serialized form of the data.For Media Type Objects, this is a document of the appropriate media type, with any Encoding Object effects applied.For Parameter and Header Objects usingschema andstyle rather than a Media Type Object, seeStyle Examples for what constitutes a serialized value.
A serialization can be represented as a valid Unicode string inserializedValue if any of the following are true of the serialization:
charset parameter that indicates any Unicode encoding (UTF-8, UTF-16, etc.), or any valid subset of such an encoding, such as US-ASCII.charset.multipart/mixed media type with parts that areapplication/json (a media type that defaults to UTF-8) andapplication/xml; charset=utf-8 (a media type with an explicitcharset parameter).In all of these cases, the conversion from the character set of the OAD (presumed to be UTF-8 as the only interoperable character set for JSON, and therefore also for JSON-compatible YAML as noted in [RFC9512]Section 3.4) first to Unicode code points and then to the actual serialization character set is well-defined.
ForexternalValue, if the character set is neither explicitly stated nor determined by the format or media type specification, implementationsSHOULD assume UTF-8.
Tooling implementationsMAY choose to validate compatibility automatically, and reject the example value(s) if incompatible.For examples that are in schema-ready data form, this is straightforward.
With serialized examples, some formats allow multiple possible valid representations of the same data, including in scenarios noted inAppendix B.In some cases, parsing the serialized example and validating the resulting data can eliminate the ambiguity, but in a few cases parsing is also ambiguous.Therefore, OAD authors are cautioned that validation of certain serialized examples is by necessity a best-effort feature.
When writing in YAML, JSON syntax can be used fordataValue (as shown in thenoRating example) but is not required.While this example shows the behavior of bothdataValue andserializedValue for JSON (in the 'withRating` example), in most cases only the data form is needed.
content:application/json:schema:type:objectrequired:-author-titleproperties:author:type:stringtitle:type:stringrating:type:numberminimum:1maximum:5multipleOf:0.5examples:noRating:summary:Anot-yet-ratedworkdataValue:author:A.Writertitle:TheNewestBookwithRating:summary:Aworkwithanaverageratingof4.5starsdataValue:author:A.Writertitle:AnOlderBookrating:4.5serializedValue:| { "author": "A. Writer", "title": "An Older Book", "rating": 4.5 }Fully binary data is shown usingexternalValue:
content:image/png:schema: {}examples:Red:externalValue:./examples/2-by-2-red-pixels.pngSince there is no standard for serializing boolean values (as discussed inAppendix B), this example usesdataValue andserializedValue to show how booleans are serialized for this particular parameter:
name:flagin:queryrequired:trueschema:type:booleanexamples:"true":dataValue:trueserializedValue:flag=true"false":dataValue:falseserializedValue:flag=falseThe 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.
Unlikedynamic links (i.e. links providedin 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, aruntime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.
| Field Name | Type | Description |
|---|---|---|
| operationRef | string | A URI reference to an OAS operation. This field is mutually exclusive of theoperationId field, andMUST point to anOperation Object. RelativeoperationRef valuesMAY be used to locate an existingOperation Object in the OpenAPI Description. |
| operationId | string | The name of anexisting, resolvable OAS operation, as defined with a uniqueoperationId. This field is mutually exclusive of theoperationRef field. |
| parameters | Map[string, Any |{expression}] | A map representing parameters to pass to an operation as specified withoperationId or identified viaoperationRef. The key is the parameter name to be used (optionally qualified with the parameter location, e.g.path.id for anid parameter in the path), whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. |
| requestBody | Any |{expression} | A literal value or{expression} to use as a request body when calling the target operation. |
| description | string | A description of the link. [CommonMark] syntaxMAY be used for rich text representation. |
| server | Server Object | A server object to be used by the target operation. |
This objectMAY be extended withSpecification Extensions.
A linked operationMUST be identified using either anoperationRef oroperationId.The identified or referenced operationMUST be unique, and in the case of anoperationId, itMUST be resolved within the scope of the OpenAPI Description (OAD).Because of the potential for name clashes, theoperationRef syntax is preferred for multi-document OADs.However, because use of an operation depends on its URL path template in thePaths Object, operations from anyPath Item Object that is referenced multiple times within the OAD cannot be resolved unambiguously.In such ambiguous cases, the resulting behavior is implementation-defined andMAY result in an error.
Note that it is not possible to provide a constant value toparameters that matches the syntax of a runtime expression.It is possible to have ambiguous parameter names, e.g.name: "id", in: "path" andname: "path.id", in: "query"; this isNOT RECOMMENDED and the behavior is implementation-defined, however implementationsSHOULD prefer the qualified interpretation (path.id as a path parameter), as the names can always be qualified to disambiguate them (e.g. usingquery.path.id for the query parameter).
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:idin:pathrequired:truedescription:theuseridentifier,asuserIdschema:type:stringget:responses:'200':description:theuserbeingreturnedcontent:application/json:schema:type:objectproperties:uuid:# the unique user idtype:stringformat:uuidlinks:address:# the target link operationIdoperationId:getUserAddressparameters:# 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:useridin:pathrequired:truedescription:theuseridentifier,asuserIdschema:type:string# linked operationget:operationId:getUserAddressresponses:'200':description:theuser'saddressWhen 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:getUserAddressByUUIDparameters:# get the `uuid` field from the `uuid` field in the response bodyuserUuid:$response.body#/uuidClients follow all links at their discretion.Neither permissions nor the capability to make a successful call to that link is guaranteedsolely by the existence of a relationship.
As theoperationId is an optional field in anOperation Object, referencesMAY instead be made through a URI reference withoperationRef.Note that both of these examples reference operations that can be identified via thePaths Object to ensure that the operation’s path template is unambiguous.
A relative URI referenceoperationRef:
links:UserRepositories:# returns array of '#/components/schemas/repository'operationRef:'#/paths/~12.0~1repositories~1%7Busername%7D/get'parameters:username:$response.body#/usernameA non-relative URIoperationRef:
links:UserRepositories:# returns array of '#/components/schemas/repository'operationRef:https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1%7Busername%7D/getparameters:username:$response.body#/usernameNote that in the use ofoperationRef theescaped forward-slash (~1) is necessary whenusing JSON Pointer in URI fragments, and it is necessary to URL-encode{ and} as%7B and%7D, respectively.The unescaped, percent-decoded path template in the above examples would be/2.0/repositories/{username}.
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 byLink Objects andCallback Objects.
The runtime expression is defined by the following [ABNF] 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" ["#" json-pointer ] json-pointer= *("/" reference-token ) reference-token= *( unescaped / escaped ) unescaped=%x00-2E /%x30-7D /%x7F-10FFFF; %x2F ('/') and %x7E ('~') are excluded from 'unescaped' escaped="~" ("0" /"1" ); representing '~' and '/', respectively name= *char token=1*tchar tchar="!" /"#" /"$" /"%" /"&" /"'" /"*" /"+" /"-" /"." /"^" /"_" /"`" /"|" /"~" /DIGIT /ALPHAHere,json-pointer is taken from [RFC6901],char from [RFC8259]Section 7 andtoken from [RFC9110]Section 5.6.2.
Thename identifier is case-sensitive, whereastoken is not.
The table below provides examples of runtime expressions and examples of their use in a value:
| 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 parametersMUST be declared in theparameters 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 therequestBody 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.
Describes a single header forHTTP responses and forindividual parts inmultipart representations; see the relevantResponse Object andEncoding Object documentation for restrictions on which headers can be described.
The Header Object follows the structure of theParameter Object, including determining its serialization strategy based on whetherschema orcontent is present, with the following changes:
nameMUST NOT be specified, it is given in the correspondingheaders map.inMUST NOT be specified, it is implicitly inheader.header (for example,style). This means thatallowEmptyValueMUST NOT be used, andstyle, if used,MUST be limited to"simple".These fieldsMAY be used with eithercontent orschema.
Theexample andexamples fields are mutually exclusive; seeWorking with Examples for guidance on validation requirements.
| Field Name | Type | Description |
|---|---|---|
| description | string | A brief description of the header. This could contain examples of use. [CommonMark] syntaxMAY be used for rich text representation. |
| required | boolean | Determines whether this header is mandatory. The default value isfalse. |
| deprecated | boolean | Specifies that the header is deprecated andSHOULD be transitioned out of usage. Default value isfalse. |
| example | Any | Example of the header’s potential value; seeWorking With Examples. |
| examples | Map[string,Example Object |Reference Object] | Examples of the header’s potential value; seeWorking With Examples. |
This objectMAY be extended withSpecification Extensions.
For simpler scenarios, aschema andstyle can describe the structure and syntax of the header.
When serializing headers withschema, URI percent-encodingMUST NOT be applied; if using an RFC6570 implementation that automatically applies it, itMUST be removed before use.ImplementationsMUST pass header values through unchanged rather than attempting to automatically quote header values, as the quoting rules vary too widely among different headers; seeAppendix D for guidance on quoting and escaping.
| Field Name | Type | Description |
|---|---|---|
| style | string | Describes how the header value will be serialized. The default (and only legal value for headers) is"simple". |
| explode | boolean | When this is true, header values of typearray orobject generate a single header whose value is a comma-separated list of the array items or key-value pairs of the map, seeStyle Examples. For other data types this field has no effect. The default value isfalse. |
| schema | Schema Object | The schema defining the type used for the header. |
See alsoAppendix C: Using RFC6570-Based Serialization for additional guidance.
For more complex scenarios, thecontent field can define the media type and schema of the header, as well as give examples of its use.
| Field Name | Type | Description |
|---|---|---|
| content | Map[string,Media Type Object |Reference Object] | A map containing the representations for the header. The key is the media type and the value describes it. The mapMUST only contain one entry. |
[RFC9264] defines theapplication/linkset andapplication/linkset+json media types.The former is exactly the format of HTTP link header values except allowing additional whitespace for readability, while the latter is an equivalent JSON representation of such headers.
To use either of these media types, theschema in theMedia Type ObjectMUST describe the links as they would be structured in theapplication/linkset+json format.If the Media Type Object’s parent key isapplication/linkset+json, then the serialization is trivial, however this format cannot be used in the HTTPLink header.If the Media Type Object’s parent key isapplication/linkset, then the serializationMUST be the equivalent representation of theschema-modeled links in theapplication/linkset format.If theapplication/linkset Media Type Object is used in thecontent field of a Header Object (or a Parameter Object within: "header"), the serializationMUST be made compatible with the HTTP field syntax as described by [RFC9264]Section 4.1.
The following example shows how the same data model can be used for a collection pagination linkset either in JSON format as message content, or in the HTTPLink header:
components:schemas:SimpleLinkContext:type:arrayitems:type:objectrequired:-hrefproperties:href:type:stringformat:uri-referenceCollectionLinks:type:objectrequired:-linksetproperties:linkset:type:arrayitems:type:objectrequired: [first,prev,next,last]properties:anchor:type:stringformat:uriadditionalProperties:$ref:'#/components/schemas/SimpleLinkContext'responses:CollectionWithLinks:content:application/json:schema:type:arrayheaders:Link:required:truecontent:application/linkset:schema:$ref:'#/components/schemas/CollectionLinks'StandaloneJsonLinkset:content:application/linkset+json:schema:$ref:'#/components/mediaTypes/CollectionLinks'TheSet-Cookie header is noted in [RFC9110]Section 5.3 as an exception to the normal rules of headers with multiple values.
For most headers using the general syntax defined in RFC9110, the multiple-line and comma-separated single-line forms are interchangeable, meaning that this:
Accept-Encoding:compress;q=0.5Accept-Encoding:gzip;q=1.0is interchangeable with the one-line form that works well with the OAS’sstyle: "simple" option:
Accept-Encoding:compress;q=0.5,gzip;q=1.0The OAS models such multi-value headers using the one-line form as it matches the behavior ofstyle: "simple", and works well when usingcontent as the values are completely separate from the header name, but it does not matter which form is used in an actual HTTP message.
As also noted in the RFC,Set-Cookie is an exception as it allows unquoted, non-escaped commas in its values, and can only use the one-value-per-line form.For HTTP messages, this is purely a serialization concern, and no more of a problem than a message that uses the multi-line form of any other header.
However, because examples and values modeled withcontent do not incorporate the header name, for these fieldsSet-CookieMUST be handled by placing each value on a separate line, without the header name or the: delimiter.
Note also that any URI percent-encoding, base64 encoding, or other escapingMUST be performed prior to supplying the data to OAS tooling; seeAppendix D for details.
The following example shows two different ways to describeSet-Cookie headers that require cookies named"lang" and"foo", as well as a"urlSafeData" cookie that is expected to be percent-encoded. The first usescontent in order to show exactly how such examples are formatted, but also notes the limitations of schema constraints with multi-line text. The second shows the use ofstyle: "simple", which produces the same serialized example text (with each line corresponding to oneSet-Cookie: line in the HTTP response), but allows schema constraints on each cookie; note that the percent-encoding is already applied in thedataValue field of the example:
components:headers:SetCookieWithContent:content:text/plain:schema:# Due to lack of support for multiline regular expressions# in the `pattern` keyword, not much validation can be done.type:stringexamples:WithExpires:# This demonstrates that the text is required to be provided# in the final format, and is not changed by serialization.# In practice, it is not necessary to show both value fields.# Note that only the comma (%2C) would need to be percent-encoded# if percent-encoding were only being done to make the value# a valid cookie, as space (%20) and the exclamation point (%21)# are allowed in cookies, but not in URLs. See the cookie# input parameter examples for an example of encoding only# what is needed for the cookie syntax.dataValue:| lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT foo=bar; Expires=Wed, 09 Jun 2021 10:18:14 GMT urlSafeData: Hello%2C%20world%21serializedValue:| lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT foo=bar; Expires=Wed, 09 Jun 2021 10:18:14 GMT urlSafeData: Hello%2C%20world%21SetCookieWithSchemaAndStyle:schema:type:objectrequired:-lang-foo-urlSafeDataproperties:urlSafeData:type:stringpattern:^[-_.%a-zA-Z0-9]+(;|$)additionalProperties:$comment:RequireanExpiresparameterpattern:"; *Expires="style:simpleexplode:trueexamples:SetCookies:dataValue: {"lang":"en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT""foo":"bar; Expires=Wed, 09 Jun 2021 10:18:14 GMT""urlSafeData":"Hello%2C%20world%21" }serializedValue:| lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT foo=bar; Expires=Wed, 09 Jun 2021 10:18:14 GMT urlSafeData: Hello%2C%20world%21In an HTTP message, the serialized example would look like:
Set-Cookie:lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMSet-Cookie:foo=bar; Expires=Wed, 09 Jun 2021 10:18:14 GMTSet-Cookie:urlSafeData=Hello%2C%20world%21A simple header of typeinteger:
X-Rate-Limit-Limit:description:Thenumberofallowedrequestsinthecurrentperiodschema:type:integerRequiring that a strongETag header (with a value starting with" rather thanW/) is present.
ETag:required:trueschema:type:string# Note that quotation marks are part of the# ETag value, unlike many other headers that# use a quoted string purely for managing# reserved characters.pattern:^"example:'"xyzzy"'Adds metadata to a single tag that is used by theOperation Object.It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.
| Field Name | Type | Description |
|---|---|---|
| name | string | REQUIRED. The name of the tag. Use this value in thetags array of an Operation. |
| summary | string | A short summary of the tag, used for display purposes. |
| description | string | A description for the tag. [CommonMark] syntaxMAY be used for rich text representation. |
| externalDocs | External Documentation Object | Additional external documentation for this tag. |
| parent | string | Thename of a tag that this tag is nested under. The named tagMUST exist in the API description, and circular references between parent and child tagsMUST NOT be used. |
| kind | string | A machine-readable string to categorize what sort of tag it is. Any string value can be used; common uses arenav for Navigation,badge for visible badges,audience for APIs used by different groups. Aregistry of the most commonly used values is available. |
This objectMAY be extended withSpecification Extensions.
tags:-name:account-updatessummary:AccountUpdatesdescription:Accountupdateoperationskind:nav-name:partnersummary:Partnerdescription:Operationsavailabletothepartnersnetworkparent:externalkind:audience-name:externalsummary:Externaldescription:Operationsavailabletoexternalconsumerskind:audienceA simple object to allow referencing other components in the OpenAPI Description, internally and externally.
The$ref string value contains a URI [RFC3986], which identifies the value being referenced.
See the rules for resolvingRelative References.
| Field Name | Type | Description |
|---|---|---|
| $ref | string | REQUIRED. The reference identifier. ThisMUST be in the form of a URI. |
| summary | string | A short summary which by defaultSHOULD override that of the referenced component. If the referenced object-type does not allow asummary field, then this field has no effect. |
| description | string | A description which by defaultSHOULD override that of the referenced component. [CommonMark] syntaxMAY be used for rich text representation. If the referenced object-type does not allow adescription field, then this field has no effect. |
This object cannot be extended with additional properties, and any properties addedSHALL be ignored.
Note that this restriction on additional properties is a difference between Reference Objects andSchema Objects that contain a$ref keyword.
$ref:'#/components/schemas/Pet'$ref:Pet.yaml$ref:definitions.yaml#/PetThe Schema Object allows the definition of input and output data types.These types can be objects, but also primitives and arrays. This object is a superset of theJSON Schema Specification Draft 2020-12. The empty schema (which allows any instance to validate)MAY be represented by the boolean valuetrue and a schema which allows no instance to validateMAY be represented by the boolean valuefalse.
For more information about the keywords, seeJSON Schema Core andJSON Schema Validation.
Unless stated otherwise, the keyword definitions follow those of JSON Schema and do not add any additional semantics; this includes keywords such as$schema,$id,$ref, and$dynamicRef being URIs rather than URLs.Where JSON Schema indicates that behavior is defined by the application (e.g. for annotations), OAS also defers the definition of semantics to the application consuming the OpenAPI document.
The OpenAPI Schema Objectdialect is defined as requiring theOAS base vocabulary, in addition to the vocabularies as specified in the JSON Schema Specification Draft 2020-12general purpose meta-schema.
The OpenAPI Schema Object dialect for this version of the specification is identified by the URIhttps://spec.openapis.org/oas/3.1/dialect/base (the“OAS dialect schema id”).
The following keywords are taken from the JSON Schema specification but their definitions have been extended by the OAS:
In addition to the JSON Schema keywords comprising the OAS dialect, the Schema Object supports keywords from any other vocabularies, or entirely arbitrary properties.
JSON Schema implementationsMAY choose to treat keywords defined by the OpenAPI Specification’s base vocabulary asunknown keywords, due to its inclusion in the OAS dialect with a$vocabulary value offalse.The OAS base vocabulary is comprised of the following keywords:
| Field Name | Type | Description |
|---|---|---|
| discriminator | Discriminator Object | The discriminator provides a “hint” for which of a set of schemas a payload is expected to satisfy. SeeComposition and Inheritance for more details. |
| xml | XML Object | Adds additional metadata to describe the XML representation of this schema. |
| externalDocs | External Documentation Object | Additional external documentation for this schema. |
| example | Any | A free-form field 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: The example field has been deprecated in favor of the JSON Schemaexamples keyword. Use ofexample is discouraged, and later versions of this specification may remove it. |
This objectMAY be extended withSpecification Extensions, though as noted, additional propertiesMAY omit thex- prefix within this object.
Data types in the OAS are based on the types defined by theJSON Schema Validation Specification Draft 2020-12:“null”, “boolean”, “object”, “array”, “number”, “string”, or “integer”.Models are defined using theSchema Object, which is a superset of the JSON Schema Specification Draft 2020-12.
JSON Schema keywords andformat values operate on JSON “instances” which may be one of the six JSON data types, “null”, “boolean”, “object”, “array”, “number”, or “string”, with certain keywords and formats only applying to a specific type. For example, thepattern keyword and thedate-time format only apply to strings, and treat any instance of the other five types asautomatically valid. This means JSON Schema keywords and formats doNOT implicitly require the expected type. Use thetype keyword to explicitly constrain the type.
Note that thetype keyword allows"integer" as a value for convenience, but keyword and format applicability does not recognize integers as being of a distinct JSON type from other numbers becauseJSON itself does not make that distinction. Since there is no distinct JSON integer type, JSON Schema defines integers mathematically. This means that both1 and1.0 areequivalent, and are both considered to be integers.
As defined by theJSON Schema Validation specification, data types can have an optional modifier keyword:format. As described in that specification,format is treated as a non-validating annotation by default; the ability to validateformat varies across implementations.
The OpenAPI Initiative also hosts aFormat Registry for formats defined by OAS users and other specifications. Support for any registered format is strictlyOPTIONAL, and support for one registered format does not imply support for any others.
Types that are not accompanied by aformat keyword follow the type definition in the JSON Schema. Tools that do not recognize a specificformatMAY default back to thetype alone, as if theformat is not specified.For the purpose ofJSON Schema validation, each format should specify the set of JSON data types for which it applies. In this registry, these types are shown in the “JSON Data Type” column.
The formats defined by the OAS are:
format | JSON Data Type | Comments |
|---|---|---|
int32 | number | signed 32 bits |
int64 | number | signed 64 bits (a.k.a long) |
float | number | |
double | number | |
password | string | A hint to obscure the value. |
As noted underData Type, bothtype: number andtype: integer are considered to be numbers in the data model.
API data has several forms:
format andcontentType, and possibly additional information such as class hierarchies that are beyond the scope of this specification, although theyMAY be based on specification elements such as theDiscriminator Object or guidance regardingData Modeling Techniques.JSON-serialized data is nearly equivalent to the data form because theJSON Schema data model is nearly equivalent to the JSON representation.The serialized UTF-8 JSON string{"when": "1985-04-12T23:20:50.52"} represents an object with one data field, namedwhen, with a string value,1985-04-12T23:20:50.52.
The exact application form is beyond the scope of this specification, as can be shown with the following schema for our JSON instance:
type:objectproperties:when:type:stringformat:date-timeSome applications might leave the string as a string regardless of programming language, while others might notice theformat and use it as adatetime.datetime instance in Python, or ajava.time.ZonedDateTime in Java.This specification only requires that the data is valid according to the schema, and thatannotations such asformat are available in accordance with the JSON Schema specification.
Non-JSON serializations can be substantially different from their corresponding data form, and might require several steps to parse.
To continue our “when” example, if we serialized the object asapplication/x-www-form-urlencoded, it would appear as the ASCII stringwhen=1985-04-12T23%3A20%3A50.52.This example is still straightforward to use as it is all string data, and the only differences from JSON are the URI percent-encoding and the delimiter syntax (= instead of JSON punctuation and quoting).
However, many non-JSON text-based formats can be complex, requiring examination of the appropriate schema(s) in order to correctly parse the text into a schema-ready data structure.Serializing data into such formats requires either examining the schema-validated data or performing the same schema inspections.
When inspecting schemas, given a starting point schema, implementationsMUST examine that schema and all schemas that can be reached from it by following only$ref andallOf keywords.These schemas are guaranteed to apply to any instance.When searching schemas fortype, if thetype keyword’s value is a list of types and the serialized value can be successfully parsed as more than one of the types in the list, and no other findabletype keyword disambiguates the actual required type, the behavior is implementation-defined.Schema Objects that do not containtypeMUST be considered to allow all types, regardless of which other keywords are present (e.g.maximum applies to numbers, butdoes not require the instance to be a number).
ImplementationsMAY inspect subschemas or possible reference targets of other keywords such asoneOf or$dynamicRef, butMUST NOT attempt to resolve ambiguities.For example, if an implementation opts to inspectanyOf, the schema:
anyOf:-type:numberminimum:0-type:numbermaximum:100unambiguously indicates a numeric type, but the schema:
anyOf:-type:number-maximum:100does not, because the second subschema allows all types.
Due to these limited requirements for searching schemas, serializers that have access to validated dataMUST inspect the data if possible; implementations that either do not work with runtime data (such as code generators) or cannot access validated data for some reasonMUST fall back to schema inspection.
Recall also that in JSON Schema, keywords that apply to a specific type (e.g.pattern applies to strings,minimum applies to numbers)do not require or imply that the data will actually be of that type.
As an example of these processes, given these OpenAPI components:
components:requestBodies:Form:content:application/x-www-form-urlencoded:schema:$ref:"#/components/schemas/FormData"encoding:extra:contentType:application/xmlschemas:FormData:type:objectproperties:code:allOf:-type: [string,number]pattern:"1"minimum:0-type:stringpattern:"2"count:type:integerextra:type:objectAnd this request body to parse into its data form:
code=1234&count=42&extra=%3Cinfo%3Eabc%3C/info%3EWe must first search the schema forproperties or other property-defining keywords, and then use each property schema as a starting point for a search for that property’stype keyword, as follows (the exact order is implementation-defined):
#/components/requestBodies/Form/content/application~1x-www-form-urlencoded/schema (initial starting point schema, only$ref)#/components/schemas/FormData (follow$ref, foundproperties)#/components/schemas/FormData/properties/code (starting point schema forcode property)#/components/schemas/FormData/properties/code/allOf/0 (followallOf, foundtype: [string, number])#/components/schemas/FormData/properties/code/allOf/1 (followallOf, foundtype: string)#/components/schemas/FormData/properties/count (starting point schema forcount property, foundtype: integer)#/components/schemas/FormData/properties/extra (starting point schema forextra property, foundtype: object)Note that forcode we first found an ambiguoustype, but then found anothertype keyword that ensures only one of the two possibilities is valid.
From this inspection, we determine thatcode is a string that happens to look like a number, whilecount needs to be parsed into a numberprior to schema validation.Furthermore, theextra string is in fact an XML serialization of an object containing aninfo property.This means that the data form of this serialization is equivalent to the following JSON object:
{"code":"1234","count":42"extra":{"info":"abc"}}Serializing this object also requires correlating properties withEncoding Objects, and may require inspection to determine a default value of thecontentType field.If validated data is not available, the schema inspection process is identical to that shown for parsing.
In this example, bothcode andcount are of primitive type and do not appear in theencoding field, and are therefore serialized as plain text.However, theextra field is an object, which would by default be serialized as JSON, but theextra entry in theencoding field tells use to serialize it as XML instead.
The OAS can describe eitherraw orencoded binary data.
multipart/* payload that allows binary partsapplication/json orapplication/x-www-form-urlencoded (either as a message body or in the URL query string).In the following table showing how to use Schema Object keywords for binary data, we useimage/png as an example binary media type. Any binary media type, includingapplication/octet-stream, is sufficient to indicate binary content.
| Keyword | Raw | Encoded | Comments |
|---|---|---|---|
type | omit | string | raw binary isoutside oftype |
contentMediaType | image/png | image/png | can sometimes be omitted if redundant (see below) |
contentEncoding | omit | base64 or base64url | other encodings areallowed |
Note that the encoding indicated bycontentEncoding, which inflates the size of data in order to represent it as 7-bit ASCII text, is unrelated to HTTP’sContent-Encoding header, which indicates whether and how a message body has been compressed and is applied after all content serialization described in this section has occurred. Since HTTP allows unencoded binary message bodies, there is no standardized HTTP header for indicating base64 or similar encoding of an entire message body.
Using acontentEncoding ofbase64url ensures that URL encoding (as required in the query string and in message bodies of typeapplication/x-www-form-urlencoded) does not need to further encode any part of the already-encoded binary data.
ThecontentMediaType keyword is redundant if the media type is already set:
contentType field of anEncoding ObjectIf theSchema Object will be processed by a non-OAS-aware JSON Schema implementation, it may be useful to includecontentMediaType even if it is redundant. However, ifcontentMediaType contradicts a relevant Media Type Object or Encoding Object, thencontentMediaTypeSHALL be ignored.
SeeComplete vs Streaming Content for guidance on streaming binary payloads.
Few JSON Schema implementations directly support working with binary data, as doing so is not a mandatory part of that specification.
OAS Implementations that do not have access to a binary-instance-supporting JSON Schema implementationMUST examine schemas and apply them in accordance withWorking with Binary Data.When the entire instance is binary, this is straightforward as few keywords are relevant.
However,multipart media types can mix binary and text-based data, leaving implementations with two options for schema evaluations:
properties,prefixItems, etc.) in order to break up the subschemas and apply them separately to binary and JSON-compatible data.The following table shows how to migrate from OAS 3.0 binary data descriptions, continuing to useimage/png as the example binary media type:
| OAS < 3.1 | OAS >= 3.1 | Comments |
|---|---|---|
type: stringformat: binary | contentMediaType: image/png | if redundant, can be omitted, often resulting in an emptySchema Object |
type: stringformat: byte | type: stringcontentMediaType: image/pngcontentEncoding: base64 | note thatbase64url can be used to avoid re-encoding the base64 string to be URL-safe |
JSON Schema Draft 2020-12 supportscollecting annotations, includingtreating unrecognized keywords as annotations.OAS implementationsMAY use such annotations, includingextensions not recognized as part of a declared JSON Schema vocabulary, as the basis for further validation.Note that JSON Schema Draft 2020-12 does not require anx- prefix for extensions.
Theformat keyword (when using default format-annotation vocabulary) and thecontentMediaType,contentEncoding, andcontentSchema keywords define constraints on the data, but are treated as annotations instead of being validated directly.Extended validation is one way that these constraintsMAY be enforced.
ThereadOnly andwriteOnly keywords are annotations, as JSON Schema is not aware of how the data it is validating is being used.Validation of these keywordsMAY be done by checking the annotation, the read or write direction, and (if relevant) the current value of the field.JSON Schema Validation Draft 2020-12 Section 9.4 defines the expectations of these keywords, including that a resource (described as the “owning authority”)MAY either ignore areadOnly field or treat it as an error.
Fields that are both required and read-only are an example of when it is beneficial to ignore areadOnly: true constraint in a PUT, particularly if the value has not been changed.This allows correctly requiring the field on a GET and still using the same representation and schema with PUT.Even when read-only fields are not required, stripping them is burdensome for clients, particularly when the JSON data is complex or deeply nested.
Note that the behavior ofreadOnly in particular differs from that specified by version 3.0 of this specification.
The OpenAPI Specification allows combining and extending model definitions using theallOf keyword of JSON Schema, in effect offering model composition.allOf takes an array of object definitions that are validatedindependently but together compose a single object.
While composition offers model extensibility, it does not imply a hierarchy between the models.
JSON Schema also provides theanyOf andoneOf keywords, which allow defining multiple schemas where at least one or exactly one of them must be valid, respectively.As is the case withallOf, the schemas are validatedindependently.These keywords can be used to describe polymorphism, where a single field can accept multiple types of values.
The OpenAPI specification extends the JSON Schema support for polymorphism by adding thediscriminator field whose value is aDiscriminator Object.When used, the Discriminator Object indicates the name of the property that hints which schema of ananyOf oroneOf is expected to validate the structure of the model.The discriminating propertyMAY be defined as required or optional, but when defined as an optional property the Discriminator ObjectMUST include adefaultMapping field that specifies which schema of theanyOf oroneOf, or which schema that references the current schema in anallOf, is expected to validate the structure of the model when the discriminating property is not present.
There are two ways to define the value of a discriminating property for an inheriting instance.
ImplementationsSHOULD support defining generic or template data structures using JSON Schema’s dynamic referencing feature:
$dynamicAnchor identifies a set of possible schemas (including a default placeholder schema) to which a$dynamicRef can resolve$dynamicRef resolves to the first matching$dynamicAnchor encountered on its path from the schema entry point to the reference, as described in the JSON Schema specificationAn example is included in theSchema Object Examples section below, and further information can be found on the Learn OpenAPI site’s“Dynamic References” page.
The Schema Object’senum keyword does not allow associating descriptions or other information with individual values.
ImplementationsMAY support recognizing aoneOf oranyOf where each subschema in the keyword’s array consists of aconst keyword and annotations such astitle ordescription as an enumerated type with additional information. The exact behavior of this pattern beyond what is required by JSON Schema is implementation-defined.
Thexml field allows extra definitions when translating the JSON definition to XML.TheXML Object contains additional information about the available options.
It is important for tooling to be able to determine which dialect or meta-schema any given resource wishes to be processed with: JSON Schema Core, JSON Schema Validation, OpenAPI Schema dialect, or some custom meta-schema.
The$schema keywordMAY be present in any Schema Object that is aschema resource root, and if presentMUST be used to determine which dialect should be used when processing the schema. This allows use of Schema Objects which comply with other drafts of JSON Schema than the default Draft 2020-12 support. ToolingMUST support theOAS dialect schema id, andMAY support additional values of$schema.
To allow use of a different default$schema value for all Schema Objects contained within an OAS document, ajsonSchemaDialect value may be set within theOpenAPI Object. If this default is not set, then the OAS dialect schema idMUST be used for these Schema Objects. The value of$schema within a resource root Schema Object always overrides any default.
For standalone JSON Schema documents that do not set$schema, or for Schema Objects in OpenAPI description documents that arenotcomplete documents, the dialectSHOULD be assumed to be the OAS dialect.However, for maximum interoperability, it isRECOMMENDED that OpenAPI description authors explicitly set the dialect through$schema in such documents.
type:stringformat:emailtype:objectrequired:-nameproperties:name:type:stringaddress:$ref:'#/components/schemas/Address'age:type:integerformat:int32minimum:0For a simple string to string mapping:
type:objectadditionalProperties:type:stringFor a string to model mapping:
type:objectadditionalProperties:$ref:'#/components/schemas/ComplexModel'oneOf:-const:RGBtitle:Red,Green,Bluedescription:Specifycolorswiththered,green,andblueadditivecolormodel-const:CMYKtitle:Cyan,Magenta,Yellow,Blackdescription:Specifycolorswiththecyan,magenta,yellow,andblacksubtractivecolormodeltype:objectproperties:id:type:integerformat:int64name:type:stringrequired:-nameexamples:-name:Pumaid:1components:schemas:ErrorModel:type:objectrequired:-message-codeproperties:message:type:stringcode:type:integerminimum:100maximum:600ExtendedErrorModel:allOf:-$ref:'#/components/schemas/ErrorModel'-type:objectrequired:-rootCauseproperties:rootCause:type:stringThe following example describes aPet model that can represent either a cat or a dog, as distinguished by thepetType property. Each type of pet has other properties beyond those of the basePet model. An instance without apetType property, or with apetType property that does not match eithercat ordog, is invalid.
components:schemas:Pet:type:objectproperties:name:type:stringrequired:-name-petTypeoneOf:-$ref:'#/components/schemas/Cat'-$ref:'#/components/schemas/Dog'Cat:description:Apetcattype:objectproperties:petType:const:'cat'huntingSkill:type:stringdescription:Themeasuredskillforhuntingenum:-clueless-lazy-adventurous-aggressiverequired:-huntingSkillDog:description:Apetdogtype:objectproperties:petType:const:'dog'packSize:type:integerformat:int32description:thesizeofthepackthedogisfromdefault:0minimum:0required:-packSizeThe following example extends the example of the previous section by adding aDiscriminator Object to thePet schema. Note that the Discriminator Object is only a hint to the consumer of the API and does not change the validation outcome of the schema.
components:schemas:Pet:type:objectdiscriminator:propertyName:petTypemapping:cat:'#/components/schemas/Cat'dog:'#/components/schemas/Dog'properties:name:type:stringrequired:-name-petTypeoneOf:-$ref:'#/components/schemas/Cat'-$ref:'#/components/schemas/Dog'Cat:description:Apetcattype:objectproperties:petType:const:'cat'huntingSkill:type:stringdescription:Themeasuredskillforhuntingenum:-clueless-lazy-adventurous-aggressiverequired:-huntingSkillDog:description:Apetdogtype:objectproperties:petType:const:'dog'packSize:type:integerformat:int32description:thesizeofthepackthedogisfromdefault:0minimum:0required:-petType-packSizeIt is also possible to describe polymorphic models usingallOf. The following example usesallOf with aDiscriminator Object to describe a polymorphicPet model.
components:schemas:Pet:type:objectdiscriminator:propertyName:petTypeproperties:name:type:stringpetType:type:stringrequired:-name-petTypeCat:# "Cat" will be used as the discriminating valuedescription:ArepresentationofacatallOf:-$ref:'#/components/schemas/Pet'-type:objectproperties:huntingSkill:type:stringdescription:Themeasuredskillforhuntingenum:-clueless-lazy-adventurous-aggressiverequired:-huntingSkillDog:# "Dog" will be used as the discriminating valuedescription:ArepresentationofadogallOf:-$ref:'#/components/schemas/Pet'-type:objectproperties:packSize:type:integerformat:int32description:thesizeofthepackthedogisfromdefault:0minimum:0required:-packSizecomponents:schemas:genericArrayComponent:$id:fully_generic_arraytype:arrayitems:$dynamicRef:'#generic-array'$defs:allowAll:$dynamicAnchor:generic-arraynumberArray:$id:array_of_numbers$ref:fully_generic_array$defs:numbersOnly:$dynamicAnchor:generic-arraytype:numberstringArray:$id:array_of_strings$ref:fully_generic_array$defs:stringsOnly:$dynamicAnchor:generic-arraytype:stringobjWithTypedArray:$id:obj_with_typed_arraytype:objectrequired:-dataType-dataproperties:dataType:enum:-string-numberoneOf:-properties:dataType:const:stringdata:$ref:array_of_strings-properties:dataType:const:numberdata:$ref:array_of_numbersWhen request bodies or response payloads may be one of a number of different schemas, these should use the JSON SchemaanyOf oroneOf keywords to describe the possible schemas (seeComposition and Inheritance).
A polymorphic schemaMAY include a Discriminator Object, which defines the name of the property that may be used as a hint for which schema of theanyOf oroneOf, or which schema that references the current schema in anallOf, is expected to validate the structure of the model.This hint can be used to aid in serialization, deserialization, and validation.The Discriminator Object does this by implicitly or explicitly associating the possible values of a named property with alternative schemas.
Note thatdiscriminatorMUST NOT change the validation outcome of the schema.
| Field Name | Type | Description |
|---|---|---|
| propertyName | string | REQUIRED. The name of the discriminating property in the payload that will hold the discriminating value. The discriminating propertyMAY be defined as required or optional, but when defined as optional the Discriminator ObjectMUST include adefaultMapping field that specifies which schema is expected to validate the structure of the model when the discriminating property is not present. |
| mapping | Map[string,string] | An object to hold mappings between payload values and schema names or URI references. |
| defaultMapping | string | The schema name or URI reference to a schema that is expected to validate the structure of the model when the discriminating property is not present in the payload or contains a value for which there is no explicit or implicit mapping. |
This objectMAY be extended withSpecification Extensions.
The Discriminator Object is legal only when using one of the composite keywordsoneOf,anyOf,allOf.
In both theoneOf andanyOf use cases, where those keywords are adjacent todiscriminator, all possible schemasMUST be listed explicitly.
To avoid redundancy, the discriminatorMAY be added to a parent schema definition, and all schemas building on the parent schema via anallOf construct may be used as an alternate schema.
TheallOf form ofdiscriminator isonly useful for non-validation use cases; validation with the parent schema with this form ofdiscriminatordoes not perform a search for child schemas or use them in validation in any way.This is becausediscriminator cannot change the validation outcome, and no standard JSON Schema keyword connects the parent schema to the child schemas.
The behavior of any configuration ofoneOf,anyOf,allOf anddiscriminator that is not described above is undefined.
The value of the property named inpropertyName is used as the name of the associated schema under theComponents Object,unless amapping is present for that value.Themapping entry maps a specific property value to either a different schema component name, or to a schema identified by a URI.When using implicit or explicit schema component names, inlineoneOf oranyOf subschemas are not considered.The behavior of amapping value ordefaultMapping value that is both a valid schema name and a valid relative URI reference is implementation-defined, but it isRECOMMENDED that it be treated as a schema name.To ensure that an ambiguous value (e.g."foo") is treated as a relative URI reference by all implementations, authorsMUST prefix it with the"." path segment (e.g."./foo").
Mapping keysMUST be string values, but toolingMAY convert response values to strings for comparison.However, the exact nature of such conversions are implementation-defined.
When the discriminating property is defined as optional, theDiscriminator ObjectMUST include adefaultMapping field that specifies a schema that is expected to validate the structure of the model when the discriminating property is not present in the payload or contains a value for which there is no explicit or implicit mapping. This allows the schema to still be validated correctly even if the discriminating property is missing.
The primary use case for an optional discriminating property is to allow a schema to be extended with a discriminator without breaking existing clients that do not provide the discriminating property.
When the discriminating property is defined as optional, it is important that each subschema that defines a value for the discriminating property also define the property as required, since this is no longer enforced by the parent schema.
ThedefaultMapping schema is also expected to validate the structure of the model when the discriminating property is present but contains a value for which there is no explicit or implicit mapping. This is typically expressed in thedefaultMapping schema by excluding any instances with mapped values of the discriminating property, e.g.
OtherPet:type:objectproperties:petType:not:enum: ['cat','dog']This prevents thedefaultMapping schema from validating a payload that includes the discriminating property with a mapped discriminating value, which would cause a validation to fail when polymorphism is described using theoneOf JSON schema keyword.
For these examples, assume all schemas are in theentry document of the OAD; for handling ofdiscriminator in referenced documents seeResolving Implicit Connections.
In OAS 3.x, a response payloadMAY 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 a valid payload has to match exactly one of the schemas described byCat,Dog, orLizard. Deserialization of aoneOf can be a costly operation, as it requires determining which schema matches the payload and thus should be used in deserialization. This problem also exists foranyOf schemas. Adiscriminator can be used as a “hint” to improve the efficiency of selection of the matching schema. TheDiscriminator Object cannot change the validation result of theoneOf, it can only help make the deserialization more efficient and provide better error messaging. We can specify the exact field that tells us which schema is expected to match the instance:
MyResponseType:oneOf:-$ref:'#/components/schemas/Cat'-$ref:'#/components/schemas/Dog'-$ref:'#/components/schemas/Lizard'discriminator:propertyName:petTypeThe expectation now is that a property with namepetTypeMUST be present in the response payload, and the value will correspond to the name of a schema defined in the OpenAPI Description. Thus the response payload:
{"id":12345,"petType":"Cat"}will indicate that theCat schema is expected to match this payload.
In scenarios where the value of the discriminating property does not match the schema name or implicit mapping is not possible, an optionalmapping definition can be used:
MyResponseType:oneOf:-$ref:'#/components/schemas/Cat'-$ref:'#/components/schemas/Dog'-$ref:'#/components/schemas/Lizard'-$ref:https://gigantic-server.com/schemas/Monster/schema.jsondiscriminator:propertyName:petTypemapping:dog:'#/components/schemas/Dog'monster:https://gigantic-server.com/schemas/Monster/schema.jsonHere the discriminating value ofdog will map to the schema#/components/schemas/Dog, rather than the default (implicit) value of#/components/schemas/dog. If the discriminating value does not match an implicit or explicit mapping, no schema can be determined and validationSHOULD fail.
When used in conjunction with theanyOf construct, the use of the discriminator can avoid ambiguity for serializers/deserializers where multiple schemas may satisfy a single payload.
When the discriminating property is defined as optional, the Discriminator Object has to include adefaultMapping field that specifies a schema of theanyOf oroneOf is expected to validate the structure of the model when the discriminating property is not present in the payload. This allows the schema to still be validated correctly even if the discriminator property is missing.
For example:
MyResponseType:oneOf:-$ref:'#/components/schemas/Cat'-$ref:'#/components/schemas/Dog'-$ref:'#/components/schemas/Lizard'-$ref:'#/components/schemas/OtherPet'discriminator:propertyName:petTypedefaultMapping:OtherPetOtherPet:type:objectproperties:petType:not:enum: ['Cat','Dog','Lizard']In this example, if thepetType property is not present in the payload, or if the value ofpetType is not “Cat”, “Dog”, or “Lizard”, then the payload should validate against theOtherPet schema.
This example shows theallOf usage, which avoids needing to reference all child schemas in the parent:
components:schemas:Pet:type:objectrequired:-petTypeproperties:petType:type:stringdiscriminator:propertyName:petTypemapping:dog:DogCat:allOf:-$ref:'#/components/schemas/Pet'-type:object# all other properties specific to a `Cat`properties:name:type:stringDog:allOf:-$ref:'#/components/schemas/Pet'-type:object# all other properties specific to a `Dog`properties:bark:type:stringLizard:allOf:-$ref:'#/components/schemas/Pet'-type:object# all other properties specific to a `Lizard`properties:lovesRocks:type:booleanValidated against thePet schema, a payload like this:
{"petType":"Cat","name":"Misty"}will indicate that the#/components/schemas/Cat schema is expected to match. Likewise this payload:
{"petType":"dog","bark":"soft"}will map to#/components/schemas/Dog because thedog entry in themapping element maps toDog which is the schema name for#/components/schemas/Dog.
A metadata object that allows for more fine-tuned XML model definitions.When using a Schema Object with XML, if no XML Object is present, the behavior is determined by the XML Object’s default field values.
| Field Name | Type | Description |
|---|---|---|
| nodeType | string | One ofelement,attribute,text,cdata, ornone, as explained underXML Node Types. The default value isnone if$ref,$dynamicRef, ortype: "array" is present in theSchema Object containing the XML Object, andelement otherwise. |
| name | string | Sets the name of the element/attribute corresponding to the schema, replacing the name that was inferred as described underXML Node Names. This fieldSHALL be ignored if thenodeType istext,cdata, ornone. |
| namespace | string | The IRI ([RFC3987]) of the namespace definition. ValueMUST be in the form of a non-relative IRI. |
| prefix | string | The prefix to be used for thename. |
| attribute | boolean | Declares whether the property definition translates to an attribute instead of an element. Default value isfalse. IfnodeType is present, this fieldMUST NOT be present.Deprecated: Use nodeType: "attribute" instead ofattribute: true |
| wrapped | boolean | MAY be used only for an array definition. Signifies whether the array is wrapped (for example,<books><book/><book/></books>) or unwrapped (<book/><book/>). Default value isfalse. The definition takes effect only when defined alongsidetype being"array" (outside theitems). IfnodeType is present, this fieldMUST NOT be present.Deprecated: Use nodeType: "element" instead ofwrapped: true |
Note that when generating an XML document from object data, the order of the nodes is undefined.UseprefixItems to control node ordering as shown underOrdered Elements and Text.
SeeAppendix B for a discussion of converting values of various types to string representations.
This objectMAY be extended withSpecification Extensions.
Each Schema Object describes a particular type of XML [DOM]node which is specified by thenodeType field, which has the following possible values.Except for the special valuenone, these values have numeric equivalents in the DOM specification which are given in parentheses after the name:
element (1): The schema represents an element and describes its contentsattribute (2): The schema represents an attribute and describes its valuetext (3): The schema represents a text node (parsed character data)cdata (4): The schema represents a CDATA sectionnone: The schema does not correspond to any node in the XML document, and the nodes corresponding to its subschema(s) are included directly under its parent schema’s nodeThenone type is useful for JSON Schema constructs that require more Schema Objects than XML nodes, such as a schema containing only$ref that exists to facilitate re-use rather than imply any structure.
For historical compatibility, schemas oftype: "array" default tonodeType: "none", placing the nodes for each array item directly under the parent node.This also aligns with the inferred naming behavior defined underXML Node Names.
To produce an element wrapping the list, set an explicitnodeType: "element" on thetype: "array" schema.When doing so, it is advisable to set an explicit name on either the wrapping element or the item elements to avoid them having the same inferred name.See examples for expected behavior.
If anelement node has a primitive type, then the schema also produces an implicittext node described by the schema for the contents of theelement node named by the property name (orname field).
Explicittext nodes are necessary if an element has both attributes and content.
Note that placing twotext nodes adjacent to each other is ambiguous for parsing, and the resulting behavior is implementation-defined.
Theelement andattribute node types require a name, whichMUST be inferred from the schema as follows, unless overridden by thename field:
schemas field, the component name is the inferred name.schema field, no name can be inferred and an XML Object with aname fieldMUST be present.Note that when using arrays, singular vs plural forms arenot inferred, and must be set explicitly.
Thenamespace field is intended to match the syntax ofXML namespaces, although there are a few caveats:
XML does not, by default, have a concept equivalent tonull, and to preserve compatibility with version 3.1.1 and earlier of this specification, the behavior of serializingnull values is implementation-defined.
However, implementationsSHOULD handlenull values as follows:
xsi:nil="true" attribute.Note that for attributes, this makes either anull value or a missing property serialize to an omitted attribute.As the Schema Object validates the in-memory representation, this allows handling the combination ofnull and a required property.However, because there is no distinct way to representnull as an attribute, it isRECOMMENDED to make attribute properties optional rather than usenull.
To ensure correct round-trip behavior, when parsing an element that omits an attribute, implementationsSHOULD set the corresponding property tonull if the schema allows for that value (e.g.type: ["number", "null"]), and omit the property otherwise (e.g.type: "number").
The Schema Objects are followed by an example XML representation produced for the schema shown.For examples usingattribute orwrapped, please see version 3.1 of the OpenAPI Specification.
Basic string property without an XML Object, usingserializedValue (the remaining examples will useexternalValue so that the XML form can be shown with syntax highlighting):
application/xml:schema:type:objectxml:name:documentproperties:animals:type:stringexamples:pets:dataValue:animals:dog,cat,hamsterserializedValue:| <document> <animals>dog, cat, hamster</animals> </document>Basic string array property (nodeType isnone by default):
application/xml:schema:type:objectxml:name:documentproperties:animals:type:arrayitems:type:stringexamples:pets:dataValue:animals:-dog-cat-hamsterexternalValue:./examples/pets.xmlWhere./examples/pets.xml would be:
<document><animals>dog</animals><animals>cat</animals><animals>hamster</animals></document>application/xml:schema:type:objectxml:name:documentproperties:animals:type:stringxml:name:animalexamples:pets:dataValue:animals:-dog-cat-hamsterexternalValue:./examples/pets.xmlWhere./examples/pets.xml would be:
<document><animal>dog</animal><animal>cat</animal><animal>hamster</animal></document>Note that the name of the root XML element comes from the component name.
components:schemas:Person:type:objectproperties:id:type:integerformat:int32xml:nodeType:attributename:type:stringxml:namespace:https://example.com/schema/sampleprefix:samplerequestBodies:Person:content:application/xml:schema:$ref:"#/components/schemas/Person"examples:Person:dataValue:id:123name:exampleexternalValue:./examples/Person.xmlWhere./examples/Person.xml would be:
<Personid="123"><sample:namexmlns:sample="https://example.com/schema/sample">example</sample:name></Person>Changing the element names:
application/xml:schema:type:objectxml:name:documentproperties:animals:type:arrayitems:type:stringxml:name:animalexamples:pets:dataValue:animals:-dog-cat-hamsterexternalValue:./examples/pets.xmlWhere./examples/pets.xml would be:
<document><animal>dog</animal><animal>cat</animal><animal>hamster</animal></document>Thename field for thetype: "array" schema has no effect because the defaultnodeType for that object isnone:
application/xml:schema:type:objectxml:name:documentproperties:animals:type:arrayxml:name:aliensitems:type:stringxml:name:animalexamples:pets:dataValue:animals:-dog-cat-hamsterexternalValue:./examples/pets.xmlWhere./examples/pets.xml would be:
<document><animal>dog</animal><animal>cat</animal><animal>hamster</animal></document>Even when a wrapping element is explicitly created by settingnodeType toelement, if a name is not explicitly defined, the same name will be used for both the wrapping element and the list item elements:
application/xml:schema:type:objectxml:name:documentproperties:animals:type:arrayxml:nodeType:elementitems:type:stringexamples:pets:dataValue:animals:-dog-cat-hamsterexternalValue:./examples/pets.xmlWhere./examples/pets.xml would be:
<document><animals><animals>dog</animals><animals>cat</animals><animals>hamster</animals></animals></document>To overcome the naming problem in the example above, the following definition can be used:
application/xml:schema:type:objectxml:name:documentproperties:animals:type:arrayxml:nodeType:elementitems:type:stringxml:name:animalexamples:pets:dataValue:animals:-dog-cat-hamsterexternalValue:./examples/pets.xmlWhere./examples/pets.xml would be:
<document><animals><animal>dog</animal><animal>cat</animal><animal>hamster</animal></animals></document>Affecting both wrapping element and item element names:
application/xml:schema:type:objectxml:name:documentproperties:animals:type:arrayxml:name:aliensnodeType:elementitems:type:stringxml:name:animalexamples:pets:dataValue:animals:-dog-cat-hamsterexternalValue:./examples/pets.xmlWhere./examples/pets.xml would be:
<document><aliens><animal>dog</animal><animal>cat</animal><animal>hamster</animal></aliens></document>If we change the wrapping element name but not the item element names:
application/xml:schema:type:objectxml:name:documentproperties:animals:type:arrayxml:name:aliensnodeType:elementitems:type:stringexamples:pets:dataValue:animals:-dog-cat-hamsterexternalValue:./examples/pets.xmlWhere./examples/pets.xml would be:
<document><aliens><aliens>dog</aliens><aliens>cat</aliens><aliens>hamster</aliens></aliens></document>application/xml:schema:type:arrayxml:nodeType:elementname:animalsitems:xml:name:animalproperties:kind:type:stringxml:nodeType:attributename:type:stringxml:nodeType:textexamples:pets:dataValue:-kind:Catname:Fluffy-kind:Dogname:FidoWhere./examples/pets.xml would be:
<animals><animalkind="Cat">Fluffy</animals><animalkind="Dog">Fido</animals><animals>In this example, no element is created for the Schema Object that contains only the$ref, as itsnodeType defaults tonone.It is necessary to create a subschema for the CDATA section as otherwise the content would be treated as an implicit node of typetext.
components:schemas:Documentation:type:objectproperties:content:type:stringcontentMediaType:text/htmlxml:nodeType:cdataresponses:content:application/xml:schema:$ref:"#/components/schemas/Documentation"examples:docs:dataValue:content:<html><head><title>AwesomeDocs</title></head><body></body><html>externalValue:./examples/docs.xmlWhere./examples/docs.xml would be:
<Documentation> <![CDATA[<html><head><title>Awesome Docs</title></head><body></body><html>]]></Documentation>Alternatively, the named root element could be set at the point of use and the root element disabled on the component (note that in this example, the samedataValue is used in two places with different serializations shown withexternalValue):
paths:/docs:get:responses:"200":content:application/xml:schema:xml:nodeType:elementname:StoredDocument$ref:"#/components/schemas/Documentation"examples:stored:dataValue:content:<html><head><title>AwesomeDocs</title></head><body></body><html>externalValue:./examples/stored.xmlput:requestBody:required:truecontent:application/xml:schema:xml:nodeType:elementname:UpdatedDocument$ref:"#/components/schemas/Documentation"examples:updated:dataValue:content:<html><head><title>AwesomeDocs</title></head><body></body><html>externalValue:./examples/updated.xmlresponses:"201": {}components:schemas:Documentation:xml:nodeType:nonetype:objectproperties:content:type:stringcontentMediaType:text/htmlxml:nodeType:cdatawhere./examples/stored.xml would be:
<StoredDocument> <![CDATA[<html><head><title>Awesome Docs</title></head><body></body><html>]]></StoredDocument>and./examples/updated.xml would be:
<UpdatedDocument> <![CDATA[<html><head><title>Awesome Docs</title></head><body></body><html>]]></UpdatedDocument>To control the exact order of elements, use theprefixItems keyword.With this approach, it is necessary to set the element names using the XML Object as they would otherwise all inherit the parent’s name despite being different elements in a specific order.It is also necessary to setnodeType: "element" explicitly on the array in order to get an element containing the sequence.
This first ordered example shows a sequence of elements, as well as the recommended serialization ofnull for elements:
application/xml:schema:xml:nodeType:elementname:OneTwoThreetype:arrayminLength:3maxLength:3prefixItems:-xml:name:Onetype:string-xml:name:Twotype:objectrequired:-unit-valueproperties:unit:type:stringxml:nodeType:attributevalue:type:numberxml:nodeType:text-xml:name:Threetype:-boolean-"null"examples:OneTwoThree:dataValue:-Sometext-unit:cubitsvalue:42null]externalValue:./examples/OneTwoThree.xmlWhere./examples/OneTwoThree.xml would be:
<OneTwoThree><One>Some text</One><Twounit="cubits">42</Two><Threexsi:nil="true" /></OneTwoThree>In this next example, thename needs to be set for the element, while thenodeType needs to be set for the text nodes.
application/xml:schema:xml:nodeType:elementname:Reporttype:arrayprefixItems:-xml:nodeType:texttype:string-xml:name:datatype:number-xml:nodeType:texttype:stringexamples:Report:dataValue:-Somepreambletext.-42-Somepostambletext.externalValue:./examples/Report.xmlWhere./examples/Report.xml would be:
<Report>Some preamble text.<data>42</data>Some postamble text.</Report>Recall that the schema validates the in-memory data, not the XML document itself.This example does not define properties for"related" as it is showing howempty objects andnull are handled.
application/xml:schema:xml:name:producttype:objectrequired:-count-description-relatedproperties:count:type:-number-"null"xml:nodeType:attributerating:type:stringxml:nodeType:attributedescription:type:stringrelated:type:-object-"null"examples:productWithNulls:dataValue:count:nulldescription:Thingrelated:nullexternalValue:./examples/productWithNulls.xmlproductNoNulls:dataValue:count:42description:Thingrelated: {}externalValue:./examples/productNoNulls.xmlWhere./examples/productWithNulls.xml would be:
<product><description>Thing</description><relatedxsi:nil="true" /></product>and./examples/productNoNulls.xml would be:
<productcount="42"><description>Thing</description><related></related></product>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), mutual TLS (use of a client certificate), OAuth2’s common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749], OAuth2 device authorization flow as defined in [RFC8628], and [OpenID-Connect-Core].Please note that as of 2020, the implicit flow is about to be deprecated byOAuth 2.0 Security Best Current Practice. Recommended for most use cases is Authorization Code Grant flow with PKCE.
| Field Name | Type | Applies To | Description |
|---|---|---|---|
| type | string | Any | REQUIRED. The type of the security scheme. Valid values are"apiKey","http","mutualTLS","oauth2","openIdConnect". |
| description | string | Any | A description for security scheme. [CommonMark] syntaxMAY be used for rich text representation. |
| name | string | apiKey | REQUIRED. The name of the header, query or cookie parameter to be used. |
| in | string | apiKey | REQUIRED. The location of the API key. Valid values are"query","header", or"cookie". |
| scheme | string | http | REQUIRED. The name of the HTTP Authentication scheme to be used in the Authorization header as defined in [RFC9110]Section 16.4.1. The values usedSHOULD be registered in theIANA Authentication Scheme registry. The value is case-insensitive, as defined in [RFC9110]Section 11.1. |
| bearerFormat | string | http ("bearer") | 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 | OAuth Flows Object | oauth2 | REQUIRED. An object containing configuration information for the flow types supported. |
| openIdConnectUrl | string | openIdConnect | REQUIRED.Well-known URL to discover the [OpenID-Connect-Discovery]provider metadata. |
| oauth2MetadataUrl | string | oauth2 | URL to the OAuth2 authorization server metadata [RFC8414]. TLS is required. |
| deprecated | boolean | Any | Declares this security scheme to be deprecated. ConsumersSHOULD refrain from usage of the declared scheme. Default value isfalse. |
This objectMAY be extended withSpecification Extensions.
type:httpscheme:basictype:apiKeyname:api-keyin:headertype:httpscheme:bearerbearerFormat:JWTtype:mutualTLSdescription:Certmustbesignedbyexample.comCAtype:oauth2flows:implicit:authorizationUrl:https://example.com/api/oauth/dialogscopes:write:pets:modifypetsinyouraccountread:pets:readyourpetsAllows configuration of the supported OAuth Flows.
| Field Name | Type | Description |
|---|---|---|
| implicit | OAuth Flow Object | Configuration for the OAuth Implicit flow |
| password | OAuth Flow Object | Configuration for the OAuth Resource Owner Password flow |
| clientCredentials | OAuth Flow Object | Configuration for the OAuth Client Credentials flow. Previously calledapplication in OpenAPI 2.0. |
| authorizationCode | OAuth Flow Object | Configuration for the OAuth Authorization Code flow. Previously calledaccessCode in OpenAPI 2.0. |
| deviceAuthorization | OAuth Flow Object | Configuration for the OAuth Device Authorization flow. |
This objectMAY be extended withSpecification Extensions.
Configuration details for a supported OAuth Flow
| Field Name | Type | Applies To | Description |
|---|---|---|---|
| authorizationUrl | string | oauth2 ("implicit","authorizationCode") | REQUIRED. The authorization URL to be used for this flow. ThisMUST be in the form of a URL. The OAuth2 standard requires the use of TLS. |
| deviceAuthorizationUrl | string | oauth2 ("deviceAuthorization") | REQUIRED. The device authorization URL to be used for this flow. ThisMUST be in the form of a URL. The OAuth2 standard requires the use of TLS. |
| tokenUrl | string | oauth2 ("password","clientCredentials","authorizationCode","deviceAuthorization") | REQUIRED. The token URL to be used for this flow. ThisMUST be in the form of a URL. The OAuth2 standard requires the use of TLS. |
| refreshUrl | string | oauth2 | The URL to be used for obtaining refresh tokens. ThisMUST be in the form of a URL. The OAuth2 standard requires the use of TLS. |
| scopes | Map[string,string] | oauth2 | REQUIRED. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The mapMAY be empty. |
This objectMAY be extended withSpecification Extensions.
type:oauth2flows:implicit:authorizationUrl:https://example.com/api/oauth/dialogscopes:write:pets:modifypetsinyouraccountread:pets:readyourpetsauthorizationCode:authorizationUrl:https://example.com/api/oauth/dialogtokenUrl:https://example.com/api/oauth/tokenscopes:write:pets:modifypetsinyouraccountread:pets:readyourpetsLists the required security schemes to execute this operation.
The name used for each propertyMUST either correspond to a security scheme declared in theSecurity Schemes under theComponents Object, or be the URI of a Security Scheme Object.Property names that are identical to a component name under the Components ObjectMUST be treated as a component name.To reference a Security Scheme with a single-segment relative URI reference (e.g.foo) that collides with a component name (e.g.#/components/securitySchemes/foo), use the. path segment (e.g../foo).
Using a Security Scheme component name that appears to be a URI isNOT RECOMMENDED, as the precedence of component-name-matching over URI resolution, which is necessary to maintain compatibility with prior OAS versions, is counter-intuitive. See alsoSecurity Considerations.
A Security Requirement ObjectMAY refer to multiple security schemes in which case all schemesMUST 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 thesecurity field is defined on theOpenAPI Object orOperation Object and contains multiple Security Requirement Objects, only one of the entries in the list needs to be satisfied to authorize the request.This enables support for scenarios where the API allows multiple, independent security schemes.
An empty Security Requirement Object ({}) indicates anonymous access is supported.
| Field Pattern | Type | Description |
|---|---|---|
| {name} | [string] | Each name or URIMUST correspond to a security scheme as described above. If the security scheme is of type"oauth2" or"openIdConnect", then the value is a list of scope names required for the execution, and the listMAY be empty if authorization does not require a specified scope. For other security scheme types, the arrayMAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band. |
See alsoImplicit Connection Resolution Examples inAppendix G: Parsing and Resolution Guidance for an example using Security Requirement Objects in multi-document OpenAPI Descriptions.
api_key: []This example uses a component name for the Security Scheme.
petstore_auth:-write:pets-read:petsThis example uses a relative URI reference for the Security Scheme.
Optional OAuth2 security as would be defined in anOpenAPI Object or anOperation Object:
security:- {}-petstore_auth:-write:pets-read:petsWhile 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 byx-.
| Field Pattern | Type | Description |
|---|---|---|
| ^x- | Any | Allows extensions to the OpenAPI Schema. The field nameMUST begin withx-, for example,x-internal-id. Field names beginningx-oai- andx-oas- are reserved for uses defined by theOpenAPI Initiative. The value can be any valid JSON value (null, a primitive, an array, or an object.) |
The OpenAPI Initiative maintains severalextension registries, including registries forindividual extension keywords andextension keyword namespaces.
Extensions are one of the best ways to prove the viability of proposed additions to the specification.It is thereforeRECOMMENDED that implementations be designed for extensibility to support community experimentation.
Support for any one extension isOPTIONAL, and support for one extension does not imply support for others.
OpenAPI Descriptions use a combination of JSON, YAML, and JSON Schema, and therefore share their security considerations:
In addition, OpenAPI Descriptions are processed by a wide variety of tooling for numerous different purposes, such as client code generation, documentation generation, server side routing, and API testing. OpenAPI Description authors must consider the risks of the scenarios where the OpenAPI Description may be used.
An OpenAPI Description describes the security schemes used to protect the resources it defines. The security schemes available offer varying degrees of protection. Factors such as the sensitivity of the data and the potential impact of a security breach should guide the selection of security schemes for the API resources. Some security schemes, such as basic auth and OAuth Implicit flow, are supported for compatibility with existing APIs. However, their inclusion in OpenAPI does not constitute an endorsement of their use, particularly for highly sensitive data or operations.
The rules for connecting aSecurity Requirement Object to aSecurity Scheme Object under aComponents Object are ambiguous in a way that could be exploited. Specifically:
Some objects in the OpenAPI SpecificationMAY 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 librariesMAY choose to allow access to parts of the documentation based on some form of authentication/authorization.
Two examples of this:
OpenAPI Descriptions may contain references to external resources that may be dereferenced automatically by consuming tools. External resources may be hosted on different domains that may be untrusted.
References in an OpenAPI Description may cause a cycle. Tooling must detect and handle cycles to prevent resource exhaustion.
Certain fields allow the use of Markdown which can contain HTML including script. It is the responsibility of tooling to appropriately sanitize the Markdown.
| Version | Date | Notes |
|---|---|---|
| 3.2.0 | 2025-09-19 | Release of the OpenAPI Specification 3.2.0 |
| 3.1.2 | 2025-09-19 | Patch release of the OpenAPI Specification 3.1.2 |
| 3.1.1 | 2024-10-24 | Patch release of the OpenAPI Specification 3.1.1 |
| 3.1.0 | 2021-02-15 | Release of the OpenAPI Specification 3.1.0 |
| 3.1.0-rc1 | 2020-10-08 | rc1 of the 3.1 specification |
| 3.1.0-rc0 | 2020-06-18 | rc0 of the 3.1 specification |
| 3.0.4 | 2024-10-24 | Patch release of the OpenAPI Specification 3.0.4 |
| 3.0.3 | 2020-02-20 | Patch release of the OpenAPI Specification 3.0.3 |
| 3.0.2 | 2018-10-08 | Patch release of the OpenAPI Specification 3.0.2 |
| 3.0.1 | 2017-12-06 | Patch release of the OpenAPI Specification 3.0.1 |
| 3.0.0 | 2017-07-26 | Release of the OpenAPI Specification 3.0.0 |
| 3.0.0-rc2 | 2017-06-16 | rc2 of the 3.0 specification |
| 3.0.0-rc1 | 2017-04-27 | rc1 of the 3.0 specification |
| 3.0.0-rc0 | 2017-02-28 | Implementer’s Draft of the 3.0 specification |
| 2.0 | 2015-12-31 | Donation of Swagger 2.0 to the OpenAPI Initiative |
| 2.0 | 2014-09-08 | Release of Swagger 2.0 |
| 1.2 | 2014-03-14 | Initial release of the formal document. |
| 1.1 | 2012-08-22 | Release of Swagger 1.1 |
| 1.0 | 2011-08-10 | First release of the Swagger Specification |
Serializing typed data to plain text, which can occur intext/plain message bodies ormultipart parts, as well as in theapplication/x-www-form-urlencoded format in either URL query strings or message bodies, involves significant implementation- or application-defined behavior.
Schema Objects validate data based on theJSON Schema data model, which only recognizes four primitive data types: strings (which areonly broadly interoperable as UTF-8), numbers, booleans, andnull.Notably, integers are not a distinct type from other numbers, withtype: "integer" being a convenience defined mathematically, rather than based on the presence or absence of a decimal point in any string representation.
TheParameter Object,Header Object, andEncoding Object offer features to control how to arrange values from array or object types.They can also be used to control how strings are further encoded to avoid reserved or illegal characters.However, there is no general-purpose specification for converting schema-validated non-UTF-8 primitive data types (or entire arrays or objects) to strings.
Two cases do offer standards-based guidance:
null, are consideredundefined and therefore treated specially in the expansion process when serializing based on that specificationImplementations of RFC6570 often have their own conventions for converting non-string values, but these are implementation-specific and not defined by the RFC itself.This is one reason for the OpenAPI Specification to leave these conversions as implementation-defined: It allows using RFC6570 implementations regardless of how they choose to perform the conversions.
To control the serialization of numbers, booleans, andnull (or other values RFC6570 deems to be undefined) more precisely, schemas can be defined astype: "string" and constrained usingpattern,enum,format, and other keywords to communicate how applications must pre-convert their data prior to schema validation.The resulting strings would not require any further type conversion.
Theformat keyword can assist in serialization.Some formats (such asdate-time) are unambiguous, while others (such asdecimal in theFormat Registry) are less clear.However, care must be taken withformat to ensure that the specific formats are supported by all relevant tools as unrecognized formats are ignored.
Requiring input as pre-formatted, schema-validated strings also improves round-trip interoperability as not all programming languages and environments support the same data types.
Serialization is defined in terms of [RFC6570] URI Templates in three scenarios:
| Object | Condition |
|---|---|
| Parameter Object | Whenschema is present |
| Header Object | Whenschema is present |
| Encoding Object | When encoding forapplication/x-www-form-urlencoded and any ofstyle,explode, orallowReserved are used |
Implementations of this specificationMAY use an implementation of RFC6570 to perform variable expansion, however, some caveats apply.
Note that when usingstyle: "form" RFC6570 expansion to produce anapplication/x-www-form-urlencoded HTTP message body, it is necessary to remove the? prefix that is produced to satisfy the URI query string syntax.
When usingstyle and similar keywords to produce amultipart/form-data body, the query string names are placed in thename parameter of theContent-Disposition part header, and the values are placed in the corresponding part body; the?,=, and& characters are not used, and URI percent encoding is not applied, regardless of the value ofallowReserved.Note that while [RFC7578] allows using [RFC3986] percent-encoding in “file names”, it does not otherwise address the use of percent-encoding within the format.Users are expected to provide names and data with any escaping necessary for conformance with RFC7578 already applied.
Note also that not all RFC6570 implementations support all four levels of operators, all of which are needed to fully support the OpenAPI Specification’s usage.Using an implementation with a lower level of support will require additional manual construction of URI Templates to work around the limitations.
Certain field values translate to RFC6570operators (or lack thereof):
| field | value | equivalent |
|---|---|---|
| style | "simple" | n/a |
| style | "matrix" | ; prefix operator |
| style | "label" | . prefix operator |
| style | "form" | ? prefix operator |
| allowReserved | false | n/a |
| allowReserved | true | + prefix operator |
| explode | false | n/a |
| explode | true | * modifier suffix |
Multiplestyle: "form" parameters are equivalent to a single RFC6570variable list using the? prefix operator:
parameters:-name:fooin:queryschema:type:objectexplode:true-name:barin:queryschema:type:stringThis example is equivalent to RFC6570’s{?foo*,bar}, andNOT{?foo*}{&bar}. The latter is problematic because iffoo is not defined, the result will be an invalid URI.The& prefix operator has no equivalent in the Parameter Object.
Note that RFC6570 does not specify behavior for compound values beyond the single level addressed byexplode. The result of using objects or arrays where no behavior is clearly specified for them is implementation-defined.
Delimiters used by RFC6570 expansion, such as the, used to join arrays or object values withstyle: "simple", are all automatically percent-encoded as long asallowReserved isfalse.Note that since RFC6570 does not define a way to parse variables based on a URI Template, users must take care to first split values by delimiter before percent-decoding values that might contain the delimiter character.
WhenallowReserved istrue, both percent-encoding (prior to joining values with a delimiter) and percent-decoding (after splitting on the delimiter) must be done manually at the correct time.
SeeAppendix E for additional guidance on handling delimiters forstyle values with no RFC6570 equivalent that already need to be percent-encoded when used as delimiters.
Configurations with no direct [RFC6570] equivalentSHOULD also be handled according to RFC6570.ImplementationsMAY create a properly delimited URI Template with variables for individual names and values using RFC6570 regular or reserved expansion (based onallowReserved).
This includes:
pipeDelimited,spaceDelimited, anddeepObject, which have no equivalents at allform withallowReserved: true, which is not allowed because only one prefix operator can be used at a timeThe Parameter Object’sname field has a much more permissive syntax than RFC6570variable name syntax.A parameter name that includes characters outside of the allowed RFC6570 variable character setMUST be percent-encoded before it can be used in a URI Template.
Let’s say we want to use the following data in a form query string, whereformulas is exploded, andwords is not:
formulas:a:x+yb:x/yc:x^ywords:-math-is-funThis array of Parameter Objects uses regularstyle: "form" expansion, fully supported by [RFC6570]:
parameters:-name:formulasin:queryschema:type:objectadditionalProperties:type:stringexplode:true-name:wordsin:queryschema:type:arrayitems:type:stringThis translates to the following URI Template:
{?formulas*,words}when expanded with the data given earlier, we get:
?a=x%2By&b=x%2Fy&c=x%5Ey&words=math,is,funBut now let’s say that (for some reason), we really want that/ in theb formula to show up as-is in the query string, and we want our words to be space-separated like in a written phrase.To do that, we’ll addallowReserved: true toformulas, and change tostyle: "spaceDelimited" forwords:
parameters:-name:formulasin:queryschema:type:objectadditionalProperties:type:stringexplode:trueallowReserved:true-name:wordsin:querystyle:spaceDelimitedexplode:falseschema:type:arrayitems:type:stringWe can’t combine the? and+ RFC6570prefixes, and there’s no way with RFC6570 to replace the, separator with a space character.So we need to restructure the data to fit a manually constructed URI Template that passes all of the pieces through the right sort of expansion.
Here is one such template, using a made-up convention ofwords.0 for the first entry in the words value,words.1 for the second, andwords.2 for the third:
?a={+a}&b={+b}&c={+c}&words={words.0} {words.1} {words.2}RFC6570mentions the use of. “to indicate name hierarchy in substructures,” but does not define any specific naming convention or behavior for it.Since the. usage is not automatic, we’ll need to construct an appropriate input structure for this new template.
We’ll also need to pre-process the values forformulas because while/ and most other reserved characters are allowed in the query string by RFC3986,[,], and#are not, and&,=, and+ all havespecial behavior in theapplication/x-www-form-urlencoded format, which is what we are using in the query string.
SettingallowReserved: true doesnot make reserved characters that are not allowed in URIs allowed, it just allows them to bepassed through expansion unchanged, for example because some other specification has defined a particular meaning for them.
Therefore, users still need to percent-encode any reserved characters that arenot being passed through due to a special meaning because reserved expansion does not know which reserved characters are being used, and which should still be percent-encoded.However, reserved expansion, unlike regular expansion,will leave the pre-percent-encoded triples unchanged.See alsoAppendix E for further guidance on percent-encoding and form media types, including guidance on handling the delimiter characters forspaceDelimited,pipeDelimited, anddeepObject in parameter names and values.
So here is our data structure that arranges the names and values to suit the template above, where values forformulas have[]#&=+ pre-percent encoded (although only+ appears in this example):
a:x%2Byb:x/yc:x^ywords.0:mathwords.1:iswords.2:funExpanding our manually assembled template with our restructured data yields the following query string:
?a=x%2By&b=x/y&c=x%5Ey&words=math%20is%20funThe/ and the pre-percent-encoded%2B have been left alone, but the disallowed^ character (inside a value) and space characters (in the template but outside of the expanded variables) were percent-encoded.
Care must be taken when manually constructing templates to handle the values that RFC6570considers to beundefined correctly:
formulas: {}words:-hello-worldUsing this data with our original RFC6570-friendly URI Template,{?formulas*,words}, produces the following:
?words=hello,worldThis means that the manually constructed URI Template and restructured data need to leave out theformulas object entirely so that thewords parameter is the first and only parameter in the query string.
Restructured data:
words.0:hellowords.1:worldManually constructed URI Template:
?words={words.0} {words.1}Result:
?words=hello%20worldIn this example, the heart emoji is not legal in URI Template names (or URIs):
parameters:-name:❤️in:queryschema:type:stringWe can’t just pass❤️: "love!" to an RFC6570 implementation.Instead, we have to pre-percent-encode the name (which is a six-octet UTF-8 sequence) in both the data and the URI Template:
"%E2%9D%A4%EF%B8%8F":love!{?%E2%9D%A4%EF%B8%8F}This will expand to the result:
?%E2%9D%A4%EF%B8%8F=love%21HTTP headers have inconsistent rules regarding what characters are allowed, and how some or all disallowed characters can be escaped and included.While thequoted-string ABNF rule given in [RFC9110]Section 5.4.6 is the most common escaping solution, it is not sufficiently universal to apply automatically.For example, a strongETag looks like"foo" (with quotes, regardless of the contents), and a weakETag looks likeW/"foo" (note that only part of the value is quoted); the contents of the quotes for this header are also not escaped in the wayquoted-string contents are.
For this reason, any data being passed to a header by way of aParameter orHeader Object needs to be quoted and escaped prior to passing it to the OAS implementation, and the parsed header values are expected to contain the quotes and escapes.
[RFC6570]'s percent-encoding behavior is not always appropriate forin: "cookie" parameters.While percent-encoding seems more common as an escaping mechanism than the base64 encoding (contentEncoding: “base64”) recommended by [RFC6265],section 5.6 of draft-ietf-httpbis-rfc6265bis-20, the proposed update to that RFC notes that cookies sent in theSet-Cookie response header that appear to be percent-encodedMUST NOT be decoded when stored by the client, which would mean that they are already encoded when retrieved from that storage for use in theCookie request header.The behavior ofstyle: "cookie" assumes this usage, anddoes not apply or remove percent-encoding.
If automatic percent-encoding is desired,style: "form" with a primitive value or with the non-defaultexplode value offalse provides this behavior.However, note that the default value ofexplode: true forstyle: "form" with non-primitive values uses the wrong delimiter for cookies (& instead of; followed by a single space) to set multiple cookie values.Usingstyle: "form" within: "cookie" via an RFC6570 implementation requires stripping the? prefix, as when producingapplication/x-www-form-urlencoded message bodies.To allow the full use ofstyle: "form" within: "cookie", use theallowReserved field.
NOTE: In this section, theapplication/x-www-form-urlencoded andmultipart/form-data media types are abbreviated asform-urlencoded andform-data, respectively, for readability.
Percent-encoding is used in URIs and media types that derive their syntax from URIs.The fundamental rules of percent-encoding are:
+ character is decoded depends on whether you are usingapplication/x-www-form-urlencoded rules or more general URI rules; this is the only time where choice of decoding algorithm can change the outcome.The rest of this appendix provides more detailed guidance based on the above rules.
This process is concerned with three classes of characters, the names of which vary among specifications but are defined as follows for the purposes of this section:
form-urlencoded defines special behavior for=,&, and+)Unless otherwise specified, this section uses RFC3986’s definition ofreserved andunreserved, and defines the unsafe set as all characters not included in either of those sets.
Each URI component (such as the query string) considers some of the reserved characters to be unsafe, either because they serve as delimiters between the components (e.g.#), or (in the case of[ and]) were historically considered globally unsafe but were later given reserved status for limited purposes.
Reserved characters with no special meaning defined within a component can be left un-percent encoded.However, other specifications can define special meanings, requiring percent-encoding for those characters outside of the additional special meanings.
Theform-urlencoded media type defines special meanings for= and& as delimiters, and+ as the replacement for the space character (instead of its percent-encoded form of%20).This means that while these three characters are reserved-but-allowed in query strings by RFC3986, they must be percent-encoded inform-urlencoded query strings except when used for theirform-urlencoded purposes; seeAppendix C for an example of handling+ in form values.
[RFC7578]Section 2 suggests RFC3986-based percent-encoding as a mechanism to keep text-based per-part header data such as file names within the ASCII character set.This suggestion was not part of older (pre-2015) specifications forform-data, so care must be taken to ensure interoperability.Users wishing to use percent-encoding in this wayMUST provide the data in percent-encoded form, as percent-encoding is not automatically applied for this media type regardless of which Encoding Object fields are used.
Theform-data media type allows arbitrary text or binary data in its parts, so percent-encoding or similar escaping is not needed in general.
URI percent encoding and theform-urlencoded media type have complex specification histories spanning multiple revisions and, in some cases, conflicting claims of ownership by different standards bodies.Unfortunately, these specifications each define slightly different percent-encoding rules, which need to be taken into account if the URIs orform-urlencoded message bodies will be subject to strict validation.(Note that many URI parsers do not perform validation by default, if at all.)
This specification normatively cites the following relevant standards:
| Specification | Date | OAS Usage | Percent-Encoding | Notes |
|---|---|---|---|---|
| [RFC3986] | 01/2005 | URI/URL syntax, including non-form-urlencoded content-based serialization | [RFC3986] | obsoletes [RFC1738], [RFC2396] |
| [RFC6570] | 03/2012 | style-based serialization | [RFC3986] | does not use+ for query strings |
| WHATWG-URL Section 5 | “living” standard | content-basedform/url-encoded serialization, including HTTP message contents | WHATWG-URL Section 1.3 | obsoletes [RFC1866], [HTML401] |
Style-based serialization with percent-encoding is used in theParameter Object whenschema is present, and in theEncoding Object when at least one ofstyle,explode, orallowReserved is present.SeeAppendix C for more details of RFC6570’s two different approaches to percent-encoding, including an example involving+.
Content-based serialization is defined by theMedia Type Object, and used with theParameter Object andHeader Object when thecontent field is present, and with theEncoding Object based on thecontentType field when the fieldsstyle,explode, andallowReserved are absent.For use in URIs, each part is encoded based on the media type (e.g.text/plain orapplication/json), and must then be percent-encoded for use in aform-urlencoded string (in form-style query strings), or for general URI use in other URL components, unless the media type already incorporates URI percent-encoding.
Prior versions of this specification required [RFC1866] and its use of [RFC1738] percent-encoding rules in place of [WHATWG-URL].The [WHATWG-URL]form-urlencoded rules represent the current browser consensus on that media type, and avoid the ambiguity introduced by unclear paraphrasing of RFC1738 in RFC1866.
Users needing conformance with RFC1866/RFC1738 are advised to check their tooling and library behavior carefully.
WHATWG is aweb browser-oriented standards group that has defined a “URL Living Standard” for parsing and serializing URLs in a browser context, including parsing and serializingform-urlencoded data.WHATWG’s percent-encoding rules for query strings are different depending on whether the query string isbeing treated asform-urlencoded (where it requires more percent-encoding than [RFC1738]) oras part of the generic syntax, where its requirements differ from [RFC3986].
This specification only depends on WHATWG for itsform-urlencoded specification.Implementations using the query string in other ways are advised that, the distinctions between WHATWG’s non-form-urlencoded query string rules and RFC3986 require careful consideration, incorporating both WHATWG’s percent-encoding sets and their set of valid Unicode code points for URLs; seePercent-Encoding and Illegal or Reserved Delimiters for more information.
The percent-decoding algorithm does not care which characters were or were not percent-decoded, which means that URIs percent-encoded according to any specification will be decoded correctly.
Similarly, allform-urlencoded decoding algorithms simply add+-for-space handling to the percent-decoding algorithm, and will work regardless of the encoding specification used.
However, care must be taken to useform-urlencoded decoding if+ represents a space, and to use regular percent-decoding if+ represents itself as a literal value.
The[,],|, and space characters, which are used as delimiters for thedeepObject,pipeDelimited, andspaceDelimited styles, respectively, allMUST be percent-encoded to comply with [RFC3986].This requires users to pre-encode the character(s) in some other way in parameter names and values to distinguish them from the delimiter usage when using one of these styles.
The space character is always illegal and encoded in some way by all implementations of all versions of the relevant standards.While one could use theform-urlencoded convention of+ to distinguish spaces in parameter names and values fromspaceDelimited delimiters encoded as%20, the specifications define the decoding as a single pass, making it impossible to distinguish the different usages in the decoded result unless a non-standard parsing algorithm is used that separates based on one delimiter before decoding the other.Any such non-standard parsing approach will not be interoperable across all tools.
Some environments use[,], and possibly| unencoded in query strings without apparent difficulties.WHATWG’s generic query string rules do not require percent-encoding them in non-form-urlencoded query strings, although it also excludes them from the set of valid URL Unicode code points.Code that relies on leaving these delimiters unencoded, while using regular percent-encoding for them within names and values, is not guaranteed to be interoperable across all implementations.
For maximum interoperability, it isRECOMMENDED to either define and document an additional escape convention while percent-encoding the delimiters for these styles, or to avoid these styles entirely.The exact method of additional encoding/escaping is left to the API designer, and is expected to be performed before serialization and encoding described in this specification, and reversed after this specification’s encoding and serialization steps are reversed.This keeps it outside of the processes governed by this specification.
This section shows each of the four possible sources of base URIs, followed by an example with a relative$self and$id.
A base URI within the resource’s content ([RFC3986]Section 5.1.1) is the highest-precedence source of a base URI.For OpenAPI documents, this source is the OpenAPI Object’s$self field, while for Schema Objects that contain a$id, or are a subschema of a Schema Object containing a$id, the source is the$id field:
Assume the retrieval URI of the following document isfile://home/someone/src/api/openapi.yaml:
openapi:3.2.0$self:https://example.com/api/openapiinfo:title:ExampleAPIversion:1.0paths:/foo:get:requestBody:$ref:"shared/foo#/components/requestBodies/Foo"Assume the retrieval URI for the following document ishttps://git.example.com/shared/blob/main/shared/foo.yaml:
openapi:3.2.0$self:https://example.com/api/shared/fooinfo:title:SharedcomponentsforallAPIsversion:1.0components:requestBodies:Foo:content:application/json:schema:$ref:../schemas/fooschemas:Foo:$id:https://example.com/api/schemas/fooproperties:bar:$ref:barBar:$id:https://example.com/api/schemas/bartype:stringIn this example, the retrieval URIs are irrelevant because both documents define$self.
The relative$ref in the first document is resolved against$self to producehttps://example.com/api/shared/foo#/components/requestBodies/Foo.The portion of that URI before the# matches the$self of the second document, so the reference target is resolved to#/components/requestBodies/Foo in that second document.
In that document, the$ref in the Request Body Object is resolved using that document’s$self as the base URI, producinghttps://example.com/api/schemas/foo.This matches the$id at#/components/schemas/Foo/$id so it points to that Schema Object.That Schema Object has a subschema with$ref: bar, which is resolved against the$id to producehttps://example.com/api/schemas/bar, which matches the$id at#/components/schemas/Bar/$id.
To guarantee interoperability, Schema Objects containing an$id, or that are under a schema containing an$id,MUST be referenced by the nearest such$id for the non-fragment part of the reference.As the JSON Schema specification notes, using a base URI other than the nearest$id and crossing that$id with a JSON Pointer fragmentis not interoperable.
Note also that it is impossible for the reference at#/components/schemas/Foo/properties/bar/$ref to reference the schema at#/components/schemas/Bar usingonly a JSON Pointer fragment, as the JSON Pointer would be resolved relative tohttps://example.com/api/schemas/foo, not to the OpenAPI document’s base URI from$self.
If no base URI can be determined within the content, the next location to search is any encapsulating entity ([RFC3986]Section 5.1.2).
This is common for Schema Objects encapsulated within an OpenAPI document.An example of an OpenAPI Object itself being encapsulated in another entity would be amultipart/related archive ([RFC2557]), such as the followingmultipart/related; boundary="boundary-example"; type="application/openapi+yaml" document.Note that this is purely an example, and support for such multipart documents or any other format that could encapsulate an OpenAPI Object is not a requirement of this specification.
RFC2557 was written to allow sending hyperlinked sets of documents as email attachments, in which case there would not be a retrieval URI for the multipart attachment (although the format could also be used in HTTP as well).
--boundary-exampleContent-Type: application/openapi+yamlContent-Location: https://example.com/api/openapi.yamlopenapi: 3.2.0info: title: Example API version: 1.0 externalDocs: url: docs.htmlcomponents: requestBodies: Foo: content: application/json: schema: $ref: "#/components/api/schemas/Foo" schemas: Foo: properties: bar: $ref: schemas/bar--boundary-exampleContent-Type: application/schema+jsonContent-Location: https://example.com/api/schemas/bar{ "type": "string"}--boundary-exampleContent-Type: text/htmlContent-Location: https://example.com/api/docs.html<html> <head> <title>API Documentation</title> </head> <body> <p>Awesome documentation goes here</p> </body></html>--boundary-exampleIn this example, the URI for each part, which also serves as its base URI, comes from the part’sContent-Location header as specified by RFC2557.Since the Schema Object at#/components/schemas/Foo does not contain an$id, the reference in its subschema uses the OpenAPI document’s base URI, which is taken from theContent-Location header of its part within themultipart/related format.The resulting reference tohttps://example.com/schemas/bar matches theContent-Location header of the second part, which according to RFC2557 allows the reference target to be located within the multipart archive.
Similarly, theurl field of theExternal Documentation Object is resolved against the base URI fromContent-Location, producinghttps://example.com/api/docs.html which matches theContent-Location of the third part.
If no base URI is provided from either of the previous sources, the next source is the retrieval URI ([RFC3986]Section 5.1.3).
Assume this document was retrieved fromhttps://example.com/api/openapis.yaml:
openapi:3.2.0info:title:ExampleAPIversion:1.0components:requestBodies:Foo:content:application/json:schema:$ref:schemas/fooAssume this document was retrieved fromhttps://example.com/api/schemas/foo:
{"type":"object","properties":{"bar":{"type":"string"}}}Resolving the$ref: schemas/foo against the retrieval URI of the OpenAPI document produceshttps://example.com/api/schemas/foo, the retrieval URI of the JSON Schema document.
When constructing an OpenAPI document in memory that does not have a$self, or an encapsulating entity, or a retrieval URI, applications can resolve internal (fragment-only) references by assuming a default base URI ([RFC3986]Section 5.1.4).While this sort of internal resolution can be performed in practice without choosing a base URI, choosing one, such as a URN with a randomly generated UUID (e.g.urn:uuid:f26cdaad-3193-4398-a838-4ecb7326c4c5) avoids the need to implement it as a special case.
Let’s re-consider the first example in this appendix, but with relative URI references for$self and$id, and retrieval URIs that support that relative usage:
Assume that the following is retrieved fromhttps://staging.example.com/api/openapi:
openapi:3.2.0$self:/api/openapiinfo:title:ExampleAPIversion:1.0paths:/foo:get:requestBody:$ref:"shared/foo#/components/requestBodies/Foo"Assume the retrieval URI for the following document ishttps://staging.example.com/api/shared/foo:
openapi:3.2.0$self:/api/shared/fooinfo:title:SharedcomponentsforallAPIsversion:1.0components:requestBodies:Foo:content:application/json:schema:$ref:../schemas/fooschemas:Foo:$id:/api/schemas/fooproperties:bar:$ref:barBar:$id:/api/schemas/bartype:stringIn this example, all of the$self and$id values are relative URI references consisting of an absolute path.This allows the retrieval URI to set the host (and scheme), in this casehttps://staging.example.com, resulting in the first document’s$self beinghttps://staging.example.com/openapi, and the second document’s$self beinghttps://staging.example.com/api/shared/foo, with$id values ofhttps://staging.example.com/api/schemas/foo andhttps://staging.example.com/api/schemas/bar.Relative$self and$id values of this sort allow the same set of documents to work when deployed to other hosts, e.g.https://example.com (production) orhttps://localhost:8080 (local development).
ImplementationsMAY support complete-document parsing in any of the following ways:
openapi fieldAdditional mechanisms can be used to support documents with Objects other than an OpenAPI Object or a Schema Object at the root, but note that the resulting behavior is implementation-defined:
Implementations that parse referenced fragments of OpenAPI content without regard for the content of the rest of the containing document will miss keywords that change the meaning and behavior of the reference target.In particular, failing to take into account keywords that change the base URI introduces security risks by causing references to resolve to unintended URIs, with unpredictable results.While some implementations support this sort of parsing due to the requirements of past versions of this specification, in version 3.1 and later, the result of parsing fragments in isolation isundefined and likely to contradict the requirements of this specification.
While it is possible to structure certain OpenAPI Descriptions to ensure that they will behave correctly when references are parsed as isolated fragments, depending on this isNOT RECOMMENDED.This specification does not explicitly enumerate the conditions under which such behavior is safe and provides no guarantee for continued safety in any future versions of the OAS.
JSON or YAML objects within an OAD are interpreted as specific Objects (such asOperation Objects,Response Objects,Reference Objects, etc.) based on their context. Depending on how references are arranged, a given JSON or YAML object can be interpreted in multiple different contexts:
If the same JSON/YAML object is parsed multiple times and the respective contexts require it to be parsed asdifferent Object types, the resulting behavior isimplementation defined, andMAY be treated as an error if detected. An example would be referencing an empty Schema Object under#/components/schemas where a Path Item Object is expected, as an empty object is valid for both types. For maximum interoperability, it isRECOMMENDED that OpenAPI Description authors avoid such scenarios.
The following Objects and Fields involve the use of implicit connections:
| Source | Target | Alternative |
|---|---|---|
Security Requirement Object{name} | Security Scheme Object name under theComponents Object | n/a |
Discriminator Objectmapping(implicit, or explicit name syntax) | Schema Object name under the Components Object | mapping(explicit URI syntax) |
Operation Objecttags | Tag Objectname (in theOpenAPI Object’stags array) | n/a |
Link ObjectoperationId | Operation ObjectoperationId | operationRef |
An additional implicit connection involves appending the templated URL paths of thePaths Object to the appropriateServer Object’surl field.This connection is unambiguous because only the entry document’s Paths Object contributes URLs to the described API.
The implicit connections in the Security Requirement Object and Discriminator Object rely on thecomponent name, which is the name of the property holding the component in the appropriately typed sub-object of the Components Object.For example, the component name of the Schema Object at#/components/schemas/Foo isFoo.The implicit connection oftags in the Operation Object uses thename field of Tag Objects, which (like the Components Object) are found under the root OpenAPI Object.This means resolving component names and tag names both depend on starting from the correct OpenAPI Object.
For resolving component and tag name connections from a referenced (non-entry) document, it isRECOMMENDED that tools resolve from the entry document, rather than the current document.Resolving component and tag name connections from a referenced (non-entry) document to the entry document as recommended underResolving Implicit Connections allows components and Tag Objects to be defined next to the API’s deployment information in the top-level array of Server Objects and treated as an interface for referenced documents to access.
For Security Requirement Objects and Discriminator Objects, it is also possible to keep the resolution within the referenced document by using the URI-reference form that these Objects offer.
There are no URI-based alternatives for the Operation Object’stags field.OAD authors are advised to use external solutions such as the OpenAPI Initiative’s Overlay Specification to simulate sharingTag Objects across multiple documents.
This section shows how to retrieve an HTTP-accessible multi-document OpenAPI Description (OAD) and resolve aSecurity Requirement Object in the referenced (non-entry) document.The behavior for Discriminator Object non-URI mappings and for the Operation Object’stags field operate on the same principles.
First, theentry document is where parsing begins. It defines theMySecurity security scheme to be JWT-based, and it defines a Path Item as a reference to a component in another document:
GET/api/description/openapiHTTP/1.1Host:www.example.comAccept:application/openapi+json"components":{"securitySchemes":{"MySecurity":{"type":"http","scheme":"bearer","bearerFormat":"JWT"}}},"paths":{"/foo":{"$ref":"other#/components/pathItems/Foo"}}GET/api/description/openapiHTTP/1.1Host:www.example.comAccept:application/openapi+yamlcomponents:securitySchemes:MySecurity:type:httpscheme:bearerbearerFormat:JWTpaths:/foo:$ref:'other#/components/pathItems/Foo'This entry document references another document,other, without using a file extension. This gives the client the flexibility to choose an acceptable format on a resource-by-resource basis, assuming both representations are available:
GET/api/description/otherHTTP/1.1Host:www.example.comAccept:application/openapi+json"components":{"securitySchemes":{"MySecurity":{"type":"http","scheme":"basic"}},"pathItems":{"Foo":{"get":{"security":["MySecurity":[]]}}}}GET/api/description/otherHTTP/1.1Host:www.example.comAccept:application/openapi+yamlcomponents:securitySchemes:MySecurity:type:httpscheme:basicpathItems:Foo:get:security:-MySecurity: []In theother document, the referenced path item has a Security Requirement for a Security Scheme,MySecurity. The same Security Scheme exists in the original entry document. As outlined inResolving Implicit Connections,MySecurity is resolved with animplementation-defined behavior, but the section formally recommends that tools resolve component names from theentry document. As with all implementation-defined behavior, it is important to check tool documentation to determine which behavior is supported.