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!
A. Installing mysql
B. Connecting to database
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.
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.
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”.
Simple route for GETing results from a database is done!