Create API specification Document with Open API 3.0

Overview

When two systems become to interact with each other through API, the most use of API is its document. The developer tend to go through the document from getting start guide, core concept, till the example of its usage for enhance the development. Without clear and complete documentation, the developer will struggle to use API and it will become useless. Therefore, API documentation is a key important for communication between API provider and API consumer. In this article, I'm going to introduce OpenAPI specification and Redoc to generate a beautiful, easy to find and simple to use API specification documentation.

Introduction

My name is Vorthanak from System Development department. I graduated from a university in Cambodia. This is my second year working in auカブコム証券. Recently, I've been involved with kabuステーション®API specification, which currently is using Swagger 2.0 and Redoc. However, swagger 2.0 is too old to be able to integrate with some peripheral tools, One of kabu STATION API|auカブコム証券's users has requested in API community for support OpenAPI specification ver.3.0 and this is where I get start using OpenAPI ver.3.0 and experience some tools that can be used with it.

Getting start

Before we can get start, we need to have some basic idea about the OpenAPI Specification and Redoc first.

What is OpenAPI Specification?

OpenAPI specification is known as an open-source framework that use to build a descriptive RESTFul API specification document. It is a newer version of swagger specification. The latest version of OpenAPI is 3.0.3. The definition of OpenAPI can be written in YAML or JSON. The definition file let us to define:

  • Authentication mechanism
  • Available API endpoints
  • Endpoints request method (GET, POST, PUT)
  • Input parameters (Header parameters, Request Body, Query parameters and Path parameters)
  • Response result
  • Other contact information, API license, terms and conditions etc.

Official site: OpenAPI Specification - Version 3.0.3 | Swagger

What is Redoc?

Redoc is a javascript based API document generation tool. It is one of the most powerful free docs tools that allows to generate a beautiful 3 interactive layouts design API document from OpenAPI specification without needs of server.

You can Find more information on REST OpenAPI Reference Docs · Redocly

Walkthrough OpenAPI specification and Redoc

As I mention, kabuステーション®API is using swagger 2.0 for its specification. In this article, I'm going to use kabuステーション®API specification that I upgrade it from swagger 2.0 to OpenAPI 3.0 as an example and I will introduce some useful third party tools that can integrate with OpenAPI 3.0.

Prerequisite
  • Knowledge of YAML or JSON for OpenAPI specification definition
  • Get Redoc installed on your computer for API documentation generation.
Create an OpenAPI definition

Since OpenAPI definition can be created either in YAML or JSON format, you can choose the one you familiar with. In here, I'm going to use YAML format to write definition. This YAML file is divided into three sections.

  • Meta information : It contained the information such as version of the OpenAPI, Info object that contained version, title, contact, servers, swagger extension etc. Below is the example meta information of kabu Station API definition in OpenAPI ver.3.0.
openapi: 3.0.0
info:
  version: "1.5"
  title: kabuステーションAPI
  contact:
    url: ../ptal/index.html
  x-logo:
    url: ../ptal/content/image/common/logo.png
  servers:
    - url: http://localhost:18080/kabusapi/
tags:
  - name: auth
    description: APIトークンを発行します。
    x-displayName: 認証

※ Note: API definition is required to specify version of OpenAPI at the beginning for it uses.

version definition
swagger ver. 2.0 swagger : 2.0.0
OpenAPI Ver.3.0 openapi : 3.0.0
  • Path : You can define your API endpoints in path. It allows you to specify HTTP verb for manipulate the resource of the API. The endpoint is indicate to the server of the API. To start define path, you need to follow rules and hierarchy structure of OpenAPI specification. It must start with paths: as parent, then endpoint, HTTP method, and response. The indentation is a very important rule that need follow, otherwise it will return error when you generate it to a document. In example below, I defined POST method of /token endpoint. So client will use POST http://localhost:18080/kabusapi/token .
paths:
  /token:
    post:
      tags:
        - auth
      summary: トークン発行
      description: |-
        APIトークンを発行します。
        発行したトークンは有効である限り使用することができ、リクエストごとに発行する必要はありません。
        発行されたAPIトークンは以下のタイミングで無効となります。
        ・kabuステーションを終了した時
        ・kabuステーションからログアウトした時
        ・別のトークンが新たに発行された時
        <br>※kabuステーションは早朝、強制的にログアウトいたしますのでご留意ください。
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RequestToken"
        required: true
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TokenSuccess"
        "400":
          description: BadRequest
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
        "404":
          description: NotFound
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
        "500":
          description: InternalServerError
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

