OpenAPI Specification: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 10: Line 10:


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 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'''.
=Endpoint=


=TO REVIEW=
=TO REVIEW=

Revision as of 21:00, 25 January 2024

External

Internal

Overview

OpenAPI Specification (OAS), formerly Swagger Specification, is an API description format for 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.


Endpoint

TO REVIEW

An OpenAPI file allows you to describe the entire API, including:

  • Available endpoints and operations on each endpoint.
  • Input and output parameters for each operation.
  • Authentication methods.
  • Contact information, license, terms of use, etc.


The document addresses both OpenAPI 2.0 and OpenAPI 3.0. The differences will be emphasized.

Swagger Java Model

SwaggerJavaModel.png

info

title

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.

paths

Contains a map of paths.

Path

The path is designated by its literal, as key in the paths map. Each path contains zero or one of these operations: GET, POST, PUT, HEAD, DELETE, PATCH, OPTIONS, a list of Parameters and a map of vendor extensions.

Operation

OpenAPI 2.0 Operation
paths:
  /a:
    get:
      parameters:
        - name: 'test'
          in: query
          type: 'string'
      responses:
        200:
          schema:
            $ref: '#/definitions/Empty'
definitions:
  Empty:
    type: object

Also see:

Amazon API Gateway Integration

Valid operation keys:

  • get
  • put
  • post
  • delete
  • options
  • head
  • patch

parameters

Contains a list of in-line declaration of parameters (parameter objects) and references.

responses

responses Object

A required element that list all possible 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:
     responses:
       200:
         ...
       default: 
         ...

produces

Contains a list of media types this operation can respond with. The list specified at operation level overrides the list specified on global level. Document that.

paths:
 /a:
   get:
     produces:
       - application/json

Note that Swagger Core Operation.getProduces() may return null.

consumes

Note that Swagger Core Operation.getConsumes() may return null.

tags

Grouping Operations with Tags

Each API 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.

tags:
  -name: tag-a
   description: Something that would shed light on tag-a semantics
   externalDocs:
    url: http://example.com/my-docs/tag-a.html
   
paths:
  /a:
    get:
      tags:
        - tag-a
        - other-tag

Path Templating

Path templating refers to the usage of curly braces ({}) to mark a section of a URL path as replaceable using path parameters.

Parameter

Parameter Object

There are five parameter types: path, query, request header, request body and form parameters. All parameters use the following fields in their declaration:

  • name
  • in
  • required
  • description
  • 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 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:
         - name: id
           in: path
           type: string
           required: true
           description: "some description"

Also see:

REST Path Parameters

Query Parameter

Also see:

REST Query Parameters

Request Header

Also see:

REST Request Headers

Request Body

Also see:

REST Request Body

Form

Response

Response Object
Describing Responses in OpenAPI 2.0

A response is defined by its HTTP status code and the data returned in the response body and/or headers.

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'

description

The description is required. Represents a short description of the response.

Response Body

schema

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 $ref. This is useful if multiple responses share the same schema.

For reference models (RefModel), model.setReference("RefName") puts the model in the correct state to refer to:

definitions:
  RefName:
    type: ...

In-line schema:

responses:
  200:
    description: something
    schema:
      type: object
      properties:
        id:
          type: integer
          description: The user ID.
        username:
          type: string
          description: The user name.

This is an example that uses references:

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.
"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.

headers

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 x-amazon-apigateway-integration, it has to be declared in the headers section for the corresponding response, otherwise a template error is generated.

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'

Reference Object

$ref

Data Types

Data Types

Basic Types

string

number

integer

boolean

array

object

CORS

CORS in Swagger

More:

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"]]