Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Axios API client generated by OpenAPITools code generator?

I am using Swagger/OpenAPI Codegen to generate an API client for the Fetch client in my Vue app and want to use Axios instead. I started by using the OpenAPITools typescript-axios code generator:

java -jar .\openapi-generator-cli.jar generate -i http://localhost:5000/swagger/v1/swagger.json -g typescript-axios -o app\api

I then tried to assign the typed response in to a local variable of the same type:

@Component
export default class Themes extends Vue {
  private themesApi!: ThemesApi;
  private themes: Theme[];

  constructor() {
    super();
    this.themes = [];
  }

  private async mounted() {
    const apiConfig: Configuration = {
      basePath: config.API_URL,
    };

    this.themesApi = new ThemesApi(apiConfig);
  }

  private async getThemes() {
    this.themes = await this.themesApi.getThemes();
  }
}

However, this raised the following TypeScript error:

> 139:5 Type 'AxiosResponse<Theme[]>' is missing the following
> properties from type 'Theme[]': length, pop, push, concat, and 28
> more.
>     137 | 
>     138 |   private async getThemes() {
>   > 139 |     this.themes = await this.themesApi.getThemes();
>         |     ^

The local variable is of the same type: Screenshot showing local variable has the same type.

So why is it raising this error?

like image 969
Magnus Johansson Avatar asked Mar 17 '19 18:03

Magnus Johansson


1 Answers

Have a look at the types for Axios, specifically AxiosResponse: https://github.com/axios/axios/blob/master/index.d.ts#L70

You'll see that it accepts a generic, in your case Theme, which will be accessible under the data property. So you'll need to get your value out using something like the following:

private async getThemes() {
  const response = await this.themesApi.getThemes();
  this.themes = response.data;
}
like image 106
Richard Avatar answered Oct 03 '22 18:10

Richard