skip to content
Avatar Bruno Garcia

Research about auto-generating API Client and API Mock

The main goal of this project is to auto-generate a API Client and API Mock from an Open API definition

Description

  • The definition was copied from the Open API Petstore project.
  • I’ve created a simple demo to check if the generated code works. And it works! 😀

Github

Check out the source code on Github.

App Architecture

App Architecture

What is OpenAPI?

Originally known as the Swagger Specification, the OpenAPI Specification (OAS) is a format that can be used to describe, produce, consume, and visualize RESTful web services. It’s a specification standard for REST APIs that defines the structure and syntax.

Source: What is OpenAPI?

What is a API Client?

An API client is a set of tools and protocols that operate from an application on a computer. They help you to bypass some operations when developing a web application rather than reinventing the wheel every time. Using a client API is a great way to speed up the development process.

Source: What is Client in API Terms?

What is a API Mock?

Mock APIs are used to simulate actual APIs where you can generate requests with custom data and get realistic responses the actual API would return. It is a fast and easy way of testing your REST API even before it goes live.

Source: API Mocking - Everything You Need To Know

Tools

  • typescript-fetch for generate the API Client. There are other generators that can be used. Check the Client Generator page.
  • MSW for generate the API Mock.
  • msw-auto-mock for generate random mock data from OpenAPI descriptions for MSW.
  • faker for generate massive amounts of fake (but realistic) data for testing and development.

Generate the API Client

For generate the API Client, first you need to install Docker.

Then, run the following command:

docker run --rm \
    -v $PWD:/local openapitools/openapi-generator-cli generate \
    -i /local/petstore.yaml \
    -g typescript-fetch \
    -o /local/api

Generate the API Mock

We use msw-auto-mock to generate random mock data from OpenAPI descriptions for MSW.

  • You must specify the OpenAPI file path.
  • You must specify the output file path.
  • You must specify the base URL of the API.
npx msw-auto-mock petstore.yaml -o ./mock.js --base-url http://petstore.swagger.io/v2