#3 How to create a REST API with Node.js and Express
Corey Domingos
2 years ago

While client side development can be fun and lucrative, expanding your abilities into API development will turn you into a more well rounded Software Developer. APIs, or Application Programming Interfaces, allow software systems to transmit data between one an other, and promote highly reusable systems. Since the inception of REST architecture in 2000 by Roy Fielding, a new standard was set for API development — which began to really gain traction in 2005 and is still an extremely relevant architecture to this day. A variety of languages can be used to create REST APIs, but today we will walk through how to create a REST API with Node.js and Express.


What is a REST API?

API development is by far my favorite aspect of Software Development, and if you share the same lust to understand what is going on behind the scenes — I'm sure you'll grow to share this same sentiment towards API development. REST, less commonly known as, Representational State Transfer is a API development Architecture that is used to handle HTTP requests to typically transfer, modify, or manipulate resources. With REST architecture you'll be able to make use of the following HTTP requests to perform these actions:


- GET (request from a resource)

- POST (publish to a resource)

- PUT (publish or update a resource)

- Patch (modify a resource)

- Delete (remove the resource)


These actions will be tied to what we refer to as a API endpoint — which is the resource that you are trying to access in the form of an address. Each unique API endpoint will implement your desired API level logic on the requested resource. Enough background, lets setup a REST API using Node.js that we will be able to build on in future how-to's.


Let's Build

First things first we will need Node.js and NPM installed on your machine, if you do not you can download them here. To check if you have Node.js and NPM already installed, run the below commands in your command prompt to verify.

node -v
npm -v

In your command prompt navigate to the sub directory where you would like your API to be stored and run:

mkdir myRestApi

With our project folder created we can now navigate into our project and run:

npm init

This will then walk us through creating the "package.json" file.

Press ^C at any time to quit.
package name: (myrestapi)
version: (1.0.0)
description: my node api
entry point: (app.js)
test command:
git repository:
keywords:
author: your name
license: (ISC)
About to write to C:\Users\yourdir\package.json:

{
  "name": "myrestapi",
  "version": "1.0.0",
  "description": "my node api",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "corey domingos",
  "license": "ISC"
}

Is this OK? (yes) 

After the "package.json" file is created we will install Express using:

npm i express

Now we can open our project in Visual Studio Code by executing:

code .

With the project open in VS Code, open the "package.json" file and add the start command so the "package.json" file will look like this:

{
  "name": "myrestapi",
  "version": "1.0.0",
  "description": "my node api",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start" : "node app.js"
  },
  "author": "corey domingos",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.2"
  }
}

Then create a file in the root directory "app.js", which will be executed when the start command defined in the "package.json" file is ran. In the "app.js" file we will implement the below code to start the sever listening on port "8080":

var express = require('express'); 
var app = express(); 
var port = 8080; 

app.listen(port, () => {
    console.log(`Server is listening on port: ${port}`)
})

Execute the start command in your project folder:

node app.js

In your terminal you should see the below:

Server is listening on port: 8080

With just a couple steps, your first Node.js REST API is live on your localhost. Pretty easy right? Now lets set up one API endpoint to test. We will modify the existing "app.js" file with one "GET" endpoint like below:

var express = require('express'); 
var app = express(); 
var port = 8080; 


app.get('/testApi', (req, res) => {
    res.status(200).json({status: true, messsage : "The api is working!"})
})


app.listen(port, () => {
    console.log(`Server is listening on port: ${port}`)
})

After restarting the server with the start command, navigate to your desired web browser and access "http://localhost:8080/testApi". If all went well you should see the below displayed on the webpage.

{"status":true,"messsage":"The api is working!"}


API Testing

Now the simple REST API that we built in this demo does not require in depth testing and can be accessed in your browser — but as your API endpoints become more complex you'll need to make use of an API testing tool. The most common REST API tool is Postman, but there are plenty of other alternatives on the market to help you test your endpoints. My favorite REST API testing tool is Advanced Rest Client, which can be used as a desktop application, or chrome extension.


Conclusion

We now have a running REST API using Node.js and Express to build on. While we only created one endpoint in this post, going forward we will use this barebones project to develop a full CRUD (Create, Request, Update, Delete) REST API. Interested in creating a conversation on this blog post? Create a post in our Node.js community!

Written by
Corey Domingos
Specializing in Full-Stack modern web development, with a focus in Rest API development & deployment. Find my StackCafe community profile at coreydom!
Yes I would like to receive emails from the StackCafe Team for newsletters, how-to's, and community updates.