Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

OpenAPI Specification Basics

OpenAPI Specification Basics

The OpenAPI Specification (OAS) is a standard format used to describe RESTful APIs.

The OpenAPI Specification allows developers to define the structure, parameters, responses, and other information of an API in a machine-readable way.

The OpenAPI Specification was originally called the Swagger Specification, and was later donated to the OpenAPI Initiative and renamed OpenAPI.

The main functions of the OpenAPI Specification include:

There are currently two widely used versions of OpenAPI:

  1. OpenAPI 2.0 (formerly Swagger 2.0)
  2. OpenAPI 3.x (latest stable version)

It is recommended that new projects use OpenAPI 3.x, because it provides more features and improvements.

The Structure of the OpenAPI Specification

OpenAPI documents are usually written in YAML or JSON format.

Below is a basic OpenAPI document structure:

Example

openapi: 3.1.0 # OpenAPI version

info:

  title: Sample API # API name

  description: This is a sample API document

  version: 1.0.0 # API version

servers:

  - url: https://api.example.com/v1 # API server address

    description: Production environment

  - url: https://dev-api.example.com/v1

    description: Development environment

paths: # API path definitions

  /users: # endpoint path

    get: # HTTP method

      summary: Get all users

      description: Returns the list of all users in the system

      operationId: getUsers

      tags:

        - users # group label

      parameters: # request parameters

        - name: limit

          in: query

          description: Maximum number of returned results

          schema:

            type: integer

            default: 20

      responses: # response definitions

        '200': # HTTP status code

          description: Successfully returned user list

          content:

            application/json:

              schema:

                type: array

                items:

                  $ref: '#/components/schemas/User'

        '400':

          description: Invalid request parameters

components: # reusable components

  schemas: # data model definitions

    User:

      type: object

      properties:

        id:

          type: integer

          format: int64

        name:

          type: string

        email:

          type: string

          format: email

      required:

        - id

        - name


OpenAPI Core Concepts Explained

1. Document Metadata (info)

The info section contains basic API information such as title, description, version, etc.:

Example

info:

  title: User Management API

  description: API for managing user information in the system

  version: 1.0.0

  contact:

    name: API Support Team

    email: support@example.com

  license:

    name: Apache 2.0

    url: https://www.apache.org/licenses/LICENSE-2.0.html

2. Server Information (servers)

The servers section defines the list of available API servers:

Example

servers:

  - url: https://api.example.com/v1

    description: Production environment

  - url: https://staging-api.example.com/v1

    description: Test environment

3. Paths (paths)

The paths section defines all API endpoints and the HTTP methods they support:

Example

paths:

  /users:

    get:

      # Get user list

    post:

      # Create new user

  /users/{userId}:

    get:

      # Get specific user

    put:

      # Update user

    delete:

      # Delete user

4. Operations (operations)

Each HTTP method under a path defines an API operation:

Example

paths:

  /users/{userId}:

    get:

      summary: Get user details

      description: Get detailed user information based on user ID

      operationId: getUserById

      tags:

        - users

      parameters:

        - name: userId

          in: path

          required: true

          description: User ID

          schema:

            type: integer

      responses:

        '200':

          description: Successfully retrieved user information

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/User'

        '404':

          description: User does not exist

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

5. Parameters (parameters)

Parameters can be defined in multiple locations:

Example

parameters:

  - name: userId

    in: path # path parameter

    required: true

    schema:

      type: integer

  - name: filter

    in: query # query parameter

    schema:

      type: string

  - name: X-API-Key

    in: header # header parameter

    schema:

      type: string

  - name: trace

    in: cookie # cookie parameter

    schema:

      type: string

6. Request Body (requestBody)

Define the request body for methods such as POST and PUT:

Example

requestBody:

  description: User data

  required: true

  content:

    application/json:

      schema:

        $ref: '#/components/schemas/User'

    application/x-www-form-urlencoded:

      schema:

        $ref: '#/components/schemas/UserForm'

