Create a new database "crud" in phpmyadmin
Create a table "users" with fields id(int)(PRIMARY KEY), name(varchar(100)), location(varchar(100))
Create a folder "rest-api"
Open in vs code or any code editor
Open the terminal
npm init
npm install --save express mysql body-parsernpm install -g nodemonNote : if you have already installed the nodemon then skip this Step
Create a new file "index.js"
Firstly connect with database
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const mysql = require("mysql");
// parse application/json
app.use(bodyParser.json());
//Create Database Connection
const conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "crud",
});//at the bottom of the code
app.listen(8000, () => {
console.log("server started on port 8000...");
});Write code creating a new record
// creat a new Record
app.post("/api/create", (req, res) => {
let data = { name: req.body.name, location: req.body.location };
let sql = "INSERT INTO users SET ?";
let query = conn.query(sql, data, (err, result) => {
if (err) throw err;
res.send(JSON.stringify({ status: 200, error: null, response: "New Record is Added successfully" }));
});
});Write code for view all records
// show all records
app.get("/api/view", (req, res) => {
let sql = "SELECT * FROM users";
let query = conn.query(sql, (err, result) => {
if (err) throw err;
res.send(JSON.stringify({ status: 200, error: null, response: result }));
});
});Write code for view a single record
// show a single record
app.get("/api/view/:id", (req, res) => {
let sql = "SELECT * FROM users WHERE id=" + req.params.id;
let query = conn.query(sql, (err, result) => {
if (err) throw err;
res.send(JSON.stringify({ status: 200, error: null, response: result }));
});
});Write code for delete a record
// delete the record
app.delete("/api/delete/:id", (req, res) => {
let sql = "DELETE FROM users WHERE id=" + req.params.id + "";
let query = conn.query(sql, (err, result) => {
if (err) throw err;
res.send(JSON.stringify({ status: 200, error: null, response: "Record deleted successfully" }));
});
});Write code for update a record
// update the Record
app.put("/api/update/", (req, res) => {
let sql = "UPDATE users SET name='" + req.body.name + "', location='" + req.body.location + "' WHERE id=" + req.body.id;
let query = conn.query(sql, (err, result) => {
if (err) throw err;
res.send(JSON.stringify({ status: 200, error: null, response: "Record updated SuccessFully" }));
});
});Start the server
nodemon index.js