In term of HTTP request, you may need to send parameters and request body to server. Hence, OpenAPI allow to describe parameters and Request body sections inside operation/path.

You can describe request body under requestBody key section. The attribute that required for request body form are content, media type (application/json, application/xml etc.), Body content/schema and others attribute such as description, required. See example:

      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RequestRegister"
        description: 登録する銘柄のリスト
        required: true

To describe the parameter, you need to specify name: , location, datatype, and other additional attribute like required, description. There are 4 kind of parameters that you can use. You can distinguish them based on location in: .

Parameter Type Key example
path parameter in: path /wallet/cash/{symbol}
query parameter in: query /positions?product=1
header parameter in: header X-API-KEY: xxxxxxxxxx
cookie parameter in: cookie

For more details: Describing Parameters

Below is the example to describe parameters.

      parameters:
        - name: X-API-KEY
          in: header
          description: トークン発行メソッドで取得した文字列
          required: true
          schema:
            type: string
        - name: exchange
          in: path
          description: |-
            市場コード
            |定義値|説明|
            |-|-|
            |1|東証|
            |3|名証|
            |5|福証|
            |6|札証|
            |2|日通し|
            |23|日中|
            |24|夜間|
          required: true
          schema:
            type: string
            format: ""
            enum:
              - 1
              - 3
              - 5
              - 6
              - 2
              - 23
              - 24
        - name: product
          in: query
          description: |-
            取得する商品
            |定義値|説明|
            |-|-|
            |0|すべて|
            |1|現物|
            |2|信用|
            |3|先物|
            |4|OP|
          required: false
  • Components : You can define common schemas, parameters, request body, response, example, link, enum etc., as a reusable component in this section. Components is a solution that OpenAPI design to reduce redundancy source code. It can be used in multiple endpoint if they are in common. To define component, you can follow example below.
components:
  schemas:
    RequestToken:
      type: object
      required:
        - APIPassword
      properties:
        APIPassword:
          description: APIパスワード
          type: string
          example: xxxxxx
  TokenSuccess:
      type: object
      properties:
        ResultCode:
          description: 結果コード<br>0が成功。それ以外はエラーコード。
          type: integer
          format: int32
          example: 0
        Token:
          description: APIトークン
          type: string
          example: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Using component help you reduce a lot of time spend on writing the same thing again and again. In order to call the component to use, you can simply assign$ref: "#/components/your component" to the endpoint.

For further knowledge, Please visit swagger.io

Generate API document from Definition file with Redoc

With only few simple steps, we can generate a beautiful interactive UI from OpenAPI definition with Redoc. You have option install redoc to use in your local machine or use CDN.

Install Redoc

using npm:

npm -i redoc

using yarn:

yarn add redoc

Reference redoc script in HTML for deployment. For CDN:

 <script src="https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js"> </script>

For npm:

<script src="node_modules/redoc/bundles/redoc.standalone.js"> </script>

Deployment

Create an index.html and reference Definition file and redoc to body.

<!DOCTYPE html>
<html>
  <head>
    <title>ReDoc</title>
    <!-- needed for adaptive design -->
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">

    <!--
    ReDoc doesn't change outer page styles
    -->
    <style>
      body {
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <redoc spec-url='openapi.yaml'></redoc>
    <script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
  </body>
</html>

Preview Redoc

To preview redoc in local, we can use Redoc Command Line Interface to render specification Doc.

You can install redoc-cli globally or using npx.

Run below command to start the server with spec rendered with Redoc

npx redoc-cli serve [spec] --watch

To generate a static HTML spec document, you can use

npx redoc-cli bundle [spec]

Extra Note: On top of OpenAPI specification, Redoc has made use of vender extension to extend more features. In kabu STATION API, I have utilized few of those extensions like x-logo, x-displayName and x-codeSamples.

  • x-logo : Use to specified Kabu Station API logo
  • x-displayName : Use to specify name for Menu categories
  • x-codeSample : Use to provide various sample code for API usage.

Useful Tips:

You can use VS code extension to write definition and preview the spec.

  • Redoc Viewer extension : Useful for previewing the redoc in local while writing definition file.
  • OpenAPI (Swagger) Editor extension: Provide rich features for swagger editor.

Conclusion

So far, I've been using OpenAPI ver.3.0 and Redoc for awhile. I can see the powerful of these open-source project over API development. We can utilize it to create a well documented API specification that give great experience to API consumer.

lastly, I will explore more tools and write an article to share in this blog again.