OpenAPI Specification: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(53 intermediate revisions by the same user not shown)
Line 8: Line 8:
* [[REST and Hypermedia]]
* [[REST and Hypermedia]]
* [[Amazon_API_Gateway_Concepts#Integration_and_Swagger_Operations|Amazon API Gateway Integration]]
* [[Amazon_API_Gateway_Concepts#Integration_and_Swagger_Operations|Amazon API Gateway Integration]]
* [[JSON_Schema#Overview|JSON Schema]]


=Overview=
=Overview=
Line 15: Line 16:
The OpenAPI specification describes [[#Endpoint|endpoints]] and [[#Operation|operations]] for each endpoint, input and output [[#Parameter|parameters]] for each operation, [[#security|authentication methods]], contact information, licenses, etc.
The OpenAPI specification describes [[#Endpoint|endpoints]] and [[#Operation|operations]] for each endpoint, input and output [[#Parameter|parameters]] for each operation, [[#security|authentication methods]], contact information, licenses, etc.


=Specification Elements=
OpenAPI specification builds upon [[JSON_Schema#Overview|JSON Schema]].
==Endpoint==
 
=<span id='Endpoint'></span>Endpoints=
An endpoint is exposed in the OpenAPI specification by its relative path, declared in the <code>[[#paths|paths]]</code> map.
An endpoint is exposed in the OpenAPI specification by its relative path, declared in the <code>[[#paths|paths]]</code> map.


<font color=darkkhaki>Refactor this.</font>
==Resource==
<font color=darkkhaki>Refactor this.</font>
<font color=darkkhaki>Refactor this.</font>


Line 66: Line 65:
==<tt>servers</tt>==
==<tt>servers</tt>==
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#serverObject}}
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#serverObject}}
<syntaxhighlight lang='yaml'>
servers:
  - url: https://petstore.swagger.io/v2
</syntaxhighlight>
==<tt>paths</tt>==
==<tt>paths</tt>==
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathsObject}}
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathsObject}}
Line 90: Line 94:
Contains a map of relative '''paths''' to individual [[#Endpoint|endpoints]].  
Contains a map of relative '''paths''' to individual [[#Endpoint|endpoints]].  


<span id='Path'></span>Each '''path name''' must start with a forward slash "/". The path is appended to the expanded URL from the server object <code>url</code> field in order to construct the full URL. [[#Path_Templating|Path templating]] is allowed. Each path accepts zero or more of the available [[#Operations|operations]] (<code>get</code>, <code>put</code>, <code>post</code>, <code>delete</code>, <code>options</code>, <code>head</code>, <code>patch</code>, <code>trace</code>) and <code>parameters</code>, which is a list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at operation level but cannot be removed there. A unique parameter is defined by a combination of a name and a location.
===Path===
For syntax of individual path specifications, see:
 
{{Internal|OpenAPI Specification Path#Overview|OpenAPI Specification Path}}


==<tt>components</tt>==
==<tt>components</tt>==
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#componentsObject}}
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#componentsObject}}
<font size=-2>
components:
  [[#schemas|schemas]]:
    Pet:
      [...]
    Error:
      [...]
</font>
===<tt>schemas</tt>===
The <code>/components/schemas</code> section of the OpenAPI specification defines reusable objects.
{{Internal|OpenAPI Specification Schemas#Overview|OpenAPI Specification Schemas}}
==<tt>webhooks</tt>==
==<tt>webhooks</tt>==
A map of path item objects or reference objects.  
A map of path item objects or reference objects.  
Line 100: Line 119:
==<tt>tags</tt>==
==<tt>tags</tt>==
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#tagObject}}
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#tagObject}}
=Path Templating=
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathTemplating}}
Path templating refers to the usage of curly braces <code>{}</code> to mark a section of a URL path as replaceable using [[#Path_Parameters|path parameters]].
=<span id='Operation'></span>Operations=
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operationObject}}
An '''operation''' represents a single HTTP operation on a [[#Path|path]].
<font size=-2>
get|put|post|delete|options|head|patch|trace:
  summary:
  description:
  [[#Parameters|parameters]]:
  [[#Responses|responses]]:
  tags:
  operationId:
  [[#RequestBody|requestBody]]:
  callbacks:
  security:
  servers:
  deprecated:
</font>
==Responses==
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#responses-object}}
The <code>responses</code> field is required and lists all possible HTTP responses that may result from executing this operation. The element must contain at least one response code. The definition is not expected to cover all possible HTTP response codes, because they may not be known in advance. However, the definition should cover a successful operation response and any known errors. The "default" map key may be used as a default response object for all HTTP codes that are not covered individually in the definition.
<syntaxhighlight lang='yaml'>
paths:
/a:
  get:
    responses:
      200:
        [...]
      default:
        [...]
</syntaxhighlight>
==RequestBody==
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#request-body-object}}
=<span id='Parameter'></span>Parameters=
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterObject}}
<font size=-2>
get:
  [...]
  parameters:
    - [[#Parameter_Name|name]]: id
      in: [[#Path_Parameters|path]]|[[#Query_Parameters|query]]|[[#Header_Parameters|header]]|[[#Cookie_Parameters|cookie]]
      description:
      required: true|false
      deprecated: true|false
      [[#allowEmptyValue|allowEmptyValue]]: true|false
      [[#Parameter_Schema|schema]]: [...]
    - [...]
</font>
An operation accepts multiple '''parameters'''.
A unique parameter is defined by a combination of its <span id='Parameter_Name'></span>'''name''', defined as value of the <code>name</code> field, and its '''location''', defined as value of the <code>in</code> field. The <code>name</code> value is required and case sensitive.
There are four possible parameter locations: "[[#Query_Parameters|query]]", "[[#Header_Parameters|header]]", "[[#Path_Parameters|path]]", "[[#Cookie_Parameters|cookie]]".
==Parameter Locations==
===Path Parameters===
A path parameter is declared as <code>in: path</code> in the OpenAPI specification file, and is a URL fragment at the left side of the question mark in the URL. For "path" parameters, the parameter name must correspond to a [[#Path_Templating|template expression]] occurring in the <code>path</code> field. Also, the <code>required</code> property is required and the value must be <code>true</code>.
===Query Parameters===
A query parameter is declared as <code>in: query</code> in the OpenAPI specification file, and it is an URL fragment that follows the question mark in the full URL.
<span id='allowEmptyValue'></span><code>allowEmptyValue</code> field is valid only for query parameters and allows sending a parameter with an empty value. The default value is <code>false</code>. Use of this property is not recommended and it is likely to be removed in a later revision.
===Header Parameters===
Header parameters are key value pairs that can be used to configure the behavior of the API.
===Cookie Parameters===
==Parameter Schema==
=Examples=
==<tt>GET</tt> with Empty Response Body==
<syntaxhighlight lang='yaml'>
paths:
  /a:
    get:
      parameters:
        - name: test
          in: query
          type: string
      responses:
        200:
          schema:
            $ref: '#/definitions/Empty'
definitions:
  Empty:
    type: object
</syntaxhighlight>
=TODEPLETE=
<font color=darkkhaki>
====<tt>parameters</tt>====
Contains a list of in-line declaration of [[#Parameter|parameters]] (parameter objects) and references.
====<tt>responses</tt>====
{{External|[https://swagger.io/specification/#responsesObject responses Object]}}
A required element that list all possible [[#Response|responses]] that are returned from executing this operations. The element must contain at least one response code. The container  maps a HTTP response code to the expected response. The definition is not expected to cover all possible HTTP response codes, because they may not be known in advance. However, the definition should cover a successful operation response and any known errors. The "default" map key may be used as a default response object for all HTTP codes that are not covered individually in the definition.
paths:
  /a:
    get:
      <font color=teal>'''responses'''</font>:
        <font color=teal>'''200</font>:
          ...
        <font color=teal>'''default</font>:
          ...
====<tt>produces</tt>====
Contains a list of media types this operation can respond with. The list specified at operation level overrides the list specified on global level. <font color=darkgray>Document that.</font>
paths:
  /a:
    get:
      <font color=teal>'''produces'''</font>:
        - application/json
Note that Swagger Core Operation.getProduces() may return null.
====<tt>consumes</tt>====
Note that Swagger Core Operation.getConsumes() may return null.
====<span id='Tags'></span><tt>tags</tt>====
{{External|[https://swagger.io/docs/specification/grouping-operations-with-tags/ Grouping Operations with Tags]}}
Each API [[#Operation|operation]] can be annotated with a list of tags. Tagged operations may be handled differently by tools and libraries. Optionally, each tag can get a "description" and an "externalDocs" in the global "tags" section on the root level. The tag names here should match those used in operations. The tag order in the global tags section also controls the default sorting in the UI - at least, for Swagger UI. It is possible to use a tag at operation level even if it is not specified on the root level.
<font color=teal>'''tags'''</font>:
  -name: tag-a
    description: Something that would shed light on tag-a semantics
    externalDocs:
    url: http&#58;//example.com/my-docs/tag-a.html
   
paths:
  /a:
    get:
      <font color=teal>'''tags'''</font>:
        - tag-a
        - other-tag
=Parameter=
{{External|[https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject Parameter Object]}}
There are five parameter types: [[#Path_Parameter|path]], [[#Query_Parameter|query]], [[#Request_Header|request header]], [[#Request_Body|request body]] and [[#Form|form]] parameters. All parameters use the following fields in their declaration:
* <span id='parameter_name'></span>'''name'''
* <span id='parameter_in'></span>'''in'''
* <span id='parameter_required'></span>'''required'''
* <span id='parameter_description'></span>'''description'''
* <span id='parameter_type'></span>'''type'''. If "in" is any value other than "body", the type is required, and it is limited to simple types, not object. The value must be one of the following: "string", "number", "integer", "boolean", "array" or "file".
==Path Parameter==
Path parameters are used together with [[#Path_Templating|path templating]]  where  the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. A path parameter is required. Example:
/query/{'''id'''}
Representation:
paths:
  /query/{id}:
    ''operation'':
        parameters:
          - [[#parameter_name|name]]: id
            [[#parameter_in|in]]: <font color=teal>'''path'''</font>
            [[#parameter_type|type]]: string
            [[#parameter_required|required]]: true
            [[#parameter_description|description]]: "some description"
Also see: {{Internal|REST_and_Hypermedia#Path_Parameter|REST Path Parameters}}
==Query Parameter==
Also see: {{Internal|REST_and_Hypermedia#Query_Parameter|REST Query Parameters}}
==Request Header==
Also see: {{Internal|REST_and_Hypermedia#Request_Header|REST Request Headers}}
==Request Body==
Also see: {{Internal|REST_and_Hypermedia#Request_Body|REST Request Body}}
==Form==
=Response=
{{External|[https://swagger.io/specification/#responseObject Response Object]}}
{{External|[https://swagger.io/docs/specification/2-0/describing-responses/ Describing Responses in OpenAPI 2.0]}}
A response is defined by its HTTP status code and the data returned in the [[#Response_Body|response body]] and/or [[#Response_Headers|headers]].
<syntaxhighlight lang='yaml'>
200:
  description: 200 response
  schema:
    $ref: '#/definitions/Empty'
    originalRef: '#/definitions/Empty'
  headers:
    Access-Control-Allow-Origin:
      type: 'string'
    Access-Control-Allow-Methods:
      type: 'string'
    Access-Control-Allow-Headers:
      type: 'string'
</syntaxhighlight>
====<tt>description</tt>====
The description is required. Represents a short description of the response.
==Response Body==
====<tt>schema</tt>====
The schema keyword is used to describe the response body. A schema may define:
* a primitive type such as "string" or "number", used for plain text responses. Note that Amazon API Gateway warns if it encounters a primitive type.
* an object
* an array – typically used with JSON and XML APIs
* a file
* a reference - the schema can be defined in-line or defined at the root level of the document and referenced via [[#.24ref|$ref]]. This is useful if multiple responses share the same schema.
For reference models (<code>RefModel</code>), <tt>model.setReference("RefName")</tt> puts the model in the correct state to refer to:
<syntaxhighlight lang='yaml'>
definitions:
  RefName:
    type: ...
</syntaxhighlight>
In-line schema:
<syntaxhighlight lang='yaml'>
responses:
  200:
    description: something
    schema:
      type: object
      properties:
        id:
          type: integer
          description: The user ID.
        username:
          type: string
          description: The user name.
</syntaxhighlight>
This is an example that uses references:
<syntaxhighlight lang='yaml'>
responses:
  200:
    description: something
    schema:
      $ref: '#/definitions/User'
...
definitions:
  User:
    type: object
    properties:
      id:
        type: integer
        description: The user ID.
      username:
        type: string
        description: The user name.
</syntaxhighlight>
"responseSchema" is sometimes used, but that seems to be deprecated.
===Empty Response Body===
For responses that have no body, like 204 No Content, no "schema" should be specified. This is conventionally treated as no-body response.
==Response Headers==
Responses can include custom headers, or headers that implement a protocol like [[#CORS|CORS]].
====<tt>headers</tt>====
The custom headers must be declared, under the "headers" section of the response. For OpenAPI 2.0, there is no way in Swagger to define common response headers for different response codes or different API operations. You need to define the headers for each response individually. "headers" is aA container that maps a header name to its definition. The header names are case insensitive. If a header is specified by the an extension, such as [[Amazon_API_Gateway_Extension_to_OpenAPI#x-amazon-apigateway-integration|x-amazon-apigateway-integration]], it has to be declared in the [[#headers|headers]] section for the corresponding response, otherwise a template error is generated.
<syntaxhighlight lang='yaml'>
200:
  description: 200 response
  ...
  headers:
    Access-Control-Allow-Origin:
      type: 'string'
    Access-Control-Allow-Methods:
      type: 'string'
    Access-Control-Allow-Headers:
      type: 'string'
  schema:
    $ref: '#/definitions/Empty'
    originalRef: '#/definitions/Empty'
</syntaxhighlight>
=Reference Object=
=$ref=
=Data Types=
=Data Types=
{{External|https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#data-types}}
OAS data types are based on those supported by [https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-4.2.1 JSON Schema Specification Draft 2020-12]
{| class="wikitable" style="text-align: left;"
! Type
! Format
! Comments
|-
| null ||  || A JSON "null" value. JSON Schema Specification type.
|-
| boolean ||  || A "true" or "false" value. JSON Schema Specification type.
|-
| object ||  || An unordered set of properties mapping a string to an instance. JSON Schema Specification type.
|-
| array ||  || An ordered list of instances. JSON Schema Specification type.
|-
| number ||  || An arbitrary-precision, base-10 decimal number value. JSON Schema Specification type.
|-
| string ||  || A string of Unicode code points. JSON Schema Specification type.
|-
| integer || int32 || Signed 32 bits. Introduced by OAS.
|-
| integer || int64 || Signed 64 bits (long). Introduced by OAS.
|-
| number || float || Introduced by OAS.
|-
| number || double || Introduced by OAS.
|-
| string || password || A hint to UIs to obscure input. Introduced by OAS.
|-
| string || date || See github.com/oapi-codegen/runtime/types/date.go
|-
| string || email || See github.com/oapi-codegen/runtime/types/email.go
|-
| string || file || See github.com/oapi-codegen/runtime/types/file.go
|-
| string || uuid || See github.com/oapi-codegen/runtime/types/uuid.go
|-
|}


{{External|[https://swagger.io/docs/specification/data-models/data-types/ Data Types]}}
=<tt>$ref</tt>=
 
=OpenAPI Operation Declaration and Implementation Examples=
==Basic Types==
{{Internal|OpenAPI_Specification_Path#Operation_Declaration_and_Implementation_Examples|OpenAPI Examples}}
 
===string===
===number===
===integer===
===boolean===
===array===
===object===
 
=CORS=
 
{{External|[https://swagger.io/docs/open-source-tools/swagger-ui/usage/cors/ CORS in Swagger]}}
 
More: {{Internal|Cross-Origin_Resource_Sharing|CORS}}
 
=Organizatorium=
 
==x-nullable==
 
Appears in automatically generated Swagger files, as such:
 
definitions:
    LibraryAccount:
      type: object
      required:
      - name
      properties:
        name:
          type: string
          '''x-nullable''': '''true'''
 
definitions:
  A:
    type: string
    title: A
    '''x-nullable''': '''true'''
 
When used for an API Gateway import, it errors out as:
 
Unable to create model for 'LibraryAccount': Invalid model specified: Validation Result: warnings : [], errors : [Invalid model schema specified. Unsupported keyword(s): ["x-nullable"]]

Latest revision as of 03:51, 27 January 2024

External

Internal

Overview

OpenAPI Specification (OAS), formerly Swagger Specification, is an API description format and a specification standard for HTTP REST APIs. The specification for an API can be expressed in a single file, which provides the source of truth for the API, starting with the API design phase, then continuing with client and server code generation, documentation and testing. The specification format is programming language agnostic, it is machine-readable and it can be used to generate code in different languages. API specifications are typically written in YAML or JSON. The latest version at the time of this writing is OpenAPI 3.1.0.

The OpenAPI specification describes endpoints and operations for each endpoint, input and output parameters for each operation, authentication methods, contact information, licenses, etc.

OpenAPI specification builds upon JSON Schema.

Endpoints

An endpoint is exposed in the OpenAPI specification by its relative path, declared in the paths map.

Refactor this.

Document Structure

openapi: 3.1.0
info: 
  [...]
servers:
   [...]
paths:
   [...]
components:
   [...]
webhooks:
   [...]
security:
   [...]
tags:
   [...]

openapi

The string following the openapi element is the version number of the OpenAPI specification this document uses.

info

https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#infoObject

info:
  title: OpenAPI Example
  version: 0.2.0
  summary: An OpenAPI example application 
  description:
  termsOfService:
  contact:
  license:

title

Required element. Represents the title of the API. When imported in AWS API Gateway, the title provides the API name, unless the AWS::ApiGateway::RestApi resource explicitly specifies a title, in which case the title specified by AWS::ApiGateway::RestApi will take priority.

version

Required element. Represents the version of the API document. It is different from openapi version string.

summary

A short summary of the API.

description

A description of the API. CommonMark syntax may be used for rich text representation.

servers

https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#serverObject
servers:
  - url: https://petstore.swagger.io/v2

paths

https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathsObject

paths:
 /a:
    summary:
    description: 
    get: [...]
    put: [...]
    post: [...]
    delete: [...]
    options: [...]
    head: [...]
    patch: [...]
    trace: [...]
    servers:
    parameters:
 /b:
   [...]
 /c:
   [...]

Contains a map of relative paths to individual endpoints.

Path

For syntax of individual path specifications, see:

OpenAPI Specification Path

components

https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#componentsObject

components:
  schemas:
    Pet:
      [...]
    Error:
      [...]

schemas

The /components/schemas section of the OpenAPI specification defines reusable objects.

OpenAPI Specification Schemas

webhooks

A map of path item objects or reference objects.

security

https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#securityRequirementObject

tags

https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#tagObject

Data Types

https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#data-types

OAS data types are based on those supported by JSON Schema Specification Draft 2020-12

Type Format Comments
null A JSON "null" value. JSON Schema Specification type.
boolean A "true" or "false" value. JSON Schema Specification type.
object An unordered set of properties mapping a string to an instance. JSON Schema Specification type.
array An ordered list of instances. JSON Schema Specification type.
number An arbitrary-precision, base-10 decimal number value. JSON Schema Specification type.
string A string of Unicode code points. JSON Schema Specification type.
integer int32 Signed 32 bits. Introduced by OAS.
integer int64 Signed 64 bits (long). Introduced by OAS.
number float Introduced by OAS.
number double Introduced by OAS.
string password A hint to UIs to obscure input. Introduced by OAS.
string date See github.com/oapi-codegen/runtime/types/date.go
string email See github.com/oapi-codegen/runtime/types/email.go
string file See github.com/oapi-codegen/runtime/types/file.go
string uuid See github.com/oapi-codegen/runtime/types/uuid.go

$ref

OpenAPI Operation Declaration and Implementation Examples

OpenAPI Examples