Creating Complete REST API using Node js Express and MySQL
How to create RESTful API in Node.js, Express and MySQL?
A RESTful (Representational State Transfer) API is an application program interface (API) that uses HTTP requests to GET, POST, PUT and DELETE data. If you want to interact with a service, you generally use an API. Node.js is best the open source server environment for creating an API.
In this lesson we will learn how to create rest api using Node.js, Express and MySQL Database with request methods GET, POST, PUT and DELETE.
I have taken an example for calling api in PHP using CURL. You can use this api in technology like as Angular, React, DotNet, PHP, etc.
First of all, Have installed Node.js in your system? if Yes then follow next steps otherwise you can watch this video Node.js Installation.
Intallation express-generator tool
We will install
express-generator tools globaly. If you have already installed
express-generator tool then no need to install.
Create a Application
Create a application using
Install mysql node modules in node.js
Before use mysql in Node.js must be ensured MySQL Database should be installed in your machine. You can see Installing MySQL documentation.
Install mysql node modules in your application.
Create a Custom Module for Database Connection
Create a db.js file in the root folder for database connection and use this connection in your entire project. Connect your database using your MySQL database credential host, database user, database password and database name.
Create a file routes/products.js for add, edit, views and delete products.
Edit app.js file and import
var productsRouter = require('./routes/products'); and set products route
Complete code app.js
Calling API in PHP
We are calling this api in PHP using CURL. But you can call this api in any technologies like as Angular, React, etc.
Create a table products
Run the app
Then load http://localhost:3000/ in your browser to access the app.
You can check this url http://localhost:3000/products for products json data.
You can run above PHP code on your machine for calling this api with all methods GET, POST, PUT and DELETE
In this lesson we have learned setup of Node.js environment, installation of
express-generator tool and create an application using
express-generator. Create a complete RESTful API in Node.js, Express and MySQL. We have used request methods GET, POST, PUT and DELETE and called this api in PHP.