Create RESTful API Using Node.js & Express 4

Creating a RESTful API with Node.js and Express 4 can be a straightforward process with the right understanding and tools. This tutorial will guide you through the steps of setting up a RESTful API using these technologies. We’ll also use MySQL to interact with our database.

Setting Up Your Environment

Before we begin, ensure that you have Node.js installed on your machine. If not, you can download it from the official Node.js website. You’ll also need to have MySQL installed.

Next, we’ll need to install a few Node.js modules:

  • Express 4: A fast, unopinionated, and flexible web application framework for Node.js.
  • Body-parser: A middleware that parses incoming request bodies before your handlers and is available under the req.body property.
  • MySQL: A Node.js module that allows you to easily interact with MySQL databases.

You can install these modules using npm (Node Package Manager) with the following command:

npm install express body-parser mysql

Initializing Your Application

Create a new file named server.js. This file will serve as the entry point for our application. In this file, we’ll require our modules and set up our HTTP server.

var express = require('express'); 
var app = express(); 
var http = require('http').Server(app); 
var mysql = require('mysql'); 
var bodyParser = require("body-parser"); 

var connection = mysql.createConnection({ 
  host : 'localhost',
  user : 'root',
  password : '',
  database : 'books',
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Creating the API Endpoints

Now that we have our server set up, we can start creating our API endpoints. For this tutorial, we’ll create endpoints to show a list of books, add a new book, update an existing book, and delete a book.

Show List of Books

To fetch all books, we’ll create a GET endpoint at /books. This endpoint will return all book data in JSON format.

app.get('/books', function(req, res) {
  connection.query("SELECT * from book", function(err, rows, fields) {
    if (err) {
      res.json({"error" : true, "message" : "Error executing MySQL query"});
    } else {
      res.json({"error" : false, "message" : "Success", "books" : rows});
    }
  });
});

Add a New Book

To add a new book, we’ll create a POST endpoint at /books. This endpoint will accept JSON data with the details of the new book and add it to the database.

app.post('/books', function(req, res) {
  var book = req.body.book;
  connection.query("INSERT INTO book SET ?", book, function(err, results) {
    if (err) {
      res.json({"error" : true, "message" : "Error executing MySQL query"});
    } else {
      res.json({"error" : false, "message" : "Book added successfully"});
    }
  });
});

Update an Existing Book

To update an existing book, we’ll create a PUT endpoint at /books/:id. This endpoint will accept JSON data with the updated details of the book and update the corresponding book in the database.

app.put('/books/:id', function(req, res) {
  var id = req.params.id;
  var book = req.body.book;
  connection.query("UPDATE book SET ? WHERE id = ?", [book, id], function(err, results) {
    if (err) {
      res.json({"error" : true, "message" : "Error executing MySQL query"});
    } else {
      res.json({"error" : false, "message" : "Book updated successfully"});
    }
  });
});

Delete a Book

To delete a book, we’ll create a DELETE endpoint at /books/:id. This endpoint will delete the corresponding book from the database.

app.delete('/books/:id', function(req, res) {
  var id = req.params.id;
  connection.query("DELETE FROM book WHERE id = ?", id, function(err, results) {
    if (err) {
      res.json({"error" : true, "message" : "Error executing MySQL query"});
    } else {
      res.json({"error" : false, "message" : "Book deleted successfully"});
    }
  });
});

Running the Server

To start the server, run the following command in your terminal:

node server.js

Your server should now be running and ready to accept requests. You can test your API endpoints using a tool like Postman or curl.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts