Use Swagger to generate API client in Frontend

Suraj KC
5 min readAug 28, 2019

--

Hi there, if you are using frontend technologies to build beautiful and immersive web applications, you are awesome :D. Being a frontend engineer, we are always looking for ways to be more effective and efficient. And the one thing that is ubiquitous in web development is design and development of RESTful apis. I myself have spent endless hours in several projects in API driven development. And there is always debate on how to get the APIs right among frontend and backend developers. Would it not be better if there was some common ground for frontend and backend engineers for API design, development and documentation ? Here, I would like to share how an excellent collaborative tool ie Swagger can help you become super efficient in your frontend development workflow.

Swagger is a set of open-source tools built around the OpenAPI Specification that can help you design, build, document and consume REST APIs.

OpenAPI Specification (formerly Swagger Specification) is an API description format for REST APIs. An OpenAPI file allows you to describe your entire API. API specifications can be written in YAML or JSON. I personally prefer YAML as it is more readable than JSON.

A sample openAPI specification is given below:

simple_openapi_specification_02_with_operation.yaml

Swagger UI

Swagger UI allows to visualize and interact with the API’s resources simply from your OpenAPI Specification. It makes it easy for back end implementation and client side consumption with visual documentation.

You can checkout this link to see it in action:

Swagger UI

If you have well written or generated specification of restful API, it is a piece of cake to setup in your frontend application.

It also provides a npm package for use in your react application.

import SwaggerUI from "swagger-ui-react"import "swagger-ui-react/swagger-ui.css"export default App = () => <SwaggerUI url="https://petstore.swagger.io/v2/swagger.json" />

Swagger Codegen

Swagger Codegen can simplify your build process by generating API client from any API, defined with the OpenAPI specification. It can be collaborative and time saving tool for your development team.

Installation

Make sure you have java installed on your system.

sudo apt install default-jdk

I think the simplest way to get Swagger codegen working is to just download the Swagger cli jar file using the following. It is not available as npm package and though it can be installation via brew or maven, I found that quite cumbersome.

wget https://oss.sonatype.org/content/repositories/releases/io/swagger/swagger-codegen-cli/2.2.1/swagger-codegen-cli-2.2.1.jar

Note: You need Swagger Codegen 3.0.20 with Open API 3.0 based files.
Then, you can use the following command to generate API client:

swagger-codegen generate -i <path of your Swagger specification> -l <language>

While this gets the work done, there is a better alternative approach to Swagger codegen.

OpenAPI generator

Similar to Swagger codegen, OpenAPI generator allows generation of API client libraries automatically given an OpenAPI Spec. It is actually a fork of Swagger-codegen and can be easily consumed as npm package.

For demo purpose, I would like to use a react typescript application. I think the process should be fairly similar to Angular or other frontend systems. For react, we can use the following generators:

This generator utilizes the Fetch API which provides an interface for fetching resources over the network. We can use the following command to generate the client using typescript fetch:

openapi-generator generate -i swagger.yaml --generator-name typescript-fetch -o gen/api

Limitations of typescript-fetch:

This generator does not support setting the auth configurations in the classes generated. The authentication mechanism for Open API Spec is explained in detail here:
https://swagger.io/docs/specification/authentication/

This generator seems to be very limited in comparison with typescript-axios in configuring the generated client.

  • TypeScript Axios

This generator is based on axios which is a promise based HTTP client for browser and node. This generator seems to be updated with support for auth configuration.

We can use the following command to generate the client using typescript axios:

openapi-generator generate -i swagger.yaml — generator-name typescript-axios -o gen/api

To get the openAPI generator working in your react typescript app, you can add openapi generator dependency:

yarn add @openapitools/openapi-generator-cli -D

Update scripts in package.json as below. I am using typescript-axios to generate the client.

"scripts": {  
"api": "rm -rf gen/api && openapi-generator generate -i http://petstore.swagger.io/v2/swagger.json --generator-name typescript-axios -o gen/api --config api.json && cd gen/api && npm install && npm run build"
}

Make sure to replace sample json file with your own generated specification json or yaml file.

api.json file looks like this:

{"npmName": "typescript-axios","npmVersion": "1.0.0","snapshot": false,"supportsES6": false,"modelPropertyNaming": "original"}

For full list of available options, you can visit this link:

https://openapi-generator.tech/docs/generators/typescript-fetch/

Then, you can simple run the following command to generate API client.

npm run api

It will generate gen > api directory containing TS files with services for HTTP methods as well as interfaces of the request and response types.

In order to use this generated API client, you can update your package.json with following snippet:

"dependencies": {
"typescript-axios": "file:gen/api"
},

It simply copies your api directory that you generated to node_modules under typescript-axios. So, may be in your react application, you could access the API client like:

import {DefaultApi} from "typescript-axios";const apiSerivice = new DefaultApi();

You can also create api client instance with the following configuration parameters:

export interface ConfigurationParameters {
apiKey?: string | ((name: string) => string);
username?: string;
password?: string;
accessToken?: string | ((name?: string, scopes?: string[]) => string);
basePath?: string;
baseOptions?: any;
}

If we need to initialize the api client with authentication token or pass other configuration as above, we can create the instance as below:

const apiSerivice = new DefaultApi({
apiKey: '' /** api key obtained from login */
});

By default, the api client uses its own instance in the generated code. If we want more flexibility in customizing axios with interceptors and other axios features, we can pass our own axios instance.

const axiosInstance = axios.create();// Configuration and base path are not provided
const apiService = new DefaultApi(undefined, undefined, axiosInstance);

Using this Api client, you can perform all the RESTful operations written in your specification file.

Here is also a repository that you might want to checkout that can help you understand the workflow.

I am just getting started with Swagger and loving the experience so far. If you have suggestions and feedbacks, kindly do let me know. Thanks. :)

Updates:
OpenAPI generator does not seem to support oneOf, allOf and anyOf keywords to combine schemas. Swagger Codegen seems to support these features.

--

--