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

推荐订阅源

大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
博客园 - 聂微东
I
InfoQ
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
Y
Y Combinator Blog
F
Full Disclosure
量子位
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
S
SegmentFault 最新的问题
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
月光博客
月光博客
人人都是产品经理
人人都是产品经理
阮一峰的网络日志
阮一峰的网络日志
博客园 - 叶小钗
The Register - Security
The Register - Security
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
B
Blog RSS Feed
The Last Watchdog
The Last Watchdog
Cisco Talos Blog
Cisco Talos Blog
T
Threat Research - Cisco Blogs
Stack Overflow Blog
Stack Overflow Blog
J
Java Code Geeks
S
Securelist
宝玉的分享
宝玉的分享
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
S
Secure Thoughts
F
Fortinet All Blogs
T
Tor Project blog
B
Blog
L
LangChain Blog
博客园 - 司徒正美
Spread Privacy
Spread Privacy
The Cloudflare Blog
A
Arctic Wolf
W
WeLiveSecurity
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
T
Troy Hunt's Blog
Help Net Security
Help Net Security
博客园_首页
Hugging Face - Blog
Hugging Face - Blog
Project Zero
Project Zero

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
How to Build Your First REST API in Node.js ?
Divyanshi Sa · 2026-05-27 · via DEV Community

Most beginners think building a backend is complicated. It looks scary from the outside. Servers, routes, databases, requests, responses, it feels like a lot. But here is the truth. Building your first REST API in Node.js is simpler than you think. You just need the right guide and a willingness to write some code.

This article is a complete Node.js REST API tutorial for absolute beginners in 2026. Are you a student building your first portfolio project? A hackathon participant who needs a strong backend? Or a developer who wants to understand how APIs actually work? This guide is for you.

By the end of this article you will have a working REST API running on your machine. You will understand every line of code you wrote. And you will be ready to take it further.

Let us get started.

What is a REST API and Why Should You Care?

Before you build something you need to understand what it actually is.

Imagine you are using a weather app on your phone. You open the app and it shows you today's temperature. Where does that data come from? The app does not store weather data itself. It sends a request to a server and the server sends back the data. The app displays it.

That communication between the app and the server happens through an API. API stands for Application Programming Interface.

REST stands for Representational State Transfer. It is a set of rules that makes this communication simple, clean and consistent. When an API follows these rules we call it a REST API.

Here is why REST APIs matter for you as a developer or project builder:

  • Almost every modern application uses REST APIs
  • They are the backbone of mobile apps, web apps and microservices
  • Understanding REST APIs opens the door to full stack and backend development
  • Hackathon projects with a solid API backend always stand out

Now let us build one.

What You Need Before You Start

This is a beginner friendly guide but you need a few things installed on your machine before we write any code.

Requirements:

Node.js: Download it from nodejs.org. Install the LTS version.

npm: It comes with Node.js automatically. No separate install needed.

Postman: A free tool to test your API. Download it from postman.com.

A code editor: VS Code works best. Download it from code.visualstudio.com.

Basic JavaScript knowledge: You should know variables, functions and how arrays work.

That is all you need. No advanced setup. No paid tools.

Setting Up Your Node.js Project

Open your terminal and follow these steps one by one.

Step 1: Create a new project folder
mkdir my-first-api
cd my-first-api

Step 2: Initialise your Node.js project
npm init -y

This creates a package.json file. It tracks your project details and dependencies.

Step 3: Install Express
Express JS is the most popular framework for building a Node.js Express REST API. It makes routing simple and saves you a lot of time.

npm install express

Step 4: Create your main file
touch index.js

Your project structure now looks like this:

my-first-api/
├── node_modules/
├── package.json
└── index.js

Enter fullscreen mode Exit fullscreen mode

You are ready to write your first API.

Building Your First Route with Express

Open index.js in your code editor and write the following code:

const express = require('express');
const app = express();
const PORT = 3000;

// Middleware to parse JSON
app.use(express.json());

// Your first route
app.get('/', (req, res) => {
  res.json({ message: 'Welcome to my first REST API!' });
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Now run your server:
node index.js

Open your browser and go to http://localhost:3000. You will see:
{
  "message": "Welcome to my first REST API!"
}

Enter fullscreen mode Exit fullscreen mode

Congratulations. You just built your first working route. This is the foundation of every REST API in Node.js. A server that listens for requests and sends back responses.

Understanding HTTP Methods GET POST PUT DELETE

Every REST API uses HTTP methods to define what action you want to perform. This is one of the most important concepts in backend development for beginners.

Here is a simple breakdown:

HTTP Method What It Does Real World Example
GET Fetch or read data Get a list of all users
POST Create new data Add a new user
PUT Update existing data Update a user's email
DELETE Remove data Delete a user account

Let us build a simple CRUD REST API in Node.js Express using these four methods. We will use an in-memory array to store data for now.

// Sample data
let users = [
  { id: 1, name: 'Rahul Sharma', email: 'rahul@example.com' },
  { id: 2, name: 'Priya Verma', email: 'priya@example.com' }
];

// GET — Fetch all users
app.get('/users', (req, res) => {
  res.json(users);
});

// GET — Fetch single user by ID
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).json({ message: 'User not found' });
  res.json(user);
});

