In today’s connected world, REST APIs are the backbone of modern applications. From mobile apps to complex web systems, APIs allow different pieces of software to communicate effectively. In this blog, we’ll explore what REST APIs are and how to build them using Node.js and PHP.
🌐 What is a REST API?
REST stands for Representational State Transfer. It’s a set of architectural principles for designing web services. A REST API allows clients (like browsers or mobile apps) to interact with a server via HTTP methods:
GET: Retrieve dataPOST: Send new dataPUT: Update existing dataDELETE: Remove data
Example Use Case:
Imagine a task manager app where users can add, view, update, and delete tasks. Each of these actions corresponds to one of the HTTP methods.
⚙️ Building REST API with Node.js (Express)
Setup
npm init -y
npm install express
Basic Server
const express = require('express');
const app = express();
app.use(express.json());
let tasks = [];
app.get('/tasks', (req, res) => res.json(tasks));
app.post('/tasks', (req, res) => {
tasks.push(req.body);
res.status(201).send('Task added');
});
app.listen(3000, () => console.log('Server running on port 3000'));
⚙️ Building REST API with PHP (Vanilla PHP)
Basic GET and POST Handler
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
echo json_encode(['message' => 'List of tasks']);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents("php://input"), true);
echo json_encode(['message' => 'Task added', 'data' => $data]);
}
✅ Summary
- REST APIs use standard HTTP methods.
- You can build them using both Node.js and PHP.
- Node.js is ideal for fast, scalable APIs.
- PHP is simple and works well in shared hosting environments.
Next, we'll connect these APIs to a database!
