OpenAPI Client
To generate the client, we use the openapi-generator-cli (opens in a new tab). Among the available options, the typescript-axios
client is the best for our use.
Steps to Generate the Client
-
Install the CLI - Ensure you have
prettier
installed and configured for code formatting.yarn add @openapitools/openapi-generator-cli -D
-
Setup the Clients Directory - Create a
clients
folder where the generated clients will be stored. In this folder, create:
- Axios Instance: If needed, set up an instance of Axios. See this Example (adds access token to the request) (opens in a new tab)
- Client Files: For each client, to simplify usage, merge the factories into a single API object. See Example 1 (opens in a new tab) and Example 2 (opens in a new tab)
-
Configure ESLint - Add the generated client folders to the ESLint ignore list in
.eslintrc.js
. See this Example (opens in a new tab) -
Create Generate Script - Add a script in
package.json
to generate the client. Since the generated client has its own formatting, runprettier
on the generated files to maintain consistency with the rest of the codebase. The schemas may contain many errors, so the--skip-validate-spec
flag is necessary. Target thestaging
version of the API. If there are more clients, you can create a one command that generates all of them. See this Example (opens in a new tab){ "scripts": { "generate-client-forms": "openapi-generator-cli generate -i https://nest-forms-backend.staging.bratislava.sk/api-json -g typescript-axios -o ./clients/openapi-forms --skip-validate-spec && prettier --write ./clients/openapi-forms", ... "generate-clients": "yarn generate-client-forms && yarn generate-client-tax", } }
-
Manage Configuration - An
openapitools.json
file will be created. Regularly update thegenerator-cli
version to keep up with the latest changes.