In this video tutorial, we'll build a fully functional REST API from scratch using Node.js and Express. Perfect for beginners who want to understand backend development.
What We'll Build
A complete CRUD API for a task management system with the following endpoints:
GET /api/tasks - List all tasks
POST /api/tasks - Create a new task
GET /api/tasks/:id - Get a specific task
PUT /api/tasks/:id - Update a task
DELETE /api/tasks/:id - Delete a taskProject Setup
mkdir task-api && cd task-api
npm init -y
npm install express mongoose dotenv cors
npm install -D nodemonThe Server Code
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
// Routes
app.get("/api/tasks", async (req, res) => {
const tasks = await Task.find().sort({ createdAt: -1 });
res.json(tasks);
});
app.post("/api/tasks", async (req, res) => {
const task = new Task(req.body);
await task.save();
res.status(201).json(task);
});
app.listen(3000, () => console.log("Server running on port 3000"));Key Takeaways
- Express makes routing incredibly simple
- Mongoose provides elegant MongoDB object modeling
- Always validate input data before saving
- Use proper HTTP status codes in responses
- CORS middleware is essential for frontend integration
No comments yet. Be the first!