How to Create a MySQL REST API
Last Updated :
19 Mar, 2024
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": "[email protected]"
}
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": "[email protected]"
}
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.
Similar Reads
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
DBMS Tutorial â Learn Database Management System Database Management System (DBMS) is a software used to manage data from a database. A database is a structured collection of data that is stored in an electronic device. The data can be text, video, image or any other format.A relational database stores data in the form of tables and a NoSQL databa
7 min read
Introduction of ER Model The Entity-Relationship Model (ER Model) is a conceptual model for designing a databases. This model represents the logical structure of a database, including entities, their attributes and relationships between them. Entity: An objects that is stored as data such as Student, Course or Company.Attri
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Introduction of DBMS (Database Management System) A Database Management System (DBMS) is a software solution designed to efficiently manage, organize, and retrieve data in a structured manner. It serves as a critical component in modern computing, enabling organizations to store, manipulate, and secure their data effectively. From small application
8 min read
SQL Query Interview Questions SQL or Structured Query Language, is the standard language for managing and manipulating relational databases such as MySQL, Oracle, and PostgreSQL. It serves as a powerful tool for efficiently handling data whether retrieving specific data points, performing complex analysis, or modifying database
15+ min read