Building a REST API with Node.js and MySQL, Fetching Data from API, and Rendering it in a Card using JavaScript and CSS.
Gurunath Kadam
Strategic Manager of Learning & Development | Subject Matter Expert | Oracle & Microsoft Certified | Educator | Software Developer | Corporate Trainer | Technical Speaker
In this comprehensive guide, we will explore the intricate process of building a robust RESTful API with Node.js, highlighting the seamless integration of MySQL as our database solution. Furthermore, we'll delve into the crucial steps required to fetch data from the API we've created and stylishly render it within a card layout using the power of JavaScript and CSS.
Let's begin!
Before we commence, ensure that you have the following installed:
Step 1: Setting Up the Project To begin, create a new directory for your project and navigate into it in the terminal.
mkdir nodejs-rest-api
cd nodejs-rest-api
Initialize your project with a package.json file.
npm init -y
Step 2: Installing Dependencies
We require the following Node.js modules:
(a) express for building the REST API.
(b) mysql2 for interacting with the MySQL database.
(c) CORS: Cross-Origin Resource Sharing facilitates web servers in specifying allowed origins for accessing server resources.
npm install express mysql2 cors
Step 3: Setting Up the Database Create a MySQL database and a table for our API. Here’s an example using MySQL:
CREATE DATABASE nodejs_rest_api;
USE nodejs_rest_api;
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL
);
领英推荐
Step 4: Creating the Express Server Create an index.js file and set up the server. [Modify the username and password to match your MySQL settings.]
const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'our_password',
database: 'nodejs_rest_api',
});
db.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err);
return;
}
console.log('Connected to MySQL database');
});
app.listen(PORT, () => {
console.log(`Server is running on https://localhost:${PORT}`);
});
Step 5: Creating API Endpoints Next, we'll construct CRUD (Create, Read, Update, Delete) endpoints for our products table. Below is the code to be added to the index.js file.
app.use('/products', cors());
// Get all users
app.get('/products', (req, res) => {
db.query('SELECT * FROM products', (err, results) => {
if (err) throw err;
res.json(results);
});
});
// Get a user by ID
app.get('/products/:id', (req, res) => {
const { id } = req.params;
db.query('SELECT * FROM products WHERE id = ?', [id], (err, results) => {
if (err) throw err;
res.json(results[0]);
});
});
// Create a new user
app.post('/products', (req, res) => {
const { name, description } = req.body;
db.query('INSERT INTO products (name, description) VALUES (?, ?)', [name, description], (err, result) => {
if (err) throw err;
res.json({ message: 'User added successfully', id: result.insertId });
});
});
// Update a user
app.put('/products/:id', (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
db.query('UPDATE products SET name = ?, description = ? WHERE id = ?', [name, description, id], (err) => {
if (err) throw err;
res.json({ message: 'User updated successfully' });
});
});
// Delete a user
app.delete('/products/:id', (req, res) => {
const { id } = req.params;
db.query('DELETE FROM products WHERE id = ?', [id], (err) => {
if (err) throw err;
res.json({ message: 'User deleted successfully' });
});
});
Explanation: The above code sets up a basic RESTful API server using Node.js and Express, and interacts with a MySQL database to perform CRUD (Create, Read, Update, Delete) operations on a table named "products". Here's a breakdown of the code:
Step 6: Testing the API
Initiate the server by executing the command node index.js in your terminal. Subsequently, you can perform HTTP requests to https://localhost:3000/products utilizing tools such as Postman or a web browser.
To retrieve data from the aforementioned API and display it in a card format using JavaScript and CSS, follow these steps:
Step 7: Create an HTML structure for the card and include a container where you'll render the data. Let's create a file named "products.html" and add the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample API Data</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<!-- Data will be rendered here -->
</div>
<script src="script.js"></script>
</body>
</html>
Step 8: Develop a CSS file named "styles.css" to customize the appearance of the card. Add the following code to the styles.css file.
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 20px;
}
.card {
border: 1px solid #ddd;
border-radius: 5px;
padding: 20px;
width: 300px;
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
background-color: #fff;
}
.card h2 {
font-size: 20px;
margin: 0;
}
.card p {
margin: 10px 0;
}
Step 9: Step 3: Create a JavaScript file named "script.js" to fetch data from the above-created API and display it within the card. Add the following code to the script.js file.
// Function to fetch data from the API
async function fetchData() {
try {
const response = await fetch('https://localhost:3000/products');
const data = await response.json();
return data;
console.log('Data:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Function to render data in cards
async function renderData() {
const container = document.querySelector('.container');
const data = await fetchData();
if (!data) {
return;
}
data.forEach(item => {
const card = document.createElement('div');
card.classList.add('card');
const title = document.createElement('h2');
title.textContent = item.name;
const body = document.createElement('p');
body.textContent = item.description;
card.appendChild(title);
card.appendChild(body);
container.appendChild(card);
});
}
// Call the renderData function to display data
renderData();
Explanation: The above code comprises JavaScript functions that facilitate fetching data from an API and rendering it in a card layout on a web page. Here's a breakdown:
Conclusion:
In this comprehensive guide, we embarked on a journey to construct a robust RESTful API using Node.js, coupled with MySQL as our database solution. We meticulously traversed each step, from setting up the project to creating API endpoints and integrating crucial functionalities.
Firstly, we ensured the prerequisites were met, including the installation of Node.js, npm, and MySQL server, setting the stage for seamless development.
We delved into the intricacies of Node.js modules, leveraging Express for API construction and MySQL2 for database interaction. Additionally, we integrated CORS (Cross-Origin Resource Sharing) to facilitate secure communication between client and server.
Our journey further led us to establish the database structure, where we meticulously defined the schema and tables using MySQL, paving the way for efficient data management.
The heart of our endeavor lay in creating the Express server, where we orchestrated the connection between client requests and database operations. Through meticulously crafted API endpoints, we facilitated CRUD (Create, Read, Update, Delete) functionalities, empowering users to manipulate data with ease.
Finally, we ventured into the realm of frontend development, employing JavaScript and CSS to breathe life into our data. By fetching API data and elegantly rendering it within a card layout, we crafted an immersive user experience that resonates with modern web standards.
In essence, this journey epitomizes the synergy between backend and frontend technologies, culminating in the creation of a dynamic and responsive web application. As you embark on your development endeavors, may this guide serve as a beacon of knowledge, empowering you to navigate the complexities of web development with confidence and finesse.
Let us continue to explore, innovate, and collaborate, as we unravel the boundless possibilities of technology in shaping our digital landscape. Until next time, let's continue to code boldly and create passionately.
Full stack developer | Java
1 年Thanks for sharing
Java Trainer @ EduBridge Learning Pvt. Ltd.
1 年Informative Article
Manager -Training Excellence/Trainer /Quality Accessor /Mentor/Coach
1 年Thank you for sharing
Java Full Stack Development Trainer
1 年Thanks for sharing
Junior Java Web Developer
1 年Thanks for posting