OpenAPI (Swagger docs) integration with serverless framework | Node.js Express.js Typescript

OpenAPI (Swagger docs) integration with serverless framework | Node.js Express.js Typescript

Introduction:

OpenAPI formerly known as swagger docs is a specification. It’s a standardised way to describe web APIs using a machine-readable format, typically YAML or JSON. OpenAPI docs could also be written in line as comments in javascript/typescript files. This format outlines the different endpoints, what kind of data they expect (request body), what kind of data they return (response), and other details that are crucial for developers and tools (eg: postman) to understand and interact with your API effectively. 

Serverless framework lets you build and deploy applications without managing servers. You write code for specific functions that execute in response to events (like an API request). The cloud provider handles server provisioning, scaling, and maintenance, allowing you to focus on core functionality and benefit from pay-per-use pricing.

Setting up swagger/OpenAPI with serverless:

Install the following dependencies
npm i swagger-jsdoc with this dependency you will be able to extract swagger doc from comments in javascript files. 

npm i swagger-ui-express this serves interactive swagger ui.

Following is a utility function that sets up the swagger configuration, the function accepts express app as the input

swagger docs extracts the api definitions from the .js files mentioned in the apis array.

Swagger needs the original URL to correctly generate the api documentation, but the api gateway (proxy) modifies the request URL and store a copy of original URL on the “x-forwarded-prefix” header and with this middleware the original URL gets assigned to req.originalUrl.

A sample swagger doc

Result

I had trouble setting up swagger docs with AWS and i hope this article helps you out.
Thank you for reading 🙂
Abd038

Socials:
https://www.linkedin.com/in/abdul-mohammad-a567b2183/
https://twitter.com/iam_abd038
https://github.com/iam-abdul

Leave a Reply

Your email address will not be published. Required fields are marked *