Skip to content

Instantly share code, notes, and snippets.

@kesor kesor/README.md
Last active Feb 4, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.