swagger-to-mock generates mock data

img

swagger-to-mock

As I introduced in the previous article, My team is using swagger as API documentation entirely.

When I write unit tests with mock data, I am reluctant to write mock data manually like most developers. I think the mock data should be exported from swagger file automatically.
To solve my annoyance, I found some tools like swagmock or swagger-mock-api, But unfortunately, these modules were not sufficient for my expectation.
What I expected was

* Work as CLI and get static JSON response files
( I don’t want to run mock-server for tests )
* Supporting OpenAPI 3 is necessary
( Since I am using swagger version 3 mainly )

So then I created swagger-to-mock as a command line tool, to generate mock JSON files automatically.

This tool works below.

  1. Parse swagger file ( JSON only for now )
  2. Generate JSON response files which are named based on ${API_PATH}_${HTTP_METHOD}_${RESPONSE_STATUS}.json format
    JSON property should be determined based on the swagger definition.
    If there is an example property, The value will be same as the example. Otherwise, The value will be a default value of each data type.

For instance, If you have swagger.yaml below

responses:
  '200':
    description: pet response
    content:
      application/json:
        schema:
          type: array
          items:
            $ref: '#/components/schemas/Pet'
components:
  schemas:
    Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
          example: 123
        name:
          type: string
          example: "Tom"
        tag:
          type: string
          example: "Cat"

And run the command to the file

$npx swagger-to-mock swagger.yaml

As a result, You can get pets_get_200.json and the body will be

[
  {
    "id": 123,
    "name": "Tom",
    "tag": "Cat"
  }
]

Isn’t cool? I hope it’s useful for your development if you are using swagger frequently.
Here is the repo. Also, there is another introduction in Japanese.
I am welcoming your feedback anytime.