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.
For the code in this article to work, make sure you have Node.js installed on your local machine.
If you need one, we created a guide on installing Node.js.
Let's get started!
Table of Contents
Bootstrap The Express.js Application
Now that we have Node.js installed, we are ready to start building the Node.js application.
Create a Node.js Application
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.

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 acheive this, we need to first install the Express.js NPM package. We will use that package to easily create an HTTP server for our REST API.
npm install express --save
Then, we need to create an index.js
entry point file. You can do so 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:
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:

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:
{
"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.
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.
Thanks for reading and happy coding!