MySQL with Node.js and Express.js

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.
Date: 2021-05-18
Building a RESTful API with Node.js, Express.js, and MySQL: A Comprehensive Guide
This article details the process of creating a RESTful API using Node.js, Express.js, and a MySQL database. A RESTful API, or Representational State Transfer Application Programming Interface, is a standardized way for applications to communicate with each other over the internet. It adheres to specific architectural constraints, making it scalable, stateless, and cacheable. The API uses HTTP requests, primarily employing the POST, PUT, GET, and DELETE methods to create, update, retrieve, and delete data respectively. Express.js serves as a powerful Node.js framework, simplifying the development of web and mobile applications by providing a robust feature set.
Setting up the Development Environment
Before beginning, you'll need a few key components installed. First, you'll need Node.js and its package manager, npm, installed on your system. For Windows users, this typically involves downloading an installer from the official Node.js website and following the on-screen instructions. After installation, you can verify the installation by opening a command prompt and typing node -v and npm -v. Successful execution will display the installed versions.
Next, a MySQL database and phpMyAdmin (or a similar MySQL administration tool) are necessary. The article suggests using Docker to simplify the setup of both. Docker allows you to run these components in isolated containers, eliminating potential conflicts with existing software and providing a consistent development environment. The specific Docker commands for setting up MySQL and phpMyAdmin would be executed in your terminal. These commands automate the process of downloading the necessary images and starting the containers, making the process considerably simpler. After the containers are running, you can access phpMyAdmin through a web browser, typically at a specified local address.
Creating the Database and Sample Data
Using phpMyAdmin, a database—let’s call it 'test'—should be created. The next step involves creating a table within the database to store the application's data. This is achieved using SQL commands. Specifically, an SQL script (referred to as Users.sql in the original) would be executed within phpMyAdmin to define the table structure (columns, data types, etc.) and potentially insert some initial sample data. This provides a functional database for testing and demonstration purposes. The details of the table structure and sample data are not provided in the original text but are necessary for the application's functionality.
Building the Node.js Application
With the database set up, we can now build the Node.js application using Express.js. The first step is to create a project directory, navigate to it using your terminal or command prompt, and initialize a Node.js project using npm init -y. This generates a package.json file, which acts as a manifest for the project, storing metadata like dependencies and scripts.
Next, the required dependencies are added to the package.json file. This involves adding entries for Express.js (for handling HTTP requests), a MySQL client library (for interacting with the database), and Nodemon (a tool that automatically restarts the Node.js application upon detecting changes in the code). After saving the updated package.json file, run npm install to download and install the specified dependencies. These dependencies are installed into a node_modules folder in your project directory.
Creating the API Logic
The core functionality of the API resides in two key files: apis.js and index.js. The apis.js file, often placed within a 'controller' folder to logically organize code, contains the functions for interacting with the MySQL database. This file would utilize the installed MySQL client library to create a connection pool, providing efficient management of database connections. The file is designed to have separate functions for each of the CRUD (Create, Read, Update, Delete) operations. Each function would perform the corresponding SQL queries to interact with the database. For instance, the create function would insert data into the table, the read function would select data, and so on.
The index.js file acts as the entry point for the server. It imports the Express.js library and the functions from apis.js. In this file, the API endpoints are defined, mapping each HTTP method (GET, POST, PUT, DELETE) to the appropriate function from apis.js. For example, a POST request to the /users endpoint might be mapped to the create function in apis.js, handling the creation of new user data in the database. Similarly, a GET request to the same endpoint might be mapped to the read function, retrieving all user data.
Running the Application and Testing Endpoints
After creating the necessary files, the Node.js application can be run from the command line. Executing a command (likely node index.js or nodemon index.js if using Nodemon) starts the Express.js server, listening on a specific port (e.g., 10091, as specified in the original). You can test the API endpoints using tools such as Postman, sending HTTP requests to the different endpoints and observing the responses. Each endpoint represents a specific operation on the data, corresponding to the functions defined in apis.js.
Conclusion
This article provides a high-level overview of building a RESTful API with Node.js, Express.js, and MySQL. The process involves setting up the environment, creating the database and tables, defining the API endpoints, and managing the interaction with the database. This structured approach enables efficient and maintainable backend development for web and mobile applications. Remember that error handling, security considerations, and more sophisticated data validation are crucial aspects for production-ready applications, which were not fully detailed in this conceptual overview.