Skip to content

Instantly share code, notes, and snippets.

@RayBenefield
Last active April 20, 2017 20:06
Show Gist options
  • Save RayBenefield/a40cfe5da8e4d10d37f27884c055b7db to your computer and use it in GitHub Desktop.
Save RayBenefield/a40cfe5da8e4d10d37f27884c055b7db to your computer and use it in GitHub Desktop.
Simple iterative steps to create an API server in Node

Did you know?

APIs run the same core system as Websites. Websites are just an HTTP call with the GET verb with a content-type of "text/html" this tells the caller that it can be rendered as HTML. Browsers know how to render HTML nicely and that's what you see in a website.

Try making a call to Postman without a server running.

postman - http://localhost:8000 (no response)

Make a project directory:

mkdir my-api
cd my-api

Setup a node project with NPM (a package manager). For now just accept the default for everything.

NOTE: Notice the "entry point": index.js; this is where our project "starts"
npm init

We need to "install" the server framework that we will be using called restify.

npm install --save restify

Now we will open our entry file (index.js) so we can write our program.

vim index.js
// index.js
var restify = require('restify');

var server = restify.createServer();

server.listen(8000, function() {
    console.log('Server started');
});

With that code written, now we can run our server using node.

node index.js

postman - http://localhost:8000 (ResourceNotFound)

We make another call to postman and we now see that the server is actually responding, but it says we don't have a "resource", so we need to go make a resource.

// index.js
// below: var server…
server.get(/, function(req, res) {
	res.send(200);
});

I'm hate restarting my server every single time I want to see changes. So we will setup something to watch our files and re-run our program every time we make a change. We will do this with nodemon and create a run script to execute the command in an easily readable name.

npm install --save-dev nodemon
vim package.json
// package.json
  "scripts": {
      "dev": "nodemon index.js --exec node"
  },

Now we can execute the script and it will start the server for the first time. Now, every time I make a change to the file it will automatically restart the server.

npm run dev

postman - http://localhost:8000 (200 Success)

The last thing we did was add a resource as the base endpoint so a call to postman will show that we return a 200 response now. Let's do more with that resource and add a body to the response.

vim index.js
// index.js
// Replace res.send
res.send(200, {
    'hello': 'world',
});

postman - http://localhost:8000 (200 Success with Hello World)

And now we have a hello world body. All we do is return a JSON object with the key of hello and a value of world. What if we want to be able to pass in values to our "resource" to get different results? One way is by providing a dynamic path.

// index.js
server.use(restify.queryParser());
server.get('/:name', function(req, res) {
    res.send(200, {
        'hello': req.params.name,
    });
});

postman - http://localhost:8000/ray (200 Success with Hello Ray)

// index.js
server.use(restify.bodyParser());
server.post('/', function(req, res) {
    res.send(200, {
        'hello': req.params.name,
    });
});

postman - POST http://localhost:8000/

Content-Type: application/json

{ "name": "ray" }

(200 Success with Hello Ray)

We have to now make a call with a JSON body.

npm install --save request
// index.js
var request = require('request');

// Above get(‘/:name’) …
server.get('/example', function(req, res) {
    request.get('https://jsonplaceholder.typicode.com/users', function(error, response, body) {
        res.send(200, JSON.parse(body));
    })
});

postman - http://localhost:8000/example (200 Success with Example results)

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