Your First API With Node and Express

May 25, 2016

* Note: I am using OSX for the commands in this tutorial. *

* Note: Do not type the $ before the terminal commands. *

* Note: If you want semicolons in your JS, by all means feel free. *

Before getting started with this project, it is important to make sure you have NodeJS installed on your computer. To check this, type the following into your terminal window and hit enter:

$ node –v

The –v means version. This should return to you the version of Node that you are working in:

v6.1.0

It is not important that your numbers match mine, all that matters is that you see some sort of version number there. Ok, let’s move on.

Now you need to set up the folder and files that you will need. Remember, this is a simple test project, so we will be using a lot less files than you would use in a real production app. Type the following command to get things setup:

$ mkdir api-test && cd api-test && touch app.js && npm init

The previous line might look confusing, but it isn’t too bad. First, we’re making a folder called api-test. Then we’re changing into that directory and creating a file called app.js. Finally, we’re running the npm init command, which will create a package.json file for us. Just hit enter through all of the prompts until you’re done. Now, open up the project in your favorite text editor (I’m using Atom).

$ atom .

For the last piece of setup, we’ll need to get Express installed in our app. Type the following into the command line:

$ npm install express --save

The --save will add express to your dependencies in your package.json file. Not important for this tutorial, but it is always good practice to remember that.

Now we’re finally ready to get started. We’ll be using some ES6 for this, and although my version of node will run the ES6 code, some hosting sites still have versions that don’t (Heroku) run it outside of strict mode. We’ll just overcome this by using strict mode. First, let’s build up a little Express server:

// app.js

'use strict'
const express = require('express')

const port = process.env.PORT || 3000
const app = express()

app.get('/', (req, res) => {
  res.json({name: 'John Doe'})
})

console.log('Running!')
app.listen(port)

With that in place let’s run the server:

$ node app.js

And in your browser of choice visit localhost:3000. We should see the JSON we sent to the home route and now we know we’re up and running.

Now let’s fill out our people.json with some data and require it in our app.js:

// people.json

[
  {
    "firstname" : "John",
    "lastname" : "Doe",
    "age" : 28,
    "gender" : "male",
    "id": 5694004
  },
  {
    "firstname" : "Jane",
    "lastname" : "Doe",
    "age" : 34,
    "gender" : "male",
    "id": 8378473
  },
  {
    "firstname" : "Jim",
    "lastname" : "Doe",
    "age" : 26,
    "gender" : "female",
    "id": 4490293
  }
]
// app.js

'use strict'
const express = require('express')
const people = require('./people') // Added line

...

Now we just need to set up our API. For this example I will only be showing you a few methods and examples. The rest is up to you to research. Let’s set up an endpoint for users to get all of your people objects. This is just a simple GET request. Funny enough, we're alreay handling a GET request. Let's just update that to respond when someong visits /api/people. We can also get rid of that object we're passing into res.json() and replace it with our people constant. It should look like this:

// app.js

...

const app = express()

app.get('/api/people', (req, res) => {
  res.json(people)
})

console.log('Running!')

...

Now is a good time to shut down and restart your server. Then head back to your web browser to see the progress. As you can see, it doesn't work anymore. That's because we aren't responding to the / directory anymore, we're looking for /api/people. Visit localhost:3000/api/people and you will see your JSON data. Just as a side note, download some sort of JSON viewer for your browser to clean it up a bit.

Now that we have that working, it would be nice if we could grab specific people right? Right! Let's set that up. This one is a little larger, so I will just plop the code in and explain each line with a comment:

// app.js

...

app.get('/api/people', (req, res) => {
  res.json(people)
})

// Another GET method, this time to /api/person/:id
// The :id is a dynamic parameter that could be anything
app.get('/api/person/:id', (req, res) => {

  // This is where we grab the id parameter from the URL
  // and set it to our constant called id
  const id = req.params.id

  // We take people, which is an array, and we filter it
  // to give back a specific person with the matching id
  // inside of an array
  const person = people.filter(person => person.id === Number(id))

  // Some error handling
  // Makes sure there is a person in the array
  if(person.length > 0) {

    // Sends out the containing person object as JSON
    res.json(person[0])

  } else {

    // If there is no user with the matching id, this will display
    res.send('NotFoundError: ID not found.')
    console.error('NotFoundError:', 'ID not found')

  }
})

console.log('Running!')

...

Once you know what everything does, feel free to remove the comments and the extra white space.

Let's test it out again, stop and start your server and visit a person's page with their ID: localhost:3000/api/person/5694004 and you should get the John Doe person returned.

And there you go! Now you have some API endpoints where people can come grab some data that you're providing. Remember, this is just a small example and in a real API you'll probably be using a database and have more architecture, but this is a good start from a learning perspective. There is so much more you can do with this. Maybe you want to create a new person, update a person's info, or just completely remove a person all together. This is all doable and all you have to do is look through the Express API reference under Application. I would suggest looking at app.get(), app.post(), app.put(), and app.delete() and then looking at the routing guide. Hope this gets you started in the right direction.