Student Senior BlogBlogs

Node.js API Tutorial

Mohd Rafey
May 24, 2025
3 min read
Banner for Node.js API Tutorial

AI Summary

Tap Generate and let AI do the magic

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:


1️⃣ Initialize Your Project

bash
1mkdir 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

bash
1node-api-tutorial/ 2β”œβ”€β”€ controllers/ 3β”œβ”€β”€ models/ 4β”œβ”€β”€ routes/ 5β”œβ”€β”€ .env 6β”œβ”€β”€ server.js

3️⃣ Setup Basic Server (server.js)

js
1const 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)

js
1const 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)

js
1const 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)

js
1const 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)

env
1PORT=5000 2MONGO_URI=mongodb://localhost:27017/node_api

πŸ§ͺ Test Your API

Open Postman and test the following endpoints:

MethodEndpointDescription
GET/api/postsGet all posts
POST/api/postsCreate new post
GET/api/posts/:idGet post by ID
PUT/api/posts/:idUpdate post by ID
DELETE/api/posts/:idDelete 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! ⚑

#nodejs#backend#express
Node.js API Tutorial | Student Senior Blogs