7. Responses (responses)

Define the possible responses for each operation:

Example

responses:

  '200':

    description: Operation successful

    content:

      application/json:

        schema:

          $ref: '#/components/schemas/SuccessResponse'

  '400':

    description: Invalid request parameters

    content:

      application/json:

        schema:

          $ref: '#/components/schemas/ErrorResponse'

8. Components (components)

The components section is used to store elements that can be reused throughout the API document:

Example

components:

  schemas:

    User:

      type: object

      properties:

        id:

          type: integer

        name:

          type: string

        email:

          type: string

          format: email

        roles:

          type: array

          items:

            type: string

            enum: [admin, user, editor]

      required:

        - name

        - email

   

    Error:

      type: object

      properties:

        code:

          type: integer

        message:

          type: string

      required:

        - code

        - message

 

  securitySchemes:

    ApiKeyAuth:

      type: apiKey

      in: header

      name: X-API-Key

   

    OAuth2:

      type: oauth2

      flows:

        implicit:

          authorizationUrl: https://example.com/oauth/authorize

          scopes:

            read: read permission

            write: write permission

9. Data Models (schemas)

Define the data structures used in the API:

Example

schemas:

  Product:

    type: object

    properties:

      id:

        type: integer

      name:

        type: string

        maxLength: 100

      price:

        type: number

        format: float

        minimum: 0

      category:

        type: string

        enum: [electronics, books, clothing]

10. Security (security)

Define the authentication and authorization methods for the API:

Example

security:

  - ApiKeyAuth: []

  - OAuth2: [read, write]


Create a complete OpenAPI document example

Below is a more complete e-commerce API example:

Example

openapi: 3.1.0

info:

  title: E-commerce API

  description: API for managing products and orders in an online store

  version: 1.0.0

  contact:

    name: API Support Team

    email: support@example.com

    url: https://api.example.com/support

  license:

    name: MIT

    url: https://opensource.org/licenses/MIT

servers:

  - url: https://api.example.com/v1

    description: Production environment

  - url: https://dev-api.example.com/v1

    description: Development environment

tags:

  - name: products

    description: Product-related operations

  - name: orders

    description: Order-related operations

  - name: users

    description: User-related operations

