OpenApi Generator for React Native by Swagger

How do you handle Restful API calls in your React Native Application?

In this article, I want to show you how to add then config OpenApiTools generator in your React Native application.

Requirements:

npx react-native init OpenApiClient —template react-native-template-typescript

After that, I add axios to the project for the client-side API call

yarn add axios

There are multiple ways to use the OpenApiTools generator in your project, but in this article, I follow the way that adds the tool in your dev dependencies. To this purpose run:

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

Configs:

Run the below command in your project to generate all files in the generated directory at the root of your project:

npx openapi-generator-cli generate -i https://petstore.swagger.io/v2/swagger.json -g typescript-axios -o generated

This command has three parameters:

  • i: Address of input file or URI
  • g: Name of the generator, In this example, we use typescript-axios to generator actions and type in typescript by axios. Open API Tool supports many types of generators in most programming languages and frameworks. You can see the list of them in this repo.
  • o: Output folder of generated files. I used generated directory in this example.

For the next usage, I add the above command in the project package.json file scripts:

Therefore, every time you want to update generated files, you only need to enter the below command in the terminal:

yarn generate:apis

Usage:

api.ts

You can pass configuration object, base URL, and axios instance in the contractor on these objects.

Make object with configuration.

Now you can use these APIs in your components, like below:

Result:

Sample app screen

If you run the application in debug mode and open the console, you see such an error:

Error: not implemented
at URL.get (URL.js:195)
at setSearchParams (common.ts:91)
at getPetById$ (api.ts:450)
at tryCatch (runtime.js:63)
at Generator.invoke [as _invoke] (runtime.js:293)
at Generator.next (runtime.js:118)
at tryCatch (runtime.js:63)
at invoke (runtime.js:154)
at runtime.js:164
at tryCallOne (core.js:37)
Error in the first run

Solution:

yarn add react-native-url-polyfill

After installing this package, adds the below code in your api.ts file:

import 'react-native-url-polyfill/auto';

The final code in your api.ts seems like below:

If you run the application again and press Get First Pet, something like the below image appear on the app screen:

Successful usage of generated endpoint

Conclusion:

You can reach the code of this sample application in this repository:

React Native developer