1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

OpenAPI(swagger)+Prismを使用してモックサーバー作成

Last updated at Posted at 2023-03-27

挨拶

初めまして!お久しぶりの方はお久しぶりです!
最近ダイエットの為、自炊を頑張り節制をしているミツクマです🐻
今日は、業務でバックエンドの作業に引っ張られず
作業を進めるために使用したSwaggerについてお話します!

Swaggerって?

Swagger は RESTful APIを構築するためのオープンソースのフレームワークのことです。
「Open API Initiative」という団体がRESTful APIのインターフェイスの記述をするための
標準フォーマットを推進していて、その標準フォーマットがSwaggerです。

端的に言うと、Swaggerを使用することでAPIのモックを簡単に作ることができます!

Swaggerを使ってAPIのモック作成

Swaggerは、それぞれ便利なツールが存在するのですが
今回はVisual Studio Code(以降"VSCode")の拡張機能とPrismを使用していきたいと思います。

以下の拡張機能をVSCodeにインストールします。

  • OpenAPI(Swagger)Editor
  • Swagger Viewer

Prismのインストールは以下のコマンドです。

npm install -g @stoplight/prism-cli 

Prismが正常に動作するには、NodeJS 16以降のバージョンが必要になります。

APIのモック作成

今回は適当な値を埋め込んだAPIを作成したいと思います。
今回はyaml形式で書いていきます。

openapi: 3.0.2
info:
    description: サンプルです。
    version: 1.0.0
    title:API mocks
servers:
  - url: "http://127.0.0.1:4010"
    description: "local development server"

tags:
  - name: "test"
    description: APIのモック
    externalDocs:
      description: "test"
      url: "http://localhost:4010/api/test"
paths:
    "/api/customerList":
      get:
	  response:
	    description: Succsess
	    content:
	      application/json:
		  scheam:
		    $ref: "#/components/schemas/result"

components:
  schemas:
    result:
	type: "object"
	properties:
	  title:
	    type: "string"
	    example: "テストAPIの返り値です"	

これでswaggerの準備は完了です。
次にswaggerを書いたディレクトリで以下のコマンドを入力します。

prism mock ./swagger.yml

これでモックサーバーが立ち上がりました。
起動すると、swagger.yamlに書いたパスが表示されると思うので
そのURLにアクセスしてみましょう!

終わり

以上でSwagger + Prismでの簡易的なモックサーバー作成について終わります。
今は、SwaggerHUBというものがありインターネットに公開できるものもあるので
今後そちらの方についてもお話させていただきたいです。

私と同じような初学者のエンジニアの方に役に立てれば幸いです。
これからも自身が学んだことをアウトプットしていこうと思います。
それでは、またの機会にお会いできたら幸いです!
ミツクマでした🐻

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?