惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MyScale Blog
MyScale Blog
博客园 - 司徒正美
A
About on SuperTechFans
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
I
InfoQ
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
Google DeepMind News
Google DeepMind News
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
F
Fortinet All Blogs
S
SegmentFault 最新的问题
阮一峰的网络日志
阮一峰的网络日志
D
Docker
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
G
Google Developers Blog
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
Jina AI
Jina AI
H
Help Net Security
量子位
IT之家
IT之家

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Build a REST API with Node.js and Express from Scr...
Abdullah She · 2026-05-19 · via DEV Community

How to Build a REST API with Node.js and Express from Scratch

Create a production‑ready RESTful API step‑by‑step using Node.js, Express, and modern best practices

Before We Start: What You'll Walk Away With

By the end of this guide you’ll be running a complete CRUD REST API on your laptop, just like having a personal kitchen where you can order, update, delete, or view any dish you’ve prepared.

We’ll walk you through the whole project layout, so you’ll know exactly why each folder exists—think of it as packing a suitcase where every item has its own compartment, making the trip smoother.

You’ll also get comfortable with middleware, routing, error handling, and a dash of security, similar to using Google Maps: the router tells requests where to go, middleware adds the traffic rules, and error handling warns you when you hit a dead end.

  • Spin up a Node.js server with Express and see it respond to HTTP verbs.

  • Organize code into controllers, routes, and models so future changes feel like swapping out a single ingredient.

  • Add basic protections—like checking a password before entering a club—to keep unwanted traffic out.

  • Node.js: the engine that runs your JavaScript on the server.

  • Express: the lightweight framework that routes requests, like a maître d' directing guests to tables.

  • CRUD: Create, Read, Update, Delete – the four actions you’ll master.

When you clone the repo, you’ll see a ready‑made structure you can tweak: change a route, add a field, or point it at a cloud database without rebuilding from scratch.

In short, you’ll finish with a copy‑and‑paste‑ready API you can extend or deploy wherever you need it.

What a REST API Actually Is (No Jargon)

A REST API is simply a collection of URLs that accept HTTP verbs—GET, POST, PUT, DELETE—to let one program ask another for data or tell it to change something. Think of each URL as a door and the verb as the way you knock; the response is whatever the other side hands you back.

Picture a restaurant menu. The menu lists dishes (those are your resources). You, the diner, send a waiter a request: “I’d like the salad GET,” “Add a drink POST,” “Swap the fries for a side of veggies PUT,” or “Take the soup away DELETE.” The kitchen prepares the order and the waiter brings it back—that’s the API’s response.

Because the conversation follows a standard set of rules, any client that understands HTTP can “eat” at your API, whether it’s a web app, a mobile app, or a script you run from the command line. No need to share codebases or speak the same programming language; just follow the contract defined by the endpoints.

When you build REST API Node.js apps, you’re essentially drafting that menu, setting up the kitchen stations (routes), and training the waitstaff (middleware) so every request gets the right dish, quickly and predictably.

The 4 Mistakes Everyone Makes With REST APIs

Most of the pain you feel when a request blows up comes from a simple habit you’ve picked up early on.

Mixing business logic with routing code makes your server feel like a crowded kitchen where the chef also takes orders, washes dishes, and invoices the table. When the logic lives inside the route handler, any change forces you to rewrite the whole menu.

Ignoring proper error handling is like driving a car without a spare tire; a single flat punctures the whole journey. If a typo or missing DB field throws, the entire Node.js process exits and every client gets a 500.

Forgetting to validate input turns your API into an open‑door grocery store where anyone can walk in and dump anything on the shelves. Bad payloads slip into your database, open XSS doors, and corrupt analytics.

Not versioning the API is like packing a suitcase once and never checking the weight before a flight. The first time a client needs a new field, the whole bag shifts and the old travelers are forced to repack.

Spotting these four traps early saves you weeks of debugging when you build REST API Node.js projects.

Next, we’ll walk through the clean project layout that keeps each concern in its own drawer.

How to Build a REST API with Node.js and Express: Step‑by‑Step

Run npm init -y to create a package.json, then install the core tools:

  • express – the kitchen where your API is cooked

  • dotenv – the pantry that keeps secret ingredients safe

  • nodemon – the sous‑chef that restarts the server on every change

