Skip to content

RESTful API - Example

Users REST API

This example uses a local file to import the data and the data is not persistent as was the case with JSON server. This example is showing different method requests made to the same endpoint, showing that the method used is determining the logic that is being executed by the server. This exercise will store all the users data with JSON, without any interactions to the real database.

Routes

Here is a simple chart of basic REST APIs you will make for your users application:

Resource GET read POST create PUT update DELETE
/api/users Returns a list of users Create a new user - -
/api/users/:id Returns a specific user - Updates a specific user Deletes a specific user

Project

Create a new Node.js application and install Express, Nodemon and dotenv.

1
2
3
npm i express
npm i --save-dev nodemon
npm i dotenv

Users data

You can use a below starting users data in your application.

data.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const users =
[
  {
    "id": 1,
    "name": "Kirsi Kernel",
    "email": "kirsi@kernel.com",
    "phone": "012-345678"
  },
  {
    "id": 2,
    "name": "John Smith",
    "email": "john@smith.com",
    "phone": "021-876543"
  },
  {
    "id": 3,
    "name": "Mark Donnell",
    "email": "mark@donnell.com",
    "phone": "033-838465"
  }
]

module.exports = { users }

Save file to your project folder.

Add environment variables to a .env file

Create a .env file in the root of your project and and PORT variable.

1
PORT=3000

Note

Remember create a .gitignore file and add .env and node_modules.

Users data

Modify your index.js to use Express and dotenv.

index.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
require('dotenv').config()
const express = require('express') 
const app = express()
const port = process.env.PORT

// json parser middleware
// parse incoming requests with JSON, assign it to requests body
app.use(express.json())

// use sample users data
let { users } = require('./data')

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

GET all the users (CRUD)

Create a new API endpoint (route) to handle GET request and return all the users.

GET method
1
2
3
app.get('/api/users', (req, res) => {
  res.status(200).json({success:true,data:users})
})

Test GET request to http://localhost:3000/api/users/ with a Postman or browser. You should see the returned JSON data.

!Image 01

GET one user (CRUD)

Create a new API endpoint (route) to handle single user with GET request.

GET method
1
2
3
4
5
6
app.get('/api/users/:id', (req, res) => {
  const { id } = req.params
  const user = users.find(user => user.id === id)
  if (user) res.status(200).json({success:true,data:user})
  else res.status(404).json({success:false,error:"User not found!"})
})

Now route id parameter is used as a our user id. Correct user will be find from the users collection and found user data will be returned to the caller or 404 status code with error message if user can not be found.

Note

You will need to use : to add parameters to route path.

Test GET request to http://localhost:3000/api/users/1 with a Postman or browser. You should see the returned user JSON data.

!Image 02

Remember test also id which doesn't exists.

!Image 03

DELETE one user (CRUD)

One user can be deleted with using HTTP DELETE request. Request looks the same as above get one user, only a DELETE is used as a request.

DELETE method
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
app.delete('/api/users/:id', (req, res) => {
  const { id } = req.params
  // find user 
  const user = users.find((user) => user.id === Number(id))
  // user not found
  if (!user) {
    return res
      .status(404)
      .json({ success:false, message:`No user found with id ${id}` })
  }
  // filter user with id away from users collection
  users = users.filter(user => user.id !== Number(id))
  // return users
  res.status(200).json({ success: true, data: users })
})

Use DELETE request to delete one of the users from server.

!Image 04

Remember try to delete user which doesn't exists.

!Image 05

Finally request all the users again to see changes.

!Image 06

PUT user data (CRUD)

You can use PUT request to update user data in server side.

PUT method
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
app.put('/api/users/:id', (req, res) => {
  const { id } = req.params
  const { name, email, phone } = req.query
  const user = users.find(user => user.id === Number(id))
  // user not found
  if (!user) {
    return res
      .status(404)
      .json({ success:false, message:`No user found with id ${id}` })
  }
  // update user data
  user.name = name
  user.email = email
  user.phone = phone
  res.status(200).json({ success: true, data: users })
})

Use PUT request to send a new user data to server. Use Query Params to set a new user name and click Send button to send a new request to server. Use URI which contains some of your users id, for example: http://localhost:3000/api/users/1

Note

Query parameters are appended to the end of the request URL, following ? and listed in key value pairs, separated by & using the following syntax:

/api/users/1?name=Pekka Peloton&email=pekka@email.com&phone=040-1233212

Look how request URI will include your user name to query parameters. Send request to server side and look response in Postman.

!Image 07

POST user data (CRUD)

You can use POST request to add a new user data in server side.

POST method
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
app.post('/api/users/', (req, res) => {
  // find max id used by users
  const maxId = Math.max(...users.map(user => user.id), 0)
  // get user from request
  const user = req.body
  if (!name) {
    return res
      .status(400)
      .json({ success: false, msg: 'No user value provided!' })
  }
  // add a new user
  user.id = (maxId+1).toString() 
  users = users.concat(user) 
  res.status(201).json({ success: true, data: users })
})

Note

JavaScript map function will return all the id's in an array and ... moves array to integer values. So, now max function can find the biggest id value. New user will be added to users with JavaScript arrays concat function.

Read more about

Use Postman to send POST request to server side. This time we will use JSON data, which will be included in request body.

  • Change request type to POST
  • Use http://localhost:3000/api/users/ route
  • Select body and raw to write use JSON data
  • Remember select JSON data type
  • Write user as JSON data
json data
1
2
3
4
5
{
  "name" : "Matt Markusson",
  "email" : "matt@markusson.com",
  "phone" : "020-2022332"
}
  • Send request to server side

!Image 07

In a server side, data will be inside request.body object. You can use Express JSON parser to get it easily. This express.json() is a built-in middleware function in Express. Express JSON parser will change the incoming JSON data (inside request) to JSON object and it will available inside request.body object.

index.js
1
2
3
4
const express = require('express') 
const app = express()
app.use(express.json())
///...

Goals of this topic

Understand

  • What ExpressJS is.
  • Know how to create a simple Express application.
  • Know how to use routing in Express.
  • Know what environmental variables are and how to use them.