Tech Arise

NodeJS RESTfull APIs with Express and MySQL

RESTful web APIs are typically loosely based on HTTP methods to access resources via URL-encoded parameters and the use of JSON or XML to transmit data. RESTful Web services are one way of providing interoperability between computer systems on the Internet. Rest API helps to communicate between the client app and the server application. REST is an architecture style for designing networked applications. A REST API defines a bunch of functions which developers can perform requests and receive responses via HTTP protocol such as GET and POST.
In this tutorial, you will learn to how create CRUD (create, read, update, delete) operation RESTful APIs NodeJS with Express and MySQL. This is a very simple example, you can just copy-paste, and change according to your requirements.
Before started to implement the NodeJS RESTfull APIs with Express and MySQL, look files structure:
Understanding REST API
REST provides a block of HTTP methods which are used to alter the data. The following are common HTTP methods:
Step 1: Create MySQL Database and Table
For this tutorial, you need a MySQL database with the following table:
Set Up and Run a Simple Node Server
Let’s build our web server. Create a file named index.js
Step 2: Create file named .env
loads environment variables
Step 3: Connect to Database file named db.config.js inside “application/config/” folder.
The code below shows the database credentials
Step 4: Create models
Create a models file named news.model.js inside “application/models/” folder.
Step 5: Create controllers
Create a controllers file named news.controller.js inside “application/controllers/” folder.
Step 6: Create routes
Create a routes file named routes.js inside “application/routes/” folder.

Run Application
Now we will use Postman to run RESTful APIs.
POST Method: Save News in the database
GET method: Find a single News with a newsId.
GET method: Get all News from the database.
PUT Method: Update a News records
DELETE Method: Delete a News with the specified newsId in the request
DELETE Method: Delete all News from the database.
Exit mobile version