Automatically create an API client form an OpenAPI spec

Posted by Harald Nezbeda on Fri 26 August 2022

In a previous post I focused on how to create the OpenAPI spec in an existing project. In this one the generated spec will be used to automatically create the code required for the API client.

OAS API Client Workflow

So we will start from an OpenAPI Schema and the goal is to have a package containing the API Client which we can install from a distribution system.

The tool we are going to use for this task is called OpenAPI Generator and it has support for generating API Clients for multiple languages. In order to keep the setup easier we are going to used the provided docker image in order to run the cli.

The schema that will be used is from SnyPy and we are going to generate a client for the UI which is currently based on Angular, so the generator will be set to typescript-angular.

docker run -u $(id -u ${USER}):$(id -g ${USER}) --rm -v "${PWD}:/local" openapitools/openapi-generator-cli generate \
    -i \
    -g typescript-angular \
    -o /local/client \

The additional properties are required in order to define the name for the npm package and the version that is going to be published. You can find extra settings here.

Now we have a typescript client which can be imported into an existing Angular app, but we want to avoid to always generate this code or even worse, to store it in the versioning system. Instead we want to create a build that we can distribute and install via npm. For this we only need to go inside the client, install the required dependencies and create a build.

cd client
npm install --force
npm run build

Once this is done we can go ahead and publish the build package (make sure you are logged in to npm and have the access right for the package you are about to publish).

cd dist
npm publish --access public

Afterward the package @snypy/rest-client is available on npm. The generator is also creating the documentation of how to install configure and use the client.