Build your own REST API in express

Sharmila S
May 26 · 4 min read

In this article, we will be creating a RESTful API in express (a node.js framework).

ReST stands for Representational State Transfer, it is an architectural style for designing APIs for applications.

Let’s try building a REST API in express framework.

  • We are going to define two routes with the methods GET, POST, DELETE, PUT, and PATCH.

If you aren’t familiar with the express, read this article to get started.

Let’s consider the following array as our database.

var books = [ 
{ id: 1, title: 'Origin', author: 'Dan Brown'},
{ id: 2, title: 'Death On The Nile', author: 'Agatha Christie' },
{ id: 3, title: 'Harry Potter and the order of phoenix', author: 'J K Rowling' }
];

Route /books

This route represents the entire table or collection.

We can get all entries using the GET method, create a new entry by using the POST method, delete all entries by making a DELETE request.

Here, we will be specifying the logic to return every entry in a table or a collection.

// get all books
app.get('/books', (req, res) => {
res.send({
books: books
})
});

The logic for adding a new entry to the table is specified in this method.

// add a new book
// route - /books?title=Murder%20On%20The%20Orient%20Express&author=Agatha%20Christie
app.post('/books', (req, res) => {

const newEntry = {
id : books.length + 1,
title : req.query.title,
author : req.query.author
};
// add it to array (database)
books.push(newEntry);
res.send({
msg: 'Book added'
});
});

Here, we are using query parameters to get the data for our new entry.

When the request is made to this route with the Delete method, every entry present in the table is deleted.

// delete all books
app.delete('/books', (req, res) => {
books.length = 0; //delete all elements
res.send('Successfully deleted all books!');
});

Route /books/:bookid

:bookid represents the id of a book entry. e.g. /books/1 is represents the entry with the value ‘1’ for id.

This route is designed to access and work with individual entries.

This method reads the entry with the given id value.

app.get('/book/:bookid', (req, res) => {    const bookid = Number(req.params.bookid);
const found = books.find(book => book.id === bookid);
res.send({
book: found
});
})

Here, we will be writing the code for deleting the entry with the given id from the table.

app.delete('/book/:bookid', (req, res) => {
const bookid = Number(req.params.bookid);
books = books.filter(book => book.id !== bookid)
res.send("Successfully deleted entry");
})

Both Put and Patch are used for updating a specific document, but the difference is the put method uses a whole updated entry to replace the entry in the database whereas the patch method takes only the properties to be updated and modifies only those properties and not the whole document.

To understand this better, let’s consider an example.

  • Following is the document to be updated.
const newBook = {
id: 12,
title: 'Percy Jackson',
author: 'Rick Riordon',
}
  • For the PUT request, we will be passing the whole document with updated values.
{
id: 12,
title: 'The Lightning Thief',
author: 'Rick Riordon'
}
  • For the PATCH request, we send only the values to be modified as follows:
{
title: 'The Lightning Thief'
}

Let’s try to implement it in our app.

// route - /book/:bookid?title=SomeTitle&author=SomeAuthorapp.put('/book/:bookid', (req, res) => {    const updated   = {
id : Number(req.params.bookid),
title : req.query.title,
tauthor : req.query.author
};
for (let i = 0; i < books.length; i++) {
if ( books[i].id === updated.id ) {
books[i] = updated; //update all properties
break;
}
}
res.send("Updated successfully");
});
app.patch('/book/:bookid',(req, res) => {    const bookid = Number(req.params.bookid);    for (let i = 0; i < books.length; i++) {
if ( books[i].id === bookid ) {
//update only the properties given
const toUpdate = Object.keys(req.query)
toUpdate.forEach(key => {
books[i][key] = req.query[key]
});

}
}
res.send("Updated successfully");
});

Github Repo -> https://github.com/SharmilaS22/medium-restapi-nodejs

Happy Learning!

featurepreneur

Features for everyone!