Skip to content

Instantly share code, notes, and snippets.

@kesor
Last active February 4, 2018 23:51
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kesor/d9aa1aeabb1edd8e85e0627deecaea78 to your computer and use it in GitHub Desktop.
generating a simple api-gateway using swagger-codegen nodejs-server

API Gateway w/Swagger Codegen

I need a simple API Gateway that will use Swagger as its input format. A very simple way to achieve this is to use swagger-codegen and create a nodejs-server that will simply proxy (and optionally modify) requests it receives to some other host.

Node.js request proxy

const https = require('https');

const handler = function (req, res, next) {
  delete(req.headers.host)
  const rq = https.request({
    host: 'httpbin.org',
    path: `/anything${req.url}`,
    method: req.method,
    headers: req.headers
  }, (r) => { r.pipe(res); })
  if (req.swagger.params.body) {
    rq.write(JSON.stringify(req.swagger.params.body.value))
  }
  rq.end()
}

Generating an API

Use the service at https://generator.swagger.io to generate server code for any swagger API. An example API for Pet Store can be found at http://petstore.swagger.io and used as input.

Proxying requests

A useful service that returns any request sent to it is https://httpbin.org, it has multiple endpoints that return back the parameters sent to it. Especially useful are /get, /post, and even /anything that returns back the method used.

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