Introduction: The Backbone of Modern Apps
You've used APIs. Now it's time to build your own. In this guide, we'll build a simple REST API for managing a list of tasks. You'll learn the fundamentals of Node.js and Express, the most popular framework for Node.
What is Node.js and Express?
Node.js is a runtime that allows you to run JavaScript on the server. Express is a lightweight framework that simplifies building web applications and APIs with Node.
Step-by-Step Execution
1. Setup
Create a new folder. Open the terminal and run:
npm init -y
npm install express
2. Create the Server
Create a file named `app.js`.
const express = require('express');
const app = express();
app.use(express.json()); // Middleware to parse JSON
const tasks = [
{ id: 1, title: 'Learn Node.js' },
{ id: 2, title: 'Build an API' }
];
// GET all tasks
app.get('/api/tasks', (req, res) => {
res.json(tasks);
});
// POST a new task
app.post('/api/tasks', (req, res) => {
const newTask = { id: tasks.length + 1, title: req.body.title };
tasks.push(newTask);
res.status(201).json(newTask);
});
app.listen(3000, () => console.log('Server running on port 3000'));
3. Run the Server
node app.js
Open your browser to `http://localhost:3000/api/tasks`. You should see the JSON array.
Common Mistakes Beginners Make
- Forgetting `express.json()`: Without it, `req.body` will be undefined in POST requests.
- Not handling errors: Always add error handling middleware.
- Exposing sensitive data: Never return the entire user object with passwords.
Practical Exercise (Don't Skip This)
Add a `DELETE /api/tasks/:id` route to delete a task. Test it using Postman. If you get stuck, email me at digisoneglobal@gmail.com.
Frequently Asked Questions
Q: What is middleware?
A: Functions that have access to the request and response objects. They can modify them or end the request.
Q: How do I connect a database?
A: Use an ORM like Mongoose (MongoDB) or Sequelize (SQL).
Tools & Resources Mentioned
Conclusion & Next Steps
You've built your first API. This is a huge milestone. Next, we'll integrate Stripe payments.