
REST APIs are the backbone of modern web applications. At SwedTech Academy, we teach you to build production-ready APIs from day one.
REST (Representational State Transfer) is an architectural style for building web services. A REST API allows applications to communicate over HTTP using standard methods like GET, POST, PUT, and DELETE.
First, initialize a Node.js project and install Express:
mkdir task-api && cd task-api
npm init -y
npm install express
Here's a complete example of a simple Task API with full CRUD operations:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
let tasks = [
{ id: 1, title: 'Learn Node.js', completed: false },
{ id: 2, title: 'Build REST API', completed: false }
];
// Get all tasks
app.get('/api/tasks', (req, res) => {
res.json(tasks);
});
// Get single task
app.get('/api/tasks/:id', (req, res) => {
const task = tasks.find(t => t.id === parseInt(req.params.id));
if (!task) return res.status(404).json({ error: 'Task not found' });
res.json(task);
});
// Create new task
app.post('/api/tasks', (req, res) => {
const newTask = {
id: tasks.length + 1,
title: req.body.title,
completed: false
};
tasks.push(newTask);
res.status(201).json(newTask);
});
// Update task
app.put('/api/tasks/:id', (req, res) => {
const task = tasks.find(t => t.id === parseInt(req.params.id));
if (!task) return res.status(404).json({ error: 'Task not found' });
task.title = req.body.title || task.title;
task.completed = req.body.completed !== undefined ? req.body.completed : task.completed;
res.json(task);
});
// Delete task
app.delete('/api/tasks/:id', (req, res) => {
const index = tasks.findIndex(t => t.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ error: 'Task not found' });
tasks.splice(index, 1);
res.json({ message: 'Task deleted successfully' });
});
app.listen(PORT, () => {
console.log(`Task API running on http://localhost:${PORT}`);
});
Add proper error handling:
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
Use these tools to test:
Example cURL commands:
# GET all tasks
curl http://localhost:3000/api/tasks
# POST new task
curl -X POST http://localhost:3000/api/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Learn Express.js"}'
# PUT update task
curl -X PUT http://localhost:3000/api/tasks/1 \
-H "Content-Type: application/json" \
-d '{"completed":true}'
# DELETE task
curl -X DELETE http://localhost:3000/api/tasks/1
Now that you've built your first API, consider:
Building APIs is a fundamental skill for full-stack developers. In our Full-Stack Development course, you'll learn:
Ready to become a full-stack developer? Join SwedTech Academy and build production-ready applications!