paths:

  /products:

    get:

      summary: Get product list

      description: Returns a list of all available products, with support for pagination and filtering

      operationId: getProducts

      tags:

        - products

      parameters:

        - name: category

          in: query

          description: Filter by product category

          schema:

            type: string

        - name: page

          in: query

          description: Page number

          schema:

            type: integer

            default: 1

        - name: limit

          in: query

          description: Items per page

          schema:

            type: integer

            default: 20

      responses:

        '200':

          description: Successfully retrieved product list

          content:

            application/json:

              schema:

                type: object

                properties:

                  total:

                    type: integer

                  products:

                    type: array

                    items:

                      $ref: '#/components/schemas/Product'

        '400':

          description: Invalid parameters

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

   

    post:

      summary: Create new product

      description: Create new product information

      operationId: createProduct

      tags:

        - products

      security:

        - ApiKeyAuth: []

        - OAuth2: [write]

      requestBody:

        required: true

        content:

          application/json:

            schema:

              $ref: '#/components/schemas/ProductCreate'

      responses:

        '201':

          description: Product created successfully

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Product'

        '400':

          description: Invalid request data

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

        '401':

          description: Unauthorized

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

  /products/{productId}:

    get:

      summary: Get product details

      description: Get detailed information for a specific product by ID

      operationId: getProductById

      tags:

        - products

      parameters:

        - name: productId

          in: path

          required: true

          description: Product ID

          schema:

            type: integer

      responses:

        '200':

          description: Successfully retrieved product information

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Product'

        '404':

          description: Product does not exist

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

   

    put:

      summary: Update product

      description: Update information for a specific product

      operationId: updateProduct

      tags:

        - products

      security:

        - ApiKeyAuth: []

        - OAuth2: [write]

      parameters:

        - name: productId

          in: path

          required: true

          description: Product ID

          schema:

            type: integer

      requestBody:

        required: true

        content:

          application/json:

            schema:

              $ref: '#/components/schemas/ProductUpdate'

      responses:

        '200':

          description: Product updated successfully

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Product'

        '400':

          description: Invalid request data

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

        '401':

          description: Unauthorized

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

        '404':

          description: Product does not exist

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

   

    delete:

      summary: Delete product

      description: Delete a specific product

      operationId: deleteProduct

      tags:

        - products

      security:

        - ApiKeyAuth: []

        - OAuth2: [write]

      parameters:

        - name: productId

          in: path

          required: true

          description: Product ID

          schema:

            type: integer

      responses:

        '204':

          description: Product deleted successfully

        '401':

          description: Unauthorized

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

        '404':

          description: Product does not exist

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

  /orders:

    get:

      summary: Get order list

      description: Returns a list of all orders, with support for pagination and filtering

      operationId: getOrders

      tags:

        - orders

      security:

        - ApiKeyAuth: []

        - OAuth2: [read]

      parameters:

        - name: status

          in: query

          description: Filter by order status

          schema:

            type: string

            enum: [pending, processing, shipped, delivered, cancelled]

        - name: page

          in: query

          description: Page number

          schema:

            type: integer

            default: 1

        - name: limit

          in: query

          description: Items per page

          schema:

            type: integer

            default: 20

      responses:

        '200':

          description: Successfully retrieved order list

          content:

            application/json:

              schema:

                type: object

                properties:

                  total:

                    type: integer

                  orders:

                    type: array

                    items:

                      $ref: '#/components/schemas/Order'

        '401':

          description: Unauthorized

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

   

    post:

      summary: Create new order

      description: Create a new order

      operationId: createOrder

      tags:

        - orders

      security:

        - ApiKeyAuth: []

        - OAuth2: [write]

      requestBody:

        required: true

        content:

          application/json:

            schema:

              $ref: '#/components/schemas/OrderCreate'

      responses:

        '201':

          description: Order created successfully

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Order'

        '400':

          description: Invalid request data

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

        '401':

          description: Unauthorized

          content:

            application/json:

              schema:

                $ref: '#/components/schemas/Error'

components:

  schemas:

    Product:

      type: object

      properties:

        id:

          type: integer

          format: int64

          readOnly: true

        name:

          type: string

          maxLength: 100

        description:

          type: string

        price:

          type: number

          format: float

          minimum: 0

        category:

          type: string

          enum: [electronics, books, clothing, food]

        inStock:

          type: boolean

          default: true

        createdAt:

          type: string

          format: date-time

          readOnly: true

        updatedAt:

          type: string

          format: date-time

          readOnly: true

      required:

        - name

        - price

        - category

   

    ProductCreate:

      type: object

      properties:

        name:

          type: string

          maxLength: 100

        description:

          type: string

        price:

          type: number

          format: float

          minimum: 0

        category:

          type: string

          enum: [electronics, books, clothing, food]

        inStock:

          type: boolean

          default: true

      required:

        - name

        - price

        - category

   

    ProductUpdate:

      type: object

      properties:

        name:

          type: string

          maxLength: 100

        description:

          type: string

        price:

          type: number

          format: float

          minimum: 0

        category:

          type: string

          enum: [electronics, books, clothing, food]

        inStock:

          type: boolean

   

    Order:

      type: object

      properties:

        id:

          type: integer

          format: int64

          readOnly: true

        userId:

          type: integer

          format: int64

        items:

          type: array

          items:

            $ref: '#/components/schemas/OrderItem'

        totalAmount:

          type: number

          format: float

          readOnly: true

        status:

          type: string

          enum: [pending, processing, shipped, delivered, cancelled]

          default: pending

        shippingAddress:

          $ref: '#/components/schemas/Address'

        createdAt:

          type: string

          format: date-time

          readOnly: true

        updatedAt:

          type: string

          format: date-time

          readOnly: true

      required:

        - userId

        - items

        - shippingAddress

   

    OrderCreate:

      type: object

      properties:

        userId:

          type: integer

          format: int64

        items:

          type: array

          items:

            $ref: '#/components/schemas/OrderItem'

        shippingAddress:

          $ref: '#/components/schemas/Address'

      required:

        - userId

        - items

        - shippingAddress

   

    OrderItem:

      type: object

      properties:

        productId:

          type: integer

          format: int64

        quantity:

          type: integer

          minimum: 1

          default: 1

        unitPrice:

          type: number

          format: float

          readOnly: true

      required:

        - productId

        - quantity

   

    Address:

      type: object

      properties:

        street:

          type: string

        city:

          type: string

        state:

          type: string

        zipCode:

          type: string

        country:

          type: string

      required:

        - street

        - city

        - state

        - zipCode

        - country

   

    Error:

      type: object

      properties:

        code:

          type: integer

        message:

          type: string

      required:

        - code

        - message

 

  securitySchemes:

    ApiKeyAuth:

      type: apiKey

      in: header

      name: X-API-Key

   

    OAuth2:

      type: oauth2

      flows:

        implicit:

          authorizationUrl: https://example.com/oauth/authorize

          scopes:

            read: read permission

            write: write permission

