/node-swagger-api

Simple Node.js/TypeScript example REST API example based on Swagger with minimal dependencies

Primary LanguageJavaScript

Swagger based Node/TypeScript REST API

This is a simple REST API implemented in TypeScript on Node.js with minimal dependencies.

NOTE: I have a more recent Node.js/TypeScript example API here.

Minimizing dependencies

I strive to minimize dependencies and rely on the Node core library instead where possible. The Express framework has around 4 thousand lines of code but with about 40 dependencies the total code size is around 14 thousand lines of code. It turns out a basic JSON REST API can be built with a much smaller codebase.

The app initially depended on connect for middleware support and although connect is minimal and may be needed down the line depending on what API you are building and which middlewares you need I decided to remove that dependency for now.

Installation

npm install

Starting the Server

npm start

Building TypeScript

npm run build

Linting with tslint

npm run lint

Example CRUD API

# list
curl -i http://localhost:3000/v1/articles

# get
curl -i http://localhost:3000/v1/articles/123

# create
curl -X POST -i -d '{"foo": 1}' http://localhost:3000/v1/articles

# update
curl -X PUT -i -d '{"foo": 1}' http://localhost:3000/v1/articles/123

# delete
curl -X DELETE -i http://localhost:3000/v1/articles/123

Example: Measuring Response Time

app.server.on("request", function(req, res) {
  const requestTime = process.hrtime();
  res.on("finish", function() {
    const diff = process.hrtime(requestTime);
    const responseTime = diff[0] * 1e3 + diff[1] * 1e-6;
    console.log("Response time: ", responseTime);
  });
});

Resources

TODO

  • Logging
  • Handle swagger data types in query/body/params parsing
  • Swagger validation for query/body/params parsing