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

推荐订阅源

The Last Watchdog
The Last Watchdog
博客园_首页
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
美团技术团队
小众软件
小众软件
V
V2EX
博客园 - Franky
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
Attack and Defense Labs
Attack and Defense Labs
S
Security Affairs
Simon Willison's Weblog
Simon Willison's Weblog
I
Intezer
T
The Exploit Database - CXSecurity.com
有赞技术团队
有赞技术团队
S
Schneier on Security
人人都是产品经理
人人都是产品经理
Security Archives - TechRepublic
Security Archives - TechRepublic
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
K
Kaspersky official blog
PCI Perspectives
PCI Perspectives
AI
AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
罗磊的独立博客
O
OpenAI News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Register - Security
The Register - Security
V
Vulnerabilities – Threatpost
GbyAI
GbyAI
博客园 - 【当耐特】
C
Cisco Blogs
大猫的无限游戏
大猫的无限游戏
Help Net Security
Help Net Security
Google DeepMind News
Google DeepMind News
S
Securelist
Application and Cybersecurity Blog
Application and Cybersecurity Blog
P
Proofpoint News Feed
博客园 - 三生石上(FineUI控件)
雷峰网
雷峰网
L
LangChain Blog
SecWiki News
SecWiki News
博客园 - 叶小钗
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V2EX - 技术
V2EX - 技术
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
L
LINUX DO - 热门话题
Cisco Talos Blog
Cisco Talos Blog

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
REST API Design Made Simple with Express.js: A Beginner-Friendly Guide
Bhupesh Chan · 2026-05-09 · via DEV Community

Master REST API design with Express.js. Learn HTTP methods, clean routing, status codes, and real-world best practices through practical examples. Perfect for Node.js beginners and frontend developers moving to backend.

. Hero Section Intro

Imagine walking into your favorite restaurant. You don’t go into the kitchen and cook the food yourself. You tell the waiter what you want, and they bring it back.

That waiter? That’s your API.

In this guide, we’ll turn you from someone who’s “heard of REST” into someone who can confidently build clean, professional REST APIs with Express.js — using the “users” resource as our main example.

No fluff. Just practical, modern Node.js that you can use in real projects today. Let’s dive in! 🚀


# REST API Design Made Simple with Express.js

Hey there! If you're a beginner Node.js developer, a React dev exploring the backend, or preparing for interviews, this guide is for you.

We'll explore **REST APIs** using Express.js with real-world analogies, clean code, and modern patterns.

## What is an API?

**API** stands for **Application Programming Interface**.

Think of it as a **contract** that allows two pieces of software to talk to each other.

- **Client** (your React app, mobile app, or Postman) sends a request.
- **Server** processes it and sends back a response.

**Real-world analogy**: When you order food via a delivery app, you dont cook it yourself. You make a request  the restaurant (server) prepares it  delivers the response (your food).

## What Does REST Mean?

**REST** = **RE**presentational **S**tate **T**ransfer.

Its an architectural style introduced by Roy Fielding in 2000. RESTful APIs use standard HTTP methods to perform operations on **resources**.

### Key Characteristics of REST:
- **Stateless**: Each request contains all the information needed. The server doesnt remember previous requests.
- **Uses HTTP methods** as verbs.
- **Resources** are nouns (URLs).
- **Cacheable**, layered, and uniform interface.

**Why did REST win?** Its simple, scalable, and works beautifully with the web.

## Resources in REST Architecture

In REST, everything is a **resource**  usually a noun.

Example: **Users**, Posts, Products, Orders.

We use **plural nouns** for collection routes:
- `/users`  collection of all users
- `/users/42`  single user (resource)

**Pro Tip**: Stick to plural naming. It feels natural and is the industry standard.

## HTTP Methods Explained

Lets map real-life actions to HTTP methods using our **users** resource.

### GET  Fetch data
**Purpose**: Retrieve resources (safe, idempotent).

**Analogy**: Asking the waiter Whats on the menu? or Show me my order.

Enter fullscreen mode Exit fullscreen mode


js
// GET /users - Get all users
app.get('/users', async (req, res) => {
const users = await User.find();
res.json(users);
});

// GET /users/:id - Get one user
app.get('/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: "User not found" });
res.json(user);
});


### POST — Create new resource
**Purpose**: Create something new.

**Analogy**: Placing a new order.

Enter fullscreen mode Exit fullscreen mode


js
app.post('/users', async (req, res) => {
const newUser = await User.create(req.body);
res.status(201).json(newUser);
});


### PUT — Update/replace resource
**Purpose**: Update an existing resource (idempotent).

**Analogy**: Replacing your entire order.

Enter fullscreen mode Exit fullscreen mode


js
app.put('/users/:id', async (req, res) => {
const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(updatedUser);
});


