In this tutorial, we will learn how to create a RESTful API using Express.js to fetch product data from a MySQL database. We will go through the process step-by-step, from setting up the database, creating the API routes, and testing the endpoints using tools like Postman.
Step 1: Install Express.js and MySQL
First, make sure you have Node.js installed on your machine. If not, you can download it from the official website https://nodejs.org/.
Next, create a new directory for your project and navigate to it in the terminal. Then, run the following commands to install Express.js and MySQL dependencies:
npm install express mysql
Step 2: Set up the MySQL database
Create a new MySQL database and a table to store product information. You can do this using a tool like phpMyAdmin or the MySQL command line. Here’s an example SQL script to create a products
table:
CREATE TABLE products (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
price DECIMAL(10, 2),
description TEXT
);
Step 3: Connect Express.js to MySQL
Create a new file called app.js
and add the following code to connect Express.js to the MySQL database:
const express = require('express');
const mysql = require('mysql');
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
connection.connect();
Replace your_username
, your_password
, and your_database
with your MySQL credentials.
Step 4: Create the API endpoints
Next, let’s create the API endpoints to fetch product data from the database. Add the following code to app.js
:
app.get('/products', (req, res) => {
connection.query('SELECT * FROM products', (error, results) => {
if (error) throw error;
res.json(results);
});
});
app.get('/products/:id', (req, res) => {
connection.query('SELECT * FROM products WHERE id = ?', [req.params.id], (error, results) => {
if (error) throw error;
res.json(results[0]);
});
});
Step 5: Start the Express.js server
Finally, start the Express.js server by adding the following code to app.js
:
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Now, run node app.js
in the terminal to start the server. You should see a message saying Server running on port 3000
.
Step 6: Test the API endpoints
To test the API endpoints, you can use a tool like Postman. Send GET requests to http://localhost:3000/products
to fetch all products or http://localhost:3000/products/{id}
to fetch a specific product by its ID.
That’s it! You’ve successfully created a RESTful API using Express.js to fetch product data from a MySQL database. Feel free to expand on this tutorial by adding more endpoints or implementing CRUD operations. Happy coding!