Building RESTful APIs with Node.js & MySQL — Part 2
By: Isaac Coffie
Tags: Restful Api, MySQL, Rest Api, Expressjs, Nodejs

In part 1 of this series, we discussed briefly, the concept of APIs and more importantly RESTful APIs. We, additionally, downloaded, installed and created a node server with limited functionalities. In this section, we’ll dive deeper into creating the REST API endpoints for our BIMS as shown below:

Retrieve all books: GET /book/

Find a book by ID: GET /book/:id?

Save a book: POST /book

Update a book: PUT /book/:id

Delete a book: DELETE /book/:id

Setting up our database

Since our server will interact with a data source, we will have to create a data storage. And in this case, we shall use a MySQL database. Download and install MySQL by following this link if you are yet to do so.

MySQL: https://www.mysql.com/downloads/

You can also download XAMPP as it comes with MySQL: https://www.apachefriends.org/download.html

After installing XAMPP or MySQL Workbench, open the XAMPP Control Panel (we’re using XAMPP) and start the MySQL and Apache web server.

XAMPP Control Panel

XAMPP comes with a phpMyAdmin DBMS. You can access this DBMS by clicking on the MySQL Admin button as shown above. This will open the phpMyAdmin on your localhost.

phpMyAdmin interface

To create a new database, click on the new button on the left vertical menu as seen above. The name of the database we shall use is “bims”. Inside the bims database, create a table called book having the following attributes or columns and data types:

CREATE TABLE `book` ( `book_id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `title` varchar(50) NOT NULL, `year` int(11) NOT NULL, `author` varchar(100) NOT NULL )

After this process, your table structure should be similar to the table below.

Table structure

At this point, we’ve successfully created our data source in a MySQL database and now ready to link it to the Node.js server.

Database Configuration Files

One crucial element in any software development project is the concept of encapsulation: hiding details from the application layer. That said, we’ll hide the details of our database configuration details in a separate file named dbconnection.js. This file should be in the root directory of your project folder. You can look up the project folder in the previous tutorial.

The content of the dbconnection.js file is shown below.

database connection file

Code explanation:

We imported the MySQL Node.js connector on line 1 using the required keyword. We then created and exported a MySQL pool with the connection details. Note that we’re using localhost as our web server. You can also update the connection details if you’re using a password or your database server is hosted on the cloud.

Define the data model

In this section, we’ll create functions that can communicate with the database layer. If you’re familiar with SQL, you should find the queries below self-explanatory.

So, in your model folder, create a file called book_model.js.

The content of the file is shown below

book model file

In the code snippet above, we created a Book module that helps us to manipulate the content of our database.

Connecting the Model to the Controller

We’ll now register the functions in the book_model.js with the routes in the book_controller.js.

Fire up your book_controller.js file (which is located in the controller folder) and include important header files as follows:

controller header file

Here, we first imported the express JS framework. From the express app, we called the router object, which acts as a middleware to route API calls based on the endpoints and the HTTP method used. We then finally included the book_model.js file on line 3.

Let’s now define our API endpoints with code implementation

1) Insert a new book ==> POST /book/

Any book entry will be saved to our database through this endpoint. Using the body-parser module, this endpoint will parse and process the data (title, year and author) in the body of the request object using req.body. It will then call the createNewBook() function in the book_model.js. It finally sends a JSON object in response after insertion.

create new book item

2) Get all books ==> GET /book/

This API endpoint will return all books in the database. It simply calls the getAllBooks() function in the book_model.js

fetch all books

3) Get a book by ID ==> GET /book/:id?

This endpoint is designed to return a book when given its ID. We will first check if there’s an id field in the request parameter. If it does exist, we will parse this value (with the help of body-parser library) and pass it to the getBookById() function.

fetch book by ID

4) Update a book by ID ==> PUT /book/:id

An API endpoint for updating details of a book. It takes the book_id from the request parameter and the new book details from the request body. It returns a JSON response upon completion of the update operation.

update a book

5) Delete a book by ID ==> DELETE /book/:id

This route simply deletes a book when given an ID. It returns the number of affected rows afterwards.

delete a book

Don’t forget to export the router object so it can be accessible to other files when imported using the required keyword.

module.exports = router;

To this end, we have successfully created all the 5 REST API endpoints although we are yet to verify and validate their performance. We shall continue with the testing phase in part 3 of this series.

In case you missed part 1, you can have a good read here.