### DELETE — Remove resource
**Purpose**: Delete a resource.

Enter fullscreen mode Exit fullscreen mode


js
app.delete('/users/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.status(204).send(); // No content
});


## CRUD vs HTTP Methods Mapping

| CRUD Operation | HTTP Method | Example Route       | Status Code |
|----------------|-------------|---------------------|-------------|
| Create         | POST        | POST /users         | 201         |
| Read (all)     | GET         | GET /users          | 200         |
| Read (one)     | GET         | GET /users/:id      | 200         |
| Update         | PUT         | PUT /users/:id      | 200         |
| Delete         | DELETE      | DELETE /users/:id   | 204         |

## Express.js Setup (Modern Way)

Enter fullscreen mode Exit fullscreen mode


bash
mkdir rest-api-tutorial
cd rest-api-tutorial
npm init -y
npm install express dotenv cors helmet morgan
npm install -D nodemon


**package.json** scripts:

Enter fullscreen mode Exit fullscreen mode


json
"scripts": {
"dev": "nodemon src/server.js"
}


**src/server.js**

Enter fullscreen mode Exit fullscreen mode


js
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import dotenv from 'dotenv';

dotenv.config();

const app = express();

// Middleware
app.use(helmet()); // Security
app.use(cors()); // Enable CORS
app.use(morgan('dev')); // Logging
app.use(express.json()); // Parse JSON bodies

app.get('/', (req, res) => {
res.json({ message: "Welcome to the Users API! 👋" });
});

// Routes will go here

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(🚀 Server running on port ${PORT});
});


## Building User Routes

Create a clean structure:

Enter fullscreen mode Exit fullscreen mode


plaintext
src/
routes/
users.js
controllers/
userController.js
models/
User.js


## Status Codes Basics (The Language of the Web)

- **200 OK** — Everything went fine.
- **201 Created** — Resource was successfully created.
- **400 Bad Request** — Client sent something wrong.
- **404 Not Found** — Resource doesn’t exist.
- **500 Internal Server Error** — Something broke on the server (hide details in production!).

**Mini Summary**: Status codes tell the client what happened — use them correctly!

## REST Request-Response Lifecycle

1. **Client** sends request (Postman / frontend)
2. **Middleware** processes it (auth, validation, logging)
3. **Route** matches the URL + method
4. **Controller** contains business logic
5. **Model/Database** interaction
6. **Response** sent back with proper status code

## Best Practices for Professional APIs

- Always use plural resource names
- Consistent response formats
- Implement proper error handling
- Add API versioning (`/api/v1/users`)
- Validate input data
- Use meaningful status codes

## Common Mistakes Beginners Make

- Using verbs in URLs (`/createUser`, `/getAllUsers`)
- Returning different response shapes inconsistently
- Using `res.send()` for everything instead of `res.json()`
- Forgetting to handle errors properly
- Hardcoding sensitive values

## Packages That Make APIs More Professional

Here’s your pro toolkit:

- **express** — The foundation
- **nodemon** — Auto-restarts server during development
- **dotenv** — Manage environment variables
- **cors** — Handle cross-origin requests
- **helmet** — Add security headers
- **morgan** — Request logging
- **express-async-handler** — Clean async route handling (no try/catch everywhere)
- **zod** — Modern, TypeScript-friendly validation
- **jsonwebtoken + bcrypt** — Authentication & password hashing

**Pro Tip**: Start simple, then layer these packages as your API grows.

## Real-World Companies Using Node.js + REST

Companies like **Netflix**, **LinkedIn**, **PayPal**, **Uber**, and many startups use Node.js and REST (or REST-like) APIs for their backend services.

## Conclusion

You now understand REST API design fundamentals and how to implement them cleanly with Express.js!

**Next Steps Learning Roadmap:**
1. Add authentication (JWT)
2. Connect to MongoDB/PostgreSQL
3. Implement proper validation with Zod
4. Write tests (Jest + Supertest)
5. Deploy to Render / Railway / Vercel

You’ve got this! Start building your own API today.

---

## Suggested Tags for Hashnode
`nodejs`, `expressjs`, `restapi`, `backend`, `webdevelopment`, `javascript`, `tutorial`, `beginners`

## Suggested Cover Image Idea
A modern, clean illustration showing a restaurant waiter (API) serving data dishes to a customer (client) with HTTP method labels floating around. Use calming tech colors (blues, purples, greens).

## Suggested LinkedIn Post for Promotion

"Just published: REST API Design Made Simple with Express.js 🔥

If you’re a frontend dev trying to understand backend or a Node.js beginner, this one’s for you.

We cover resources, HTTP methods, clean routing, status codes, and modern Express patterns — all with real analogies and production-ready code.

Check it out and let me know which part was most helpful! 👇


Enter fullscreen mode Exit fullscreen mode