NodeJs Swagger documentation

With swagger.json

Allen Kim
Digital-Heart

--

Swagger is a set of open-source software tools built around the OpenAPI Specification with which we can build, document, and test our APIs.

Let’s say you have the following swagger.json, which is downloaded from AWS Lambda export.

{
"swagger" : "2.0",
"info" : {
"version" : "1.0",
"title" : "my-api-service"
},
"host" : "my-api-service.com",
"schemes" : [ "https" ],
"paths" : {
"/api/home" : {
"get" : {
"responses" : { }
}
}
}
}

What you need is to create a web page to utilize your swagger.json. For example /api/swagger to show swagger info using swagger-ui-dist .

The following is an example to show api documentation on /api/swaggerusing your ./swagger.json

./src/swagger.ts : Your API request handler

import spec from './swagger.json';

const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@3/swagger-ui.css">
</head>
<body>
<div id="swagger"></div>
<script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<script>
// SwaggerUIBundle({ dom_id: '#swagger', url: '/swagger.yaml' });
SwaggerUIBundle({ dom_id: '#swagger', spec: ${JSON.stringify(spec)} });
</script>
</body>
</html>`;

export const swaggerHandler = async (event) => {
return {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html
};
}

// For Express
// export function(req,res) {
// res.set('Content-Type', 'text/html');
// res.send(html);
// }

When you run the above code, you will see the following result by visiting /api/swagger

In summary, what you need to show Swagger documentation are;

  1. swagger.json
  2. API handler(which returns HTML)

Bonus: AWS Lambda + SAM

The above example is using AWS Lambda + SAM.

./template.yaml : SAM template

...
SwaggerFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.swaggerHandler
Events:
GetHtml:
Type: HttpApi
Properties:
Path: /api/swagger
Method: GET
Metadata: # Required for Typescript compile
BuildMethod: esbuild
BuildProperties:
Minify: true
Target: "es2020"
Sourcemap: true
EntryPoints:
- app.ts
...

./app.ts : API main entry point file

...
export {swaggerHandler} from './src/swagger';

To run AWS Lamba locally, run the following command. To learn more about running AWS lambda locally, visit this page, Develop AWS Lambda with TypeScript locally | by Allen Kim | Sep, 2023 | Medium

$ sam build
$ sam local start-api

You may ask how I get swagger.json .

Well, you can create one by yourself following OpenAPI Specification, or you can download it from your serverless cloud platform, e.g. AWS Lambda.

The following images are how I get swagger.json from AWS Lambda.

If you understand the above, you are ready to document a lot more than the simple ones on this article.

Happy coding

Oct 11th, 2023.

Allen Kim

References:

--

--