DEV Community

Basil
Basil

Posted on • Updated on

Use Openapi Generator SDK for Javascript within Nuxt.Js Project

Its very common to use an OpenApi SDK Client directly in your project - but the SDK Generators is mainly made to publish to generated code as a library on f.e. GitHub. Therefore the following steps will help you to install and use the generated SDK directly within your Nuxt.Js app:

1) Run the Openapi-generator-cli command inside your project

openapi-generator-cli generate -i https://path/to/openapi.json -g javascript -o oa/
Enter fullscreen mode Exit fullscreen mode

2) Since that generated SDK module requires superagent install that dependency in your project:

yarn add superagent
Enter fullscreen mode Exit fullscreen mode

3) Generate a NuxtJS plugin file which helps to include the library and also makes it more easy to access in your app. Create ~/plugins/oa.js

export default ({ app }, inject) => {
  const WebsiteSDK = require('~/oa/src/index.js');

  const defaultClient = WebsiteSDK.ApiClient.instance;
  const bearerAuth = defaultClient.authentications['bearerAuth'];
  bearerAuth.accessToken = "YOUR ACCESS TOKEN"

  inject('sdk', WebsiteSDK)
}
Enter fullscreen mode Exit fullscreen mode

This will make your SDK client available in nuxt.js as this.$sdk

4) Add the plugin in nuxt.config.js

plugins: [
  { src: '~/plugins/oa.js', mode: 'client'},
],
Enter fullscreen mode Exit fullscreen mode

5) Now use your new plugin to make API calls.

const api = this.$sdk.<TheApi>
api.<UniqueOperationIdFromOpenApi>({options}, (error, data, response) => {
      console.log(error, data, response)
});
Enter fullscreen mode Exit fullscreen mode

ps: Maybe there are better solutions, its more an a note for myself - maybe helps others too. Improvements are welcome!

Discussion (0)