In this guide, we will explore how to build your very first simple REST API in a Node.js environment using the incredibly fast and popular Express.js framework.
1. Project Initialization and Express.js Installation
Before we begin writing any code, we need to initialize the Node.js environment in our project directory and install the Express library via the npm terminal.
# Initialize a new Node.js project (creates package.json) npm init -y # Install the Express.js framework npm install express
2. Coding the API Server (server.js)
Create a file named server.js. In it, we will set up basic endpoints that will return test table data to visitors or your frontend in JSON format:
const express = require('express');
const app = express();
const PORT = 3000;
// Enable Express to automatically parse incoming JSON data
app.use(express.json());
// Mock data (in a real world scenario, this would be fetched from a MySQL database)
const mockTables = [
{ id: 1, name: 'customers', rows: 150 },
{ id: 2, name: 'posts', rows: 16 },
{ id: 3, name: 'settings', rows: 5 }
];
// 1. Endpoint: Basic welcome route (GET request)
app.get('/', (req, res) => {
res.send('Welcome to my first Node.js API!');
});
// 2. Endpoint: Fetch all tables in JSON format (GET request)
app.get('/api/tables', (req, res) => {
res.json(mockTables);
});
// Start the API server
app.listen(PORT, () => {
console.log(`API server is successfully running at http://localhost:${PORT}`);
});
3. Launching and Testing the API
Launch your API via the terminal using the following command:
node server.js
Now open your web browser or a utility tool (like Postman) and navigate to: http://localhost:3000/api/tables. You will see a clean, structured JSON object displayed on your screen:
[
{"id":1,"name":"customers","rows":150},
{"id":2,"name":"posts","rows":16},
{"id":3,"name":"settings","rows":5}
]
This standardized format can now be easily consumed anywhere on your dynamic website using JavaScript (via the fetch() function) to
dynamically render data into your HTML layout.