DEV Community

sdcaulley
sdcaulley

Posted on

Authentication with swagger-client in the Browser

Use of the OpenAPI specification has been growing. My place of work is very interested in leveraging it as much as possible - in both the backend and the frontend. Being on the frontend team, I was tasked with creating an API call using an OpenAPI spec, and swagger-client - a JavaScript client for using the OpenAPI spec. In this post, I want to share with you what I learned about authentication and swagger-client. It is a fairly simple process, but is not laid out clearly in the documentation for swagger-client. The code below is based on the example I found in the migration documentation.

This implementation is through the browser and called for an independent module. Following the instruction in the README, I pulled the CDN into the application through our index.html:

<script src='//unpkg.com/swagger-client' type='text/javascript'></script>
Enter fullscreen mode Exit fullscreen mode

This made the SwaggerClient class globally available in the application.

In the module, I started by creating a function that creates a new client, specific to the spec I want to use.

// function takes the spec url I want to use and the authentication code needed.
async function createClient(specUrl, auth) {
  const client =  await new SwaggerClient(
    specUrl,
    {
      authorizations: {
        // This key will be defined by the OpenApi spec
        APIKeyQueryParam: auth,
      }
    }
  )
  .catch(err => console.error('client error: ', err));

  return client;
}
Enter fullscreen mode Exit fullscreen mode

I then created the function to make the API call.

export default async function apiCall(specUrl, auth) {
  const client = await createClient(specUrl, auth);

  const data = await client.apis['Search Parameter'].titleSearch({ s: 'potter' })
    .catch(err => console.error('data fetch error: ', err));

  const result = data.body.Search;

  return result;
}
Enter fullscreen mode Exit fullscreen mode

Setting up my functions this way allows a neat decoupling of the creation of the client and the consumption of the client. It will also allow me to later refactor both functions to more generic uses as our code base matures.

I hope this helps anyone else trying to do a browser implementation of the swagger-client.

Top comments (0)