How I Built My First REST API with Node.js
Building your first REST API can feel intimidating, but once you break it down into small steps, it becomes a lot more manageable. In this post, I'll walk through how I built a simple REST API using Node.js and Express, covering the essentials: routing, middleware, and error handling.
Why Node.js and Express?
Node.js lets you run JavaScript on the server, and Express is a minimal framework that makes handling routes, requests, and responses much simpler than using raw Node.
Setting Up the Project
mkdir my-first-api
cd my-first-api
npm init -y
npm install expressCreating the Server
const express = require("express");
const app = express();
const PORT = 3000;
app.use(express.json());
app.get("/", (req, res) => {
res.send("Welcome to my first API!");
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Adding Routes
app.get("/api/users", (req, res) => {
res.json([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
]);
});
app.post("/api/users", (req, res) => {
const newUser = req.body;
res.status(201).json(newUser);
});Handling Errors
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: "Something went wrong!" });
});Wrapping Up
That's the basic structure of a REST API built with Node.js and Express. From here, you can expand it with a database, authentication, and more advanced middleware.
What's Next
In future posts, I'll cover connecting this API to a database and adding JWT-based authentication.
