Home > Software engineering >  How to use openAPI generated typescript code in react app?
How to use openAPI generated typescript code in react app?

Time:03-08

I'm making a webapp with React. For the backend I am using openAPI with Gradle to generate typescript for my API calls.

Right now, I have my frontend webapp done. And OpenAPI generates typescript files for my API.

However, what I do not understand is how to actually use the generated typescript files in my react app? I can't find any documentation on this online. This is what my setup looks like:

api.ts has following classes: ServiceApi ,ServiceApiFactory, UserData, UserDataResponse, ServiceApiAxiosParamCreator, ServiceApiFp

and I have my webpage.jsx,

when I import these classes I don't know what to do with them. When I try to do something like ServiceApi.functionName() I get an error saying the function does not exist, when it clearly does in the ts file.

Any help is appreciated, thank you!

CodePudding user response:

First, create an instance of your api (optionally put a configuration in here to change the basePath of your backend)

const api = new ServiceApi();

Then you are able to call your service methods...

const result = await api.getWhatEverYourMethodNameIs();

There are a few blogposts describing that. For example one github repo is https://github.com/stefanwille/openapi-generator-typescript-example/blob/master/src/App.tsx

  • Related