Node.js & ExpressIntermediate 7 min read
Node.js & Express: Build Your First REST API
Node.js lets you run JavaScript on a server. Express is a small framework that makes building APIs — the backend of every app — simple.
By Learn Refill Mentors · Updated
Why learn Node.js & Express?
- Use the same language (JavaScript) for frontend and backend
- Express powers thousands of production APIs
- The 'N' and 'E' in the MERN stack
1Set up the project
Create a folder, initialise npm and install Express.
Terminal
mkdir my-api && cd my-api
npm init -y
npm install express2Create your first server
This server answers requests on port 5000.
JavaScript
const express = require("express");
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.json({ message: "API is running" });
});
app.listen(5000, () => console.log("Server on port 5000"));3Add CRUD routes
GET reads data, POST creates it. req.body holds the JSON sent by the client.
JavaScript
const students = [];
app.get("/students", (req, res) => res.json(students));
app.post("/students", (req, res) => {
const student = { id: Date.now(), ...req.body };
students.push(student);
res.status(201).json(student);
});4Use route parameters
Values in the URL like /students/42 are available in req.params.
JavaScript
app.get("/students/:id", (req, res) => {
const s = students.find((x) => x.id === Number(req.params.id));
if (!s) return res.status(404).json({ error: "Not found" });
res.json(s);
});5Add middleware
Middleware runs before your routes — perfect for logging or checking login.
JavaScript
function logger(req, res, next) {
console.log(req.method, req.url);
next();
}
app.use(logger);Common mistakes
- Forgetting app.use(express.json()) so req.body is undefined
- Not returning after sending a response, causing 'headers already sent' errors
- Putting all routes in one file as the app grows
Practice task
Build a notes API with GET, POST, PUT and DELETE routes and test every route in Postman.
Frequently asked questions
What is a REST API?
A way for apps to talk over HTTP using URLs and methods like GET, POST, PUT and DELETE, usually sending JSON.