Site cover image
OpenAPI たった1コマンドでモックサーバー完成!API Sproutの紹介

Web開発の現場では、APIを境界にサーバー側、クライアント側で分担して開発することがよくあります。

そんなとき問題になるのが「ダミーのAPIを用意するのが面倒」ということです。

この問題は、API仕様のフォーマットであるOpenAPIと、OpenAPI Specをもとにコマンド1発でダミーのAPIサーバーを立ててくれるAPI Sproutを使うことで解決できます。

このエントリでは、OpenAPI Specから1コマンドでモックAPIサーバーを立ててくれるAPI Sproutを紹介します。

OpenAPI Specification

OpenAPI Specification は言語に依存しない、人間にもコンピュータにも理解しやすい RESTful API の仕様です。

下記に例を示します。

openapi: 3.0.2
info:
  title: Example API
  version: 0.0.1
servers:
- url: http://localhost:3000/
paths:
  /users/{userId}:
    get:
      operationId: getUser
      parameters:
      - explode: false
        in: path
        name: userId
        required: true
        schema:
          type: integer
        style: simple
      responses:
        200:
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserResponse'
          description: 200 response
        default:
          description: Error response
      tags:
      - users
components:
  schemas:
    UserResponse:
      description: ユーザーレスポンス
      properties:
        user:
          $ref: '#/components/schemas/User'
      required:
      - user
      type: object
    User:
      description: ユーザー
      properties:
        userId:
          description: ユーザーID
          example: 1
          type: integer
        name:
          description: ユーザー名
          example: おとよ
          type: string
        blogUrl:
          description: ブログURL
          example: http://alpacat.hatenablog.com/
          format: uri
          type: string
      required:
      - blogUrl
      - name
      - userId
      type: object

このように、さらっと見ただけでAPI仕様が理解できてしまいます。

さらに良いのは、OpenAPIは特定の言語に依存しないので、サーバ側とクライアント側で開発言語が違っていても問題ないということです。

このopenapi.yamlに基づいたダミーのAPIサーバーを、API Sproutを使って立ててみます。

API Sprout を使ってダミーAPIサーバーを立てる

API Sprout の Releases から、最新バージョンをダウンロードし、解凍してできた実行ファイルapisproutをパスの通った場所に配置します。

あとはopenapi.yamlを渡して実行するだけです。驚くほど簡単です!

$ apisprout openapi.yaml
🌱 Sprouting Example API on port 8000

ブラウザで http://localhost:8000/users/1 にアクセスしてみましょう。下記のJSONが返ってくるはずです。

{
  user: {
    blogUrl: "http://alpacat.hatenablog.com/",
    name: "おとよ",
    userId: 1
  }
}

たったこれだけで、ダミーAPIサーバーのできあがりです。

exampleに記述した値をダミーの値として返してくれます。

以上です。

このエントリでは、OpenAPI Specから1コマンドでモックAPIサーバーを立ててくれるAPI Sproutを紹介しました。

Thank you!
Thank you!
URLをコピーしました

コメントを送る

コメントはブログオーナーのみ閲覧できます