Node.js API Tutorial
Rafey Shaikh
May 24, 2025
3 min read
#nodejs#backend#express
Creating APIs using Node.js is one of the most common tasks for backend developers. In this tutorial, you'll learn how to build a basic RESTful API using Node.js, Express.js, and MongoDB. This guide is beginner-friendly and ideal for those starting their journey into backend development.
📚 What You'll Learn
- Setting up a Node.js project
- Creating a basic Express server
- Connecting MongoDB with Mongoose
- Creating RESTful routes (GET, POST, PUT, DELETE)
- Testing your API with Postman
🔧 Prerequisites
Make sure you have the following installed:
- Node.js
- MongoDB (or use MongoDB Atlas)
- Postman (for testing API)
1️⃣ Initialize Your Project
bash1mkdir node-api-tutorial 2cd node-api-tutorial 3npm init -y 4`` 5 6Then install dependencies: 7 8```bash 9npm install express mongoose dotenv
2️⃣ Create Folder Structure
bash1node-api-tutorial/ 2├── controllers/ 3├── models/ 4├── routes/ 5├── .env 6├── server.js
3️⃣ Setup Basic Server (server.js
)
js1const express = require('express'); 2const mongoose = require('mongoose'); 3require('dotenv').config(); 4 5const app = express(); 6app.use(express.json()); 7 8const PORT = process.env.PORT || 5000; 9 10// DB Connection 11mongoose.connect(process.env.MONGO_URI, { 12 useNewUrlParser: true, 13 useUnifiedTopology: true 14}).then(() => console.log("MongoDB Connected")) 15 .catch(err => console.error(err)); 16 17// Routes 18const postRoutes = require('./routes/postRoutes'); 19app.use('/api/posts', postRoutes); 20 21// Start Server 22app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
4️⃣ Create Post Model (models/Post.js
)
js1const mongoose = require('mongoose'); 2 3const postSchema = new mongoose.Schema({ 4 title: { type: String, required: true }, 5 content: String 6}, { timestamps: true }); 7 8module.exports = mongoose.model('Post', postSchema);
5️⃣ Create Controller Functions (controllers/postController.js
)
js1const Post = require('../models/Post'); 2 3exports.getAllPosts = async (req, res) => { 4 const posts = await Post.find(); 5 res.json(posts); 6}; 7 8exports.createPost = async (req, res) => { 9 const post = new Post(req.body); 10 await post.save(); 11 res.status(201).json(post); 12}; 13 14exports.getPost = async (req, res) => { 15 const post = await Post.findById(req.params.id); 16 res.json(post); 17}; 18 19exports.updatePost = async (req, res) => { 20 const updatedPost = await Post.findByIdAndUpdate(req.params.id, req.body, { new: true }); 21 res.json(updatedPost); 22}; 23 24exports.deletePost = async (req, res) => { 25 await Post.findByIdAndDelete(req.params.id); 26 res.json({ message: 'Post deleted' }); 27};
6️⃣ Setup Routes (routes/postRoutes.js
)
js1const express = require('express'); 2const router = express.Router(); 3const postController = require('../controllers/postController'); 4 5router.get('/', postController.getAllPosts); 6router.post('/', postController.createPost); 7router.get('/:id', postController.getPost); 8router.put('/:id', postController.updatePost); 9router.delete('/:id', postController.deletePost); 10 11module.exports = router;
7️⃣ Setup Environment File (.env
)
env1PORT=5000 2MONGO_URI=mongodb://localhost:27017/node_api
🧪 Test Your API
Open Postman and test the following endpoints:
Method | Endpoint | Description |
---|---|---|
GET | /api/posts | Get all posts |
POST | /api/posts | Create new post |
GET | /api/posts/:id | Get post by ID |
PUT | /api/posts/:id | Update post by ID |
DELETE | /api/posts/:id | Delete post by ID |
✅ Bonus Tips
- Use nodemon for auto-restart during development:
npm install --save-dev nodemon
- Structure code using MVC pattern (Model, View, Controller)
- Add validation using
express-validator
- Secure the API using JWT for authentication
📚 Free Resources to Learn More
Happy Coding! ⚡