Building a REST API with Node.js and MySQL, Fetching Data from API, and Rendering it in a Card using JavaScript and CSS.

Building a REST API with Node.js and MySQL, Fetching Data from API, and Rendering it in a Card using JavaScript and CSS.


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:

  • Node.js and npm
  • MySQL server


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:

  1. Dependencies:express: This module allows us to create a web server and define routes.mysql2: This module enables us to connect to and interact with a MySQL database.cors: This module provides middleware to enable Cross-Origin Resource Sharing, which allows requests from one domain to another domain.
  2. Server Setup:We create an instance of the Express application and assign it to the variable app. We define the port on which the server will listen. It defaults to 3000, but it can be overridden by the PORT environment variable.
  3. Middleware:We use the express.json() middleware to parse JSON request bodies.
  4. Database Connection:We establish a connection to the MySQL database using the mysql.createConnection() method. We provide the host, user, password, and database name as configuration options.If there is an error during the connection process, we log the error to the console.
  5. Start Server:We start the Express server, and it listens for incoming requests on the specified port.Once the server is running, we log a message to the console indicating the server's URL.
  6. CORS Configuration:We use the cors() middleware to enable CORS for requests to the '/products' endpoint.
  7. Routes:GET /products: Retrieves all products from the 'products' table in the database and sends them as a JSON response.GET /products/:id: Retrieves a specific product by its ID from the 'products' table and sends it as a JSON response.POST /products: Creates a new product in the 'products' table based on data provided in the request body and sends a JSON response with a success message and the ID of the newly inserted product.PUT /products/:id: Updates an existing product in the 'products' table with the specified ID based on data provided in the request body and sends a JSON response with a success message.DELETE /products/:id: Deletes a product with the specified ID from the 'products' table and sends a JSON response with a success message.

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:

  1. fetchData() Function:This asynchronous function utilizes the fetch() API to make a GET request to the specified URL (https://localhost:3000/products).Upon receiving a response, it extracts the JSON data asynchronously using response.json().It returns the retrieved data.If an error occurs during the fetching process, it is caught by the try...catch block, and an error message is logged to the console.
  2. renderData() Function:This asynchronous function is responsible for rendering the fetched data onto the web page.It first selects the HTML element with the class name 'container', which serves as the parent element for the cards.Then, it calls the fetchData() function to retrieve the data asynchronously.If the data is successfully retrieved (i.e., not null or undefined), it iterates through each item in the data array.For each item, it creates a new div element with the class name 'card'.It creates h2 and p elements to represent the title and body of the card, respectively, and assigns them the corresponding content from the data item.Finally, it appends the title and body elements to the card, and the card to the container element.
  3. Call to renderData() Function:This line invokes the renderData() function, triggering the process of fetching data and rendering it onto the web page.

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.


Lavanya Murugan

Full stack developer | Java

1 年

Thanks for sharing

回复
Pooja Mehta

Java Trainer @ EduBridge Learning Pvt. Ltd.

1 年

Informative Article

回复
Sweta Prakash

Manager -Training Excellence/Trainer /Quality Accessor /Mentor/Coach

1 年

Thank you for sharing

回复
Pavitra Nagaral

Java Full Stack Development Trainer

1 年

Thanks for sharing

回复
PRASANTH R

Junior Java Web Developer

1 年

Thanks for posting

回复

要查看或添加评论,请登录

Gurunath Kadam的更多文章

社区洞察

其他会员也浏览了