security:

  - ApiKeyAuth: []


Basic Syntax of the OpenAPI Specification

The OpenAPI specification supports two formats:

  1. YAML (recommended)
  2. JSON

YAML Format Example

Example

openapi: 3.0.0

info:

  title: Pet Store API

  version: 1.0.0

paths:

  /pets:

    get:

      summary: List all pets

      responses:

        '200':

          description: Successfully retrieved pet list

JSON Format Example

Example

"openapi"

:

"3.0.0"

,

 

"info"

:

{

   

"title"

:

"Pet Store API"

,

   

"version"

:

"1.0.0"

 

}

,

 

"paths"

:

{

   

"/pets"

:

{

     

"get"

:

{

       

"summary"

:

"List all pets"

,

       

"responses"

:

{

         

"200"

:

{

           

"description"

:

"Successfully retrieved pet list"

         

}

       

}

     

}

   

}

 

}

}

How to Use the OpenAPI Specification

1. Create and Edit OpenAPI Documents

You can use the following tools to create and edit OpenAPI documents:

2. Documentation Generation

Using the OpenAPI specification, you can automatically generate elegant API documentation. Common tools include:

3. Code Generation

OpenAPI can automatically generate client and server code in multiple languages:

4. API Testing and Mocking

The OpenAPI specification can also be used for:

Best Practices

1. Design Principles

2. Documentation Recommendations

3. Versioning Strategy

Frequently Asked Questions

1. What is the difference between OpenAPI and Swagger?

Swagger is the predecessor of the OpenAPI specification. In 2016, the Swagger specification was donated to the Linux Foundation and renamed the OpenAPI specification. Today, "Swagger" usually refers to the toolset built around the OpenAPI specification.

2. What are the main differences between OpenAPI 2.0 and 3.x?

OpenAPI 3.x introduced many new features, including:

3. How to handle authentication and authorization?

OpenAPI supports multiple security mechanisms:

Learning resources

  1. Official documentation:OpenAPI Initiative
  2. Tools:
  3. Swagger Editor
  4. Swagger UI
  5. OpenAPI Generator
  6. - [Swagger Editor](https://editor.swagger.io/) - [Swagger UI](https://swagger.io/tools/swagger-ui/) - [OpenAPI Generator](https://openapi-generator.tech/)
    1. Learning Resources:
    2. OpenAPI Specification
    3. Swagger Tutorial
    4. - [OpenAPI Specification](https://spec.openapis.org/oas/latest.html) - [Swagger Tutorial](https://swagger.io/docs/specification/basic-structure/)