Lay out the project like a well‑organized toolbox:

  • /src

  • /src/routes

  • /src/controllers

  • /src/models

  • /src/middleware

In src/app.js, load environment variables, spin up an Express instance, and add app.use(express.json()) so the server can read JSON payloads.

Drop a quick health‑check route:

GET /api/health → returns { status: "OK" }

It’s like asking a waiter, “Is the kitchen open?”

Create src/routes/users.js and define the classic CRUD endpoints for a User resource.

Meet Alice. She can be created with POST /api/users, read with GET /api/users/:id, updated via PUT /api/users/:id, and removed with DELETE /api/users/:id.

Write matching functions in src/controllers/userController.js. Each controller receives req and res, performs the logic, then sends a JSON response.

Add a global error‑handling middleware at the bottom of app.js. It catches rejected promises and replies with a consistent error object.

Secure the API with a trio of middleware:

  • helmet – adds HTTP headers like a lock on the front door

  • cors – decides which origins can knock

  • express-rate-limit – prevents a rush of requests, similar to a line‑up manager

  • Validate input with joi before it reaches your controllers

Create a .env file containing PORT=3000 and any secret keys. dotenv.config() pulls these values into process.env.

Fire up the server with npm run start (script: nodemon src/app.js) and test each endpoint using Postman or curl. If everything responds, you’ve successfully built a REST API with Node.js.

A Real Example: Building a Todo List API for “Sam the Startup Founder”

Sam needs a tiny Todo API so he can demo his MVP to investors by Friday.

He follows the checklist from Section 4, turning a blank folder into a working service.

  • Project init: npm init -y, install express, dotenv, joi, express-rate-limit.

  • Folder layout: create src/ with routes/, controllers/, models/, and a root server.js.

  • Routes for /todos: one file todoRoutes.js that maps HTTP verbs to controller actions.

  • Controller logic: todoController.js handles create, read, update, delete, each returning JSON.

  • Validation schema: a Joi schema ensures every Todo has a title (string, required) and optional completed flag.

  • Rate limiting: a 100‑request‑per‑minute rule protects the public beta, just like a restaurant limits tables during rush hour.

Here’s what Sam’s files look like.

// src/routes/todoRoutes.js
const express = require('express');
const router = express.Router();
const { getTodos, createTodo, updateTodo, deleteTodo } = require('../controllers/todoController');

router.get('/', getTodos);
router.post('/', createTodo);
router.put('/:id', updateTodo);
router.delete('/:id', deleteTodo);

module.exports = router;

// src/controllers/todoController.js
const Joi = require('joi');
const todos = []; // in‑memory store

const schema = Joi.object({
title: Joi.string().required(),
completed: Joi.boolean().default(false)
});

exports.getTodos = (req, res) => res.json(todos);

exports.createTodo = (req, res) => {
const { error, value } = schema.validate(req.body);
if (error) return res.status(400).json({ error: error.details[0].message });
const newTodo = { id: Date.now(), ...value };
todos.push(newTodo);
res.status(201).json(newTodo);
};

exports.updateTodo = (req, res) => {
const todo = todos.find(t => t.id == req.params.id);
if (!todo) return res.status(404).end();
const { error, value } = schema.validate(req.body);
if (error) return res.status(400).json({ error: error.details[0].message });
Object.assign(todo, value);
res.json(todo);
};

exports.deleteTodo = (req, res) => {
const index = todos.findIndex(t => t.id == req.params.id);
if (index === -1) return res.status(404).end();
todos.splice(index, 1);
res.status(204).end();
};

.env

PORT=3000
RATE_LIMIT_WINDOW=60 # seconds
RATE_LIMIT_MAX=100

  • Tip: Keep .env out of version control; it’s the key to build REST API Node.js projects that move between dev and prod.

Sam now has a functional Todo list API he can point his front‑end at and start showing off.

The Tools That Make This Easier

