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
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!"
}
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' });
});
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:
- Open Postman
- Click New Request
- Select the HTTP method (GET, POST, PUT, DELETE)
- Enter your URL — for example http://localhost:3000/users
- For POST and PUT requests click Body → select raw → choose JSON
- Enter your JSON data and click Send
Example POST request body:
{
"name": "Amit Singh",
"email": "amit@example.com"
}
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));
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);
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' });
});
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:
Use clear and consistent route names. Use nouns not verbs. /users is correct. /getUsers is not.
Always version your API Start with /api/v1/users. This makes future updates easier without breaking existing integrations.
Use correct HTTP status codes. Never return a 200 for an error. Always match the status code to the result.
Validate all incoming data. Never trust user input. Always check that required fields exist before saving to the database.
Keep your code organised. Separate your routes, controllers and models into different files as your project grows.
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.
Top comments (0)