How to automate API code generation (OpenAPI/Swagger) and boost productivity

Tutorial with React Native featuring TypeScript

Sanjin Celeski
TribalScale
3 min readSep 24, 2020

--

This article demonstrates how to generate typed client for React Native based on Axios library for HTTP requests.

OpenAPI Specification (originally known as the Swagger) is considered the world standard for RESTful APIs. OpenAPI Generator is a tool that creates HTTP client, and covers 40+ different languages and technologies.

Photo by Pexels

Note: Prerequisite for the generator is to have JDK installed on your machine.

Bootstrap the project

Our easy-peasy setup:

For demo purpose, we use convenient sample Pet Store server based on the latest (OpenAPI 3.0) specification:
https://petstore3.swagger.io

// Bootstrap RN project using TS template
npx create-react-native-app my-app --template with-typescript
// CD into the project
cd my-app
// Add project dependencies
yarn add axios url
// Add client generator (as Dev dependency)
yarn add -D @openapitools/openapi-generator-cli
// Create Api folder (for everything API related)
mkdir Api
// Download OAS file to Api folder
curl https://petstore3.swagger.io/api/v3/openapi.json > ./Api/openapi.json
// Add generator script to package.json
npx add-project-script -n "openapi" -v "openapi-generator generate -i ./Api/openapi.json -g typescript-axios -o ./Api/generated"
// Generate the client (requires JDK installed)
yarn openapi

Once generated (takes only few seconds) we will have typed client in /Api/generated folder ready to use.

Expose and use API

Create index.ts in /Api folder and expose APIs.

import { PetApi, StoreApi, UserApi } from './generated';export default {
Pet: new PetApi(),
Store: new StoreApi(),
User: new UserApi(),
};

Import the Api module in App.tsx and use the power of code-completion when looking for the right API call and adding parameters.

Extending the implementation

Optionally, you can inject custom Axios instance in order to have more control over the requests and use all features of the library like canceling requests, intercepting request/response, etc.

import axios from 'axios';
import { PetApi, StoreApi, UserApi } from './generated';
export const axiosInstance = axios.create();// configuration, base path, axios instance
const commonParams = [undefined, undefined, axiosInstance];
export default {
Pet: new PetApi(...commonParams),
Store: new StoreApi(...commonParams),
User: new UserApi(...commonParams),
};

Conclusion

That’s it! This quick tutorial demonstrates how easy and quick is to implement such best practice when it comes to API nowadays. Of course it helps to see exact steps, therefore the idea for this article.

For more in-depth understanding of the generator I warmly recommend this eBook from William Cheng (core contributor on this open source project) with special thanks to him for pointing to the right direction.

--

--