Think of your development setup like a well‑organized kitchen – you need the right tools at hand so you don’t waste time chopping onions when you could be cooking the main dish.

  • Visual Studio Code with the ESLint and Prettier extensions – the chef’s knife and cutting board. VS Code’s built‑in terminal lets you stir the pot without opening another window, while ESLint catches syntax mistakes before they spoil the broth and Prettier keeps the code tidy.

  • Postman (free tier) – the taste‑tester. Just as you’d sample a sauce before serving, Postman lets you fire requests at each endpoint, view responses, and tweak headers without leaving the editor.

  • npm and npx – the pantry and instant‑cook packets. npm stores all your dependencies, and npx runs one‑off commands (like creating a new Express project) without cluttering your global install.

  • Swagger UI Express – the restaurant menu that updates itself. Write an OpenAPI spec and Swagger UI Express serves an interactive page where anyone can explore and try your API, just like a digital menu that lets diners see ingredients.

  • GitHub Codespaces – the portable kitchen. Spin up a cloud‑based VS Code instance that already has Node, npm, and the extensions you need, so you can start cooking from any laptop, any network.

These five tools cover code editing, testing, dependency management, documentation, and environment setup, giving you a streamlined workflow to build REST API Node.js projects without the usual setup headaches.

Quick Reference: REST API with Node.js Cheat Sheet

Grab this list whenever you need to spin up a new API—think of it as a quick‑order menu for your backend.

  • Project init: Run npm init -y, then install the core stack with npm i express dotenv cors helmet morgan. It’s like ordering the basic ingredients before cooking.

  • Folder layout: Create /src with subfolders routes, controllers, and middleware. Treat each folder as a separate kitchen station.

Core files:

  • app.js – sets up Express, middleware, and routes.

  • server.js – calls app.listen and reads the port.

  • routes/*.js – defines endpoint paths.

  • controllers/*.js – holds the business logic.

CRUD pattern: Map resources to the classic set—

  • GET /resources – list all.

  • GET /resources/:id – fetch one.

  • POST /resources – create.

  • PUT /resources/:id – replace.

  • DELETE /resources/:id – remove.

Like ordering a meal: you can view the menu, pick a dish, change it, or send it back.

  • Validation: Plug a Joi schema into route middleware. For example, Alex the travel blogger sends a new post; the schema checks title length, content presence, and date format before the controller runs.

  • Error handling: Wrap async handlers, call next(err), and let a global error middleware format the response. It’s the “Google Maps reroute” when something goes off‑track.

  • Security: Add helmet for headers, cors for cross‑origin rules, a rate‑limit middleware, and keep secrets in .env. Think of it as locking the kitchen door and only handing keys to trusted staff.

  • Docs: Generate live API docs with swagger-jsdoc + swagger-ui-express. Users can explore endpoints the way a menu lets diners see every option.

Keep this cheat sheet bookmarked and you’ll build a REST API with Node.js in no time.

What to Do Next

Grab the starter repo, fire it up, and you’ll have a working API in seconds.

  • Clone & run – Click the GitHub link at the top of the article, git clone it locally, then npm install followed by npm run dev. Think of this like ordering a ready‑made pizza: the dough and sauce are already prepared, you just heat it up and start eating.

  • Add JWT auth – Install jsonwebtoken, create a middleware that checks the token, and wrap your Todo routes with it. It’s similar to giving a valet key that only lets you open the right doors.

  • Deploy to the cloud – Sign up for a free tier on Render or Railway, push your code, set the same environment variables you used locally, and flip the switch for automatic HTTPS. Deploying is like packing a suitcase: you’ve already chosen what to bring, now you just zip it up and head out.

  • Quick tip: Keep your .env file out of version control; services provide a secure place to store those values.

  • Tool suggestion: Use nodemon during development so the server restarts whenever you save a file.

  • Cheat sheet: npm run dev → start locally; npm run build → prepare for production; npm start → run the built app.

Now you have a solid base, a layer of security, and a live endpoint you can share.

💬 Got stuck or added a cool feature? Drop a comment below—let’s discuss!



About the Author

Abdullah Sheikh is the Founder & CEO at Exteed, where he leads a team of skilled developers specializing in Web2 and Web3 applications, Custom Smart Contracts, and Blockchain solutions.

With 6+ years of experience, Abdullah has built CRMs, Crypto Wallets, DeFi Exchanges, E-Commerce Stores, HIPAA Compliant EMR Systems, and AI-powered systems that drive business efficiency and innovation.

His expertise spans Blockchain, Crypto & Tokenomics, Artificial Intelligence, and Web Applications — delivering scalable, secure, and high-performance solutions tailored to each client's unique needs.

📧 info@abdullah-sheikh.com · 🔗 LinkedIn · 🌐 abdullah-sheikh.com