Node.js Building a REST API with Node, Express, TypeScript, and MySQL
- codeagle
- Aug 28, 2024
- 4 min read
In modern web development, building a robust and scalable REST API is essential for powering dynamic web applications. This blog post will guide you through creating a RESTful API using Node.js, Express, TypeScript, and MySQL. By the end of this tutorial, you'll have a solid understanding of how to set up a TypeScript-based Node.js project, connect it to a MySQL database, and build endpoints to perform CRUD operations.

Prerequisites
Before diving in, ensure you have the following installed on your machine:
Node.js (v14.x or later)
npm (comes with Node.js)
TypeScript (installed globally via npm)
MySQLÂ (local or remote database)
Step 1: Set Up Your Project
First, let's create a new directory for our project and initialize it with npm.
mkdir node-express-ts-api
cd node-express-ts-api
npm init -y
Next, install the necessary dependencies:
npm install express mysql2
npm install --save-dev typescript ts-node @types/node @types/express
This will install Express for handling HTTP requests, mysql2 for interacting with MySQL, and TypeScript along with type definitions.
Step 2: Configure TypeScript
Create a tsconfig.json file to configure TypeScript:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"]
}
This configuration ensures TypeScript compiles the code to a dist directory, with the source files located in the src directory.
Step 3: Create the Express Server
Let's set up a basic Express server in TypeScript. Create a src directory and add an index.ts file:
mkdir src
touch src/index.ts
Inside src/index.ts, add the following code:
import express from 'express';
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This code initializes an Express server that listens on port 3000 (or a port defined in the environment) and responds with "Hello, World!" on the root route.
Step 4: Set Up MySQL Connection
Next, let's connect to a MySQL database. Create a new file src/database.ts:
import mysql from 'mysql2';
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err.stack);
return;
}
console.log('Connected to the MySQL database.');
});
export default connection;
Replace your_username, your_password, and your_database with your actual MySQL credentials and database name.
Step 5: Create the REST API Endpoints
Let's create CRUD endpoints for managing a users table in our database. First, ensure your MySQL database has a users table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL
);
Now, create a new file src/routes/users.ts:
import { Router } from 'express';
import connection from '../database';
const router = Router();
// Get all users
router.get('/', (req, res) => {
connection.query('SELECT * FROM users', (error, results) => {
if (error) {
return res.status(500).json({ error });
}
res.json(results);
});
});
// Get user by ID
router.get('/:id', (req, res) => {
const { id } = req.params;
connection.query('SELECT * FROM users WHERE id = ?', [id], (error, results) => {
if (error) {
return res.status(500).json({ error });
}
if (results.length === 0) {
return res.status(404).json({ message: 'User not found' });
}
res.json(results[0]);
});
});
// Create a new user
router.post('/', (req, res) => {
const { name, email } = req.body;
connection.query('INSERT INTO users (name, email) VALUES (?, ?)', [name, email], (error, results) => {
if (error) {
return res.status(500).json({ error });
}
res.status(201).json({ id: results.insertId, name, email });
});
});
// Update a user
router.put('/:id', (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
connection.query('UPDATE users SET name = ?, email = ? WHERE id = ?', [name, email, id], (error, results) => {
if (error) {
return res.status(500).json({ error });
}
if (results.affectedRows === 0) {
return res.status(404).json({ message: 'User not found' });
}
res.json({ message: 'User updated successfully' });
});
});
// Delete a user
router.delete('/:id', (req, res) => {
const { id } = req.params;
connection.query('DELETE FROM users WHERE id = ?', [id], (error, results) => {
if (error) {
return res.status(500).json({ error });
}
if (results.affectedRows === 0) {
return res.status(404).json({ message: 'User not found' });
}
res.json({ message: 'User deleted successfully' });
});
});
export default router;
Step 6: Integrate Routes into the Server
Modify src/index.ts to include the users routes:
import express from 'express';
import usersRouter from './routes/users';
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use('/users', usersRouter);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 7: Run the Application
Compile the TypeScript code and start the server:
npx tsc
node dist/index.js
Your REST API is now up and running! You can test the endpoints using a tool like Postman or curl:
GET /users: Retrieve all users.
GET /users/: Retrieve a specific user by ID.
POST /users: Create a new user (requires name and email in the request body).
PUT /users/: Update a user by ID (requires name and email in the request body).
DELETE /users/: Delete a user by ID.
Conclusion
In this blog post, we've built a simple REST API using Node.js, Express, TypeScript, and MySQL. This setup is a solid foundation for more complex applications, allowing you to add features like authentication, validation, and more advanced querying. With the power of TypeScript, you can write safer, more maintainable code while leveraging the performance and scalability of Node.js.