LoginSignup
19
23

More than 5 years have passed since last update.

仕事でSwaggerなymlをもらいました。初めてでしたがSwaggerで簡単にモックAPIサーバが建てられてQOLが上がった感じがしました。

swagger-codegenでモックサーバを立てる

インストール

インストールは簡単で、brew一発です。公式でDockerを使ってビルドする方法もありましたが、mavenで一つ一つビルドしていくため時間がかかりますので、おすすめしません。

$ brew install swagger-codegen
$ which swagger-codegen
/usr/local/bin/swagger-codegen

もしかしたら事前にJavaが必要かもしれません

$ brew cask install java

使い方

下記のような感じで使います。

$ swagger-codegen generate \
  -i swagger.json \
  -l nodejs-server \
  -o api-mock
  • -i 元にするjson
  • -l 言語(クライアントとか、サーバとかもここで識別)
  • -o 出力先のフォルダ

APIサーバ起動

$ cd api-mock
$ npm install
...省略...
$ node .
notebook:api-mock foursue$ node .
Your server is listening on port 8080 (http://localhost:8080)
Swagger-ui is available on http://localhost:8080/docs

nodeのインストールしてない場合、下記のような感じでインストールしてから、上記のnpm installしましょう。

$ brew install node brew
$ cat 'export PATH=$HOME/.nodebrew/current/bin:$PATH' >> ~/.bash_profile
$ . ~/.bash_profile
$ mkdir ~/.nodebrew/src
$ nodebrew install-binary stable
$ nodebrew use v6.2.2

docker-composeにapi-mock入れて開発すると楽

docker-compose.ymlは下記のような感じでいいんじゃないでしょうか。
※webの方は適当です。

docker-compose.yml
api:
    image: node:latest
    volumes:
        - ./api-mock/:/usr/src/app
    ports:
        - "8080:8080"
    working_dir: "/usr/src/app"
    command: "node ."
web:
    build: ./dockerfiles
    volumes:
        - ./:/var/www/
    ports:
        - "80:80"
    links:
        - api:api

phpだと下記のような感じで動作確認できます。

$ docker-compose up -d
$ docker exec -ti ***_web_1 bash
$ php -r "var_dump(jsondecode(file_get_contents('http://api:8080/v1.0/api/***')));"

自前のプロジェクトでもSwagger使ってみようかなと思わせるくらいには敷居が低い。学習コストも低い。Swaggerは使える。

19
23
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
19
23