Create a Rest Api with Node.js & Express
Introduction
At the end of this tutorial, you will have a working REST API built with Node.js and Express that serves GET, POST, and static file requests.
All the code written in this tutorial can be found in this Github repository.
Let's get started!
Table of Contents
Install Node.js
First things first, you need to make sure you have the right software installed on your machine. For this tutorial, you'll need Node.js installed.
If you already have Node.js installed, you can skip to the Create ExpressJs Application section.
Otherwise, follow the section below that corresponds with your operating system.
Linux
For Linux, let's install Node.js via the command line using the NodeSource package archives.
First, we'll need to grab the NodeSource Personal Package Archive (PPA) to get access to its contents. Make sure you are in your home directory and then use curl to retrieve the installation script.
Open a terminal (CTRL+ALT+T) and run the following commands (replace the yellow text with the version of Node.js you wish to install):
$ cd ~
$ curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
$ sudo apt-get install -y nodejs
The PPA package has the nodejs binary in it along with npm, so you don't need to install it separately. But, to get npm packages to work, you'll need to install the build-essential package.
Run this command to do so:
$ sudo apt-get install build-essential
Node.js is now installed and ready to be used. Now it's time to build something with it!
macOS
To install Node.js on macOS, you have several options. First, you can simply download the macOS Installer direct from the Nodejs.org website.
Other alternative methods are listed below.
Download the package with bash:
$ curl "https://nodejs.org/dist/latest/node-${VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg.*|\1|p')}.pkg" > "$HOME/Downloads/node-latest.pkg" && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg" -target "/"
Using Homebrew:
brew install node
Using MacPorts:
$ pkgin -y install nodejs
Node.js is now installed and ready to be used. Now it's time to build something with it!
Windows
To install Node.js on Windows, simply download the Windows Installer directly from the Nodejs.org website.
Other alternative methods are listed below.
Using Chocolatey:
$ cinst nodejs.install
Using Scoop:
$ scoop install nodejs
Node.js is now installed and ready to be used. Now it's time to build something with it!
Create ExpressJs Application
Now that we have Node.js installed, we are ready to start building the Node.js application.
Npm Init
Create a directory to hold your application in and make that your working directory with these commands (replace the yellow text with your directory name):
$ mkdir app
And then move into the directory you just created with the cd command:
$ cd app
Now, let's use the npm init command to create a package.js file for your application. You can get more information on the purpose and components of the package.json file here.
Run the following command (make sure you're in the directory you created):
$ npm init
You'll be prompted for several things, like the name, version, and description of your application. You can hit ENTER for each of them to accept the defaults.
Your directory should now have a package.json file in it. It should look similar to the image below.
Npm Init Default Package.json File Contents
Here is a quick explanation for each component in the package.json file:
  • Name: This field only matters if you publish your package. And will tell people what the name of your thing is. The name and version of your package are the most important parts if you plan on publishing.
  • Version: The name and version together form an identifier that is assumed to be unique. Changes to the package should come along with changes to the version. If you don’t plan to publish your package, the name and version fields are optional.
  • Description: A string that helps people discover your package when it is listed in npm search.
  • Main: The filename that is the main entry point to your program and should be placed in the root directory of your application.
  • Scripts: A dictionary of script commands that are run at various times in the lifecycle of your package. Check out this page for more information.
  • Author: The name of the person or organization that created the package.
  • License: You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you’re placing on it. Check out the full list of SPDX license IDs. But you should choose one that is OSI approved.
Configure HTTP Server
For a REST API to work, the first thing we need is to have a HTTP server running.
To achieve this, let's first create our index.js entry point file with the following command (you can also create the index.js file manually with your code editor or file system gui):
$ touch index.js
Now, let's add some code to the new file.
Open the file in your favorite text editor and type the following code:
const express = require("express")
 
const PORT = process.env.PORT || 5000
const app = express()
 
app.get("/", (req, res) => {
  res.send("Welcome to your App!")
})
 
app.listen(PORT, function () {
  console.log(`Express server listening on port ${PORT}`)
})
This app starts a server on port 5000 and listens for connections. It will respond with "Welcome to your App!" to any requests to the root URL ("/") or route. Requests to any other path will receive a 404 Not Found error.
Run the app with the following command (make sure you are in the root of your app):
$ node index.js
You should see this output on your command line:
Output
 
Express server listening on port 5000.
To test the root URL route ("/"), go to this URL in your favorite browser:
http://localhost:5000
You should see a webpage with the message "Welcome to your App!" on it.
For testing purposes, try any different route URL in your browser:
http://localhost:5000/getData
You should see a webpage with the message "Cannot GET /getData".
In the next step, we will get this route working and have it retreive data for us.
Add Npm Start Script
To make things easier, let's add an npm start script to our package.json file. This will be a script that runs the index.js file when called.
Make the "scripts" section of your package.json file look like this:
...
 
"scripts": {
  "start": "node index.js"
},
 
...
Then, type this command in your terminal:
$ npm start
You should see the same output as when you ran node index.js
Add Request Methods that Return Data
We can now add a GET endpoint that takes in a request and returns data.
Json Placeholder provides free test data for prototyping a REST API. Whenever we get a request on our /getData route, we will retrieve data from them and return it.
GET Request
Update your index.js file to look like this:
const express = require("express")
const axios = require("axios")
 
const PORT = process.env.PORT || 5000
const app = express()
 
app.set("json spaces", 2)
 
app.get("/", (req, res) => {
  res.send("Welcome to your App!")
})
 
app.get("/getData", (req, res) => {
  axios.get("https://jsonplaceholder.typicode.com/posts")
    .then(function(response) {
      res.json(response.data)
    }).catch(function(error) {
      res.json("Error occured!")
    })
})
 
app.listen(PORT, function () {
  console.log(`Express server listening on port ${PORT}`)
})
Let's go over the changes we made to the index.js file.
First, we added a new npm package named Axios. This package makes HTTP requests easy and is what we will use to get the data from Json Placeholder.
Since we don't have Axios installed, we need to add it. Run this command to add it to our app's dependencies:
$ npm install axios --save
The second thing we added is the app.set("json spaces", 2) line. This adds indents to the JSON data that is returned by our endpoint, making the response data more human-readable.
The last thing we added was the new endpoint "/getData". Inside the app.get code block, we make a request to the JSON Placeholder API and return the data.
Let's test our new code!
Make sure your index.js file is saved and restart your app with the npm start command.
Then, go to your browser and visit this URL:
http://localhost:5000/getData
Your browser should show a similar response to the image below:
Browser Get Request Result
POST Request
Now, let's add a route that handles a POST request. Again, we will use the JSON Placeholder to retrieve data.
Update your index.js file to look like this:
const express = require("express")
const axios = require("axios")
const bodyParser = require("body-parser")
 
const PORT = process.env.PORT || 5000
const app = express()
 
app.set("json spaces", 2)
 
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
 
app.get("/", (req, res) => {
  res.send("Welcome to your App!")
})
 
app.get("/getData", (req, res) => {
  axios.get("https://jsonplaceholder.typicode.com/posts")
    .then(function(response) {
      res.json(response.data)
    }).catch(function(error) {
      res.json("Error occured!")
    })
})
 
app.post("/getUserById", (req, res) => {
  if (!req.body.id) {
    res.json("No ID found in reqest body.")
  } else {
    axios.get(`https://jsonplaceholder.typicode.com/users/${req.body.id}`)
      .then(function(response) {
        res.json(response.data)
      }).catch(function(error) {
        res.json("Error occured!")
      })
  }
})
 
app.listen(PORT, function () {
  console.log(`Express server listening on port ${PORT}`)
})
Let's go over the changes we made to the index.js file this time.
First, we added a new npm package named body-parser. This package serves as an express middleware that parses request bodies. This will allow us to get the data posted to the POST route.
Since we do not have the body-parser package installed, we need to add it. Run this command to add it to our app's dependencies:
$ npm install body-parser --save
Then we added two lines to configure the body-parser package: app.use(bodyParser.urlencoded({ extended: true })) and app.use(bodyParser.json()). Both of these lines allow us to get POST data from POST requests.
Last but not least, we added the app.post method that takes in the POST requests. The method returns an error response if it is not given a req.body.id value.
If a req.body.id value is given, we use axios to request the JSON Placeholder API and return the user with the given req.body.id. Then the data is returned in the response body.
Let's test our new code!
Open a new terminal window and execute this command to make a POST request using curl (if you're using Windows, you can download curl here):
$ curl --data "id=1" http://localhost:5000/getUserById
And the response data should look similar to this in your command line:
Output
 
{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556"
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}
Static Files
The last thing we'll cover is handling requests for static files. These could include anything from images, videos, json, and text files.
In this example, we will create a simple text file, place it in a new static folder, and configure our express application to handle requests for it.
First, we need to create a folder called static. Make sure you are in the root of your application and run the following command:
$ mkdir static
Then cd into your new folder:
$ cd static
And create a new folder called test.txt with this command:
$ touch test.txt
Open the test.txt file in your code editor and add these contents to it:
Test text file contents.
Save the text file and open your index.js file. We need to add one line to tell express to serve the files from our static folder.
Add this line of code anywhere in the file you wish (as long as it is below the require variable declarations at the top of the file):
...
 
app.use(express.static("static"))
 
...
Save the index.js file and restart your application with the npm start command.
Open a browser up to this URL:
http://localhost:5000/test.txt
You should see the contents of your test.txt file!
Try the same thing with different types of files (JSON, images, etc.) and check out the results.
Advertisement
Get $50 in Free Credit for 30 Days!
Try the simplest cloud server platform for developers & teams.
Sign Up Now
Conclusion
Congratulations, you now have a working REST API built with Node.js and Express that you can modify and/or add on to.
In the future, you may want to deploy your application out to the world. We have another tutorial that gives step-by-step directions on how to do that here.
We created a Github repository with all the code from this tutorial.
Let us know what you think in the comments!