A REST API (Representational State Transfer API) is a way for two systems to communicate with each other over the internet. It works on the principle of making requests and receiving responses between a client (like a web browser or mobile app) and a server (where the data is stored). Most modern REST APIs transmit data in JSON format, although they can also utilize XML, images, or even HTML.
REST APIs rely on HTTP methods (such as GET, POST, PUT, PATCH, DELETE) to perform actions on resources. These actions align with CRUD operations (Create, Read, Update, Delete), which define how data is managed over the web.
π Important Note: REST is an architectural style for designing APIs, while HTTP is the communication protocol used to transfer data. REST defines how the API should behave, and HTTP defines how communication happens. They are not the same thing, but they usually work together.
π Key Features of REST APIs
Stateless: Each request must contain all the information needed. The server does not store client session details.
Client-Server Model: The client and server operate independently, making the system scalable.
Cacheable: Responses can be cached (stored temporarily) to improve speed and performance.
Uniform Interface: REST APIs adhere to consistent rules, including standard URLs, HTTP methods, and status codes.
Layered System: APIs can be built in multiple layers, which improves security and scalability.
βοΈ Common HTTP Methods in REST API
1. GET Method
Used to read or fetch a resource.
Returns data (JSON/XML) with a status code 200 OK
if successful.
If not found, it may return 404 NOT FOUND
.
Example:
GET /customers/45
This request fetches details of the customer with ID 45.
2. POST Method
Example:
POST /customers
{
"name": "Ravi Kumar",
"email": "[email protected]"
}
This request creates a new customer.
β οΈ Note: POST is not idempotent, meaning multiple calls can create multiple records.
3. PUT Method
Example:
PUT /customers/45
{
"name": "Aarav Patel",
"email": "[email protected]"
}
This replaces customer 45βs details.
4. PATCH Method
Example:
PATCH /customers/45
{
"email": "[email protected]"
}
This updates only the email of customer 45.
PUT vs PATCH
Feature | PUT | PATCH |
---|
Update Type | Replaces full resource | Updates specific fields |
Data Required | Entire data | Only changes |
Idempotent | Yes | Not always |
5. DELETE Method
Example:
DELETE /customers/45
This deletes the customer with ID 45.
β‘ Idempotence: Methods like GET, PUT, and DELETE are idempotent (same result if repeated). POST is not idempotent.
π οΈ Create a Simple REST API using Node.js & Express
Letβs create a simple REST API using Node.js and Express.
Step 1: Create a project folder
mkdir my-rest-api
cd my-rest-api
Step 2: Initialize Node.js project
npm init -y
Step 3: Install Express
npm install express
Step 4: Create a simple server
const express = require('express');
const app = express();
const port = 4000;
app.use(express.json());
// GET route
app.get('/customers', (req, res) => {
res.json({ message: 'Fetching all customers' });
});
// POST route
app.post('/customers', (req, res) => {
const newCustomer = req.body;
res.json({ message: 'Customer created', customer: newCustomer });
});
// PUT route
app.put('/customers/:id', (req, res) => {
const customerId = req.params.id;
res.json({ message: `Customer ${customerId} updated`, data: req.body });
});
// DELETE route
app.delete('/customers/:id', (req, res) => {
const customerId = req.params.id;
res.json({ message: `Customer ${customerId} deleted` });
});
// Start server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
β
You can test this API using Postman or cURL.
π Applications of REST APIs
Social Media: Login, posting, and sharing using third-party platforms.
E-Commerce: Managing products, payments, and customer data.
Maps & Navigation: GPS tracking and real-time locations.
Weather Apps: Fetching real-time weather updates from external sources.
π REST API vs GraphQL
Feature | REST API | GraphQL |
---|
Flexibility | Fixed endpoints | Client chooses fields |
Efficiency | May require multiple calls | Single query fetches all data |
Over-fetching | Returns extra data | Only requested fields |
Under-fetching | Sometimes needs extra calls | Always gets all needed data |
Complexity | Easier to start | More flexible, but complex |
π Summary
A REST API is a lightweight and flexible way for applications to communicate over the internet. It uses HTTP methods to perform CRUD operations and follows key principles like statelessness and scalability. With wide usage in social media, e-commerce, mapping, and weather apps, REST APIs remain the backbone of modern web and mobile applications. π