// POST — Add a new user
app.post('/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name,
    email: req.body.email
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// PUT — Update a user
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).json({ message: 'User not found' });
  user.name = req.body.name || user.name;
  user.email = req.body.email || user.email;
  res.json(user);
});

// DELETE — Remove a user
app.delete('/users/:id', (req, res) => {
  users = users.filter(u => u.id !== parseInt(req.params.id));
  res.json({ message: 'User deleted successfully' });
});

Enter fullscreen mode Exit fullscreen mode

You now have a complete set of CRUD operations. This is the core of almost every real world API.

Sending a Proper JSON Response

Every modern REST API communicates using JSON — JavaScript Object Notation. It is lightweight, readable and universally supported.

A proper Node.js JSON response always includes two things — a status code and a data payload.

Here are the most common status codes you will use:

Status Code Meaning
200 Success - request worked fine
201 Created - new resource added
400 Bad Request - something wrong with input
404 Not Found - resource does not exist
500 Server Error - something broke on the server

Always send meaningful status codes with your responses. It makes your API easier to use and debug.

How to Test Your API with Postman

Writing code is only half the work. You need to test it properly. This is where Postman comes in.

Postman lets you send HTTP requests to your API without building a frontend. It is the most popular tool to test REST API with Postman and every backend developer uses it daily.

How to test your API:

  1. Open Postman
  2. Click New Request
  3. Select the HTTP method (GET, POST, PUT, DELETE)
  4. Enter your URL — for example http://localhost:3000/users
  5. For POST and PUT requests click Body → select raw → choose JSON
  6. Enter your JSON data and click Send

Example POST request body:

{
  "name": "Amit Singh",
  "email": "amit@example.com"
}

Enter fullscreen mode Exit fullscreen mode

You will see the response appear instantly in Postman. Test every route you build. Do not skip this step.

Connecting Your API to a Database

Right now your data lives in an array. When you restart the server everything resets. For a real project you need a database.

The most popular choice to connect Node.js REST API to MongoDB is MongoDB with Mongoose.

Install the required packages:
npm install mongoose

Connect to MongoDB in your index.js:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myapi')
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.log('Connection error:', err));

Enter fullscreen mode Exit fullscreen mode

Create a User model:

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true }
});

const User = mongoose.model('User', userSchema);

Enter fullscreen mode Exit fullscreen mode

Now replace your array-based routes with database operations using User.find(), User.create(), User.findByIdAndUpdate() and User.findByIdAndDelete().

This small addition transforms your simple project into a production-ready backend.

How to Handle API Errors the Right Way

Most beginners build routes that work when everything goes right. But real applications break. Users send wrong data. Records do not exist. Servers go down.

Learning how to handle API errors in Node.js is what separates a beginner project from a professional one.

Add a global error handler at the bottom of your index.js:

// Handle routes that do not exist
app.use((req, res) => {
  res.status(404).json({ message: 'Route not found' });
});

// Handle all other errors
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Something went wrong on the server' });
});

Enter fullscreen mode Exit fullscreen mode

Always validate incoming data before processing it. Always return clear error messages. Always use correct status codes.

REST API Best Practices Every Beginner Should Follow

Before you ship your API to a hackathon or add it to your portfolio follow these REST API best practices:

  1. Use clear and consistent route names. Use nouns not verbs. /users is correct. /getUsers is not.

  2. Always version your API Start with /api/v1/users. This makes future updates easier without breaking existing integrations.

  3. Use correct HTTP status codes. Never return a 200 for an error. Always match the status code to the result.

  4. Validate all incoming data. Never trust user input. Always check that required fields exist before saving to the database.

  5. Keep your code organised. Separate your routes, controllers and models into different files as your project grows.

  6. Never expose sensitive data. Do not return passwords or internal server details in your API responses.

These practices make your API clean, reliable and ready for real use.

Your API is Ready: What Comes Next

You just completed a full Node.js REST API tutorial for absolute beginners. You built a working server, created CRUD routes, handled errors, tested with Postman and connected to a database.

This is exactly how to build a REST API in Node.js step by step for beginners — and now you have done it yourself.

But this is just the beginning. Here is what you can explore next:

  • Add authentication: Learn JWT tokens to protect your routes.
  • Deploy your API: Use Railway, Render or Vercel to deploy your Node.js REST API for free on the internet.
  • Add input validation: Use the express-validator package to validate data properly.
  • Learn more about MongoDB: Build more complex queries and relationships between collections.

If you are building this for a hackathon, add a frontend with React or plain HTML and connect it to your API. Your project will immediately look more complete and impressive to judges.

The best way to get better at backend development for beginners is to keep building. Take this foundation, extend it, break it, fix it and build something you are proud to showcase.

You already have everything you need to start.