Skip to content

Instantly share code, notes, and snippets.

@acclaim-tech
Created November 4, 2017 05:56
Show Gist options
  • Save acclaim-tech/6d746bf3f0ea5c3443dc2d521d3b71c5 to your computer and use it in GitHub Desktop.
Save acclaim-tech/6d746bf3f0ea5c3443dc2d521d3b71c5 to your computer and use it in GitHub Desktop.
Expose swagger json from API Gateway lambda
module.exports.getDocs = function(event, context, callback) {
let options = {
swaggerDefinition: {
info: { // API informations (required)
title: 'API Gateway project', // Title (required)
version: '1.0.0', // Version (required)
description: 'Set of API endpoints exposed via API Gateway', // Description (optional)
},
host: 'localhost', // Host (optional)
basePath: '/', // Base path (optional),
schemes:['https','http'],
definitions: {}
},
// Path to the API docs
apis: ['handlers/*.js'],
};
// Initialize swagger-jsdoc -> returns validated swagger spec in json format
let swaggerdoc = swaggerJSDoc(options);
let stage = '';
if (!process.env.IS_OFFLINE) // if you are using serverless-offline and dev/prod stage
{
if (event.requestContext) stage=event.requestContext.stage;
if (stage && stage.length && stage.length > 0) swaggerdoc.basePath += stage + '/';
}
swaggerdoc.host = event.headers.Host;
swaggerdoc.definitions=dbTools.getSwaggerDefinitions();
// API Gateway response should have specific format (JSON.stringify below is mandatory!)
// need to add CORS headers to overwrite API Gateway default CORS settings
const response = {
statusCode: 200,
headers: {
"x-custom-header" : "Inspired by Acclaim Consulting",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
},
body: JSON.stringify(swaggerdoc)
};
callback(null, response);
};
@acclaim-tech
Copy link
Author

Most examples of using swagger specs for REST APIs are based on ExpressJs/Hapi/Restify and other similar frameworks. However, if your REST API is deployed as API Gateway lambdas, there are no web server to expose API docs.
Gist above provide you with a solution. It is just another service endpoint which dynamically generates Swagger specs from your comments (code above assumes that your methods located in 'handlers/*.js' files).

@acclaim-tech
Copy link
Author

acclaim-tech commented Nov 4, 2017

In your serverless.yml you can add next :

 getApiDocs:
   handler: handlers/handler.getDocs
   events:
     - http:
         path: api-docs
         method: get
         private: false
         cors: true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment