Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • Aptitude
  • Engineering Mathematics
  • Discrete Mathematics
  • Operating System
  • DBMS
  • Computer Networks
  • Digital Logic and Design
  • C Programming
  • Data Structures
  • Algorithms
  • Theory of Computation
  • Compiler Design
  • Computer Org and Architecture
Open In App
Next Article:
How to create API in Ruby on Rails?
Next article icon

How to Create a MySQL REST API

Last Updated : 19 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a REST API is important for enabling communication between different software systems. MySQL is one of the most popular relational database management systems which serves as the backbone for data storage in web applications.

In this article, we will learn how to create a REST API using MySQL as the database backend. We will cover the step-by-step process, starting from setting up the MySQL database to testing the API endpoints using tools like Postman or Curl.

What do you mean by REST API?

A RESTful API is an architectural style for designing application program interfaces (APIs) that utilize HTTP requests to interact with and manipulate data. Through operations such as GET, PUT, POST and DELETE, this API enables the retrieval, updating, creation and deletion of various data types and allows efficient resource management within applications.

How to Create a MySQL REST API?

Creating a REST API using MySQL as the backend is a fundamental skill for web developers. Let's go through the process of setting up a MySQL database, initializing a Node.js project installing dependencies setting up an Express server establishing a database connection, and implementing CRUD (Create, Read, Update, Delete) operations. By following these steps we will be able to create a robust API that interacts seamlessly with our MySQL database.

Step 1: Setup the MySQL Database

Let's start with creating a MySQL database and defining the necessary tables to store our data. we can use tools like MySQL Workbench or the command-line interface to do this task. For example, let's first create a simple database.

CREATE DATABASE my_db;

This statement will create a Database to store the data in the form of different tables.

Now, Create a table to store our data. For example, let's create a simple users table:

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
);

Step 2: Initialize Server Project

Now, Create a new folder for our project and navigate into it. Then, initialize a new Node.js project using follow command.

npm init -y

Step 3: Installing Dependencies

Now, install the required dependencies:

npm install express mysql

Step 4: Setup Express Server

Create a new file for e.g server.js (or any preferred name) and set up a basic Express server:

const express = require('express');
const mysql = require('mysql');

const app = express();
const port = 3000;

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Step 5: Establishing Database Connection

Let's connect our Node.js application to the MySQL database by creating a connection pool:

const conn= mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});

Step 6: Implementing CRUD Operations

Now, define routes and handlers to perform CRUD (Create, Read, Update, Delete) operations on the users table:

// Create a new user
app.post('/users', (req, res) => {
const { name, email } = req.body;
conn.query('INSERT INTO users (name, email) VALUES (?, ?)', [name, email], (err, result) => {
if (err) throw err;
res.send('User added successfully');
});
});

Explanation: This route allows us to create a new user by providing the user's name and email in the request body. The server inserts the provided data into the users table in the database.

Create a New User

  • Method: POST
  • Endpoint: /users
  • Description: This route allows us to create a new user by providing the user's name and email in the request body. The server inserts the provided data into the users table in the database.
POST /users
{
"name": "Geek",
"email": "geek@example.com"
}

Get all users

  • Method: GET
  • Endpoint: /users
  • Description: This route retrieves all users from the users table in the database and returns them as a JSON array.
 // Get all users
app.get('/users', (req, res) => {
conn.query('SELECT * FROM users', (err, rows) => {
if (err) throw err;
res.json(rows);
});
});

Explanation: This route retrieves all users from the users table in the database and returns them as a JSON array.

Get User by ID

  • Method: GET
  • Endpoint: /users/:id
  • Description: This route retrieves a specific user by their ID from the users table in the database and returns their information as a JSON object.
// Get user by ID
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
conn.query('SELECT * FROM users WHERE id = ?', userId, (err, rows) => {
if (err) throw err;
res.json(rows[0]);
});
});

This route retrieves a specific user by their ID from the users table in the database and returns their information as a JSON object.

Update User by ID

  • Method: PUT
  • Endpoint: /users/:id
  • Description: This route updates the information of a specific user identified by their ID. Clients provide the updated name and email in the request body, and the server updates the corresponding record in the users table.
 // Update user by ID
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
const { name, email } = req.body;
conn.query('UPDATE users SET name = ?, email = ? WHERE id = ?', [name, email, userId], (err, result) => {
if (err) throw err;
res.send('User updated successfully');
});
});

This route updates the information of a specific user identified by their ID. Clients provide the updated name and email in the request body, and the server updates the corresponding record in the users table.

Example:

PUT /users/123
{
"name": "Geekina",
"email": "geekina@example.com"
}

Delete User by ID

  • Method: DELETE
  • Endpoint: /users/:id
  • Description: This route deletes a specific user from the users table in the database based on their ID.
// Delete user by ID
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
conn.query('DELETE FROM users WHERE id = ?', userId, (err, result) => {
if (err) throw err;
res.send('User deleted successfully');
});
});

Example

DELETE /users/123

This route deletes a specific user from the users table in the database based on their ID.

Step 7: Testing the API

Finally, start our Express server by running follow command:

 node server.js 

Test your API endpoints using tools like Postman or curl. we can send HTTP requests to GET, POST, PUT, and DELETE data from the users table.

Conclusion

Creating a REST API with MySQL backend is a crucial skill for web developers. By following the steps outlined in this guide, you can build a robust API that interacts seamlessly with your MySQL database. Remember to handle errors easily and secure your API endpoints to ensure the integrity and confidentiality of your data. With this knowledge, you can create powerful and efficient web applications that meet the needs of modern software systems.


Next Article
How to create API in Ruby on Rails?

S

sahilali
Improve
Article Tags :
  • DBMS
  • Dev Scripter 2024

Similar Reads

    How to Create A REST API With JSON Server ?
    Setting up a RESTful API using JSON Server, a lightweight and easy-to-use tool for quickly prototyping and mocking APIs. JSON Server allows you to create a fully functional REST API with CRUD operations (Create, Read, Update, Delete) using a simple JSON file as a data source. Table of Content GET Re
    4 min read
    Create a CRUD API With PostgREST
    In today's fast-paced world, businesses rely heavily on efficient data management systems to streamline operations and deliver optimal services. One such tool that has gained popularity for its simplicity and effectiveness is PostgREST. In this article, we'll explore how you can harness the power of
    5 min read
    How to Connect to MySQL Server
    MySQL is a widely utilized open-source relational database management system (RDBMS) known for its popularity and effectiveness in handling and structuring massive amounts of data. If you are a developer, data analyst, or someone who needs to store and manage data, MySQL is a highly adaptable and de
    5 min read
    How to create API in Ruby on Rails?
    Building APIs with Ruby on Rails: A Step-by-Step GuideRuby on Rails (Rails) is a popular framework for web development, known for its convention over configuration approach. It also excels in creating robust and maintainable APIs (Application Programming Interfaces). APIs act as intermediaries, allo
    3 min read
    How to Connect Node.js Application to MySQL ?
    To connect the Node App to the MySQL database we can utilize the mysql package from Node Package Manager. This module provides pre-defined methods to create connections, query execution and perform other database related operations. Approach to Connect Node App to MySQLFirst, initialize the node.js
    2 min read
    How To Use an API? The Complete Guide
    APIs (Application Programming Interfaces) are essential tools in modern software development, enabling applications to communicate with each other. Whether you're building a web app, mobile app, or any other software that needs to interact with external services, understanding how to use an API is c
    4 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences