Building REST APIs with MySQL and Node.js

Lets try to build a RESTful API to do GET operation on a MySQL database. A lot of developers wants to map REST to CRUD directly, because REST over HTTP provides GET PUT POST and DELETE, while CRUD provides CREATE RETRIEVE UPDATE DELETE. It’s natural to want to map the REST provisions directly to CRUD operations and we’re gonna try that.

How are we going to do?

Building APIs with nodeJS is dead simple, especially when you’re a beginner, you can opt for expressJS to build your very first API sets.

Lets kick start!

I’ve used express-generator to generate a directory called apidemo. In my mysql server, I have a database called “test”. I’m establishing connection between node and my mysql database.

A. Installing mysql

Installing mysql node module

B. Connecting to database

Connecting to database in app.js

Step 1 of my mission is done, and I’m going to get into renaming route to make my API naming conventions look professional. Check the highlighted line in your generated application.

We will be redefining the /users convention now!

I’m renaming the routing convention of the highlighted line to “/api/v1/users”.

I’m tweaking my users.js to fetch result from the database(Retrieve in CRUD). We’ve already established connection to DB in the previous step, in this step we’ll use GET method to get the list of users via the API that we’re constructing.

Let’s use POSTMAN to check the API that we’ve just built.

POSTMAN snapshot of the API we’ve just built.

Now that we’ve made the basic skeleton of the API, let’s complete the structure properly. When we have no server errors, the API is going to work, but when we have some issue, the end-user of the API will have no clue about what went wrong! Here’s how he will get idea about what went wrong!

Lets check the error response! I’m renaming the “users ”table in my database to “members”.

API error response shows that there’s no users table in the other end!

Simple route for GETing results from a database is done!

NodeJS is simple yet powerful programming boon for API making. UBER, IBM, PayPal, NETFLIX and MICROSOFT relies on nodeJS for constructing APIs. If you’re good at front-end javascript development, go ahead with learning the back-end javascript!