Build a REST API with Node.js and Express
A beginner-friendly guide to setting up a professional RESTful API using Node.js, Express, and Environment variables.
Introduction
Node.js is a powerful runtime for building scalable server-side applications. In this guide, we will create a basic REST API that handles JSON data and utilizes middleware.
Step 1: Initialize the Project
First, create a new folder for your project and initialize it with a package.json file.
mkdir my-node-api
cd my-node-api
npm init -y
Step 2: Install Dependencies
We need express for the server framework and dotenv to manage our environment variables.
npm install express dotenv
Step 3: Create the Server
Create a file named index.js. This code sets up a basic server that listens on a specific port and returns a JSON response.
require('dotenv').config();
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON
app.use(express.json());
// Basic Route
app.get('/api/status', (req, res) => {
res.json({
status: 'Online',
message: 'API is running successfully'
});
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 4: Configure Environment Variables
Create a .env file in the same folder. This keeps your sensitive configurations separate from your logic.
PORT=5000
NODE_ENV=development
Step 5: Test the API
Run your server and use a tool like Postman or your browser to verify the output.
node index.js
You should see the JSON success message on your screen at http://localhost:5000/api/status.