Web API  

REST API Introduction and how it works?

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

  1. Stateless: Each request must contain all the information needed. The server does not store client session details.

  2. Client-Server Model: The client and server operate independently, making the system scalable.

  3. Cacheable: Responses can be cached (stored temporarily) to improve speed and performance.

  4. Uniform Interface: REST APIs adhere to consistent rules, including standard URLs, HTTP methods, and status codes.

  5. 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

  • Used to create a new resource.

  • On success, the server returns status 201 CREATED.

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

  • Used to update an entire resource or create it if it does not exist.

  • Replaces the resource at the given URL.

Example:

PUT /customers/45
{
  "name": "Aarav Patel",
  "email": "[email protected]"
}

This replaces customer 45’s details.

4. PATCH Method

  • Used to partially update a resource.

  • Only sends the fields that need changes.

Example:

PATCH /customers/45
{
  "email": "[email protected]"
}

This updates only the email of customer 45.

PUT vs PATCH

FeaturePUTPATCH
Update TypeReplaces full resourceUpdates specific fields
Data RequiredEntire dataOnly changes
IdempotentYesNot always

5. DELETE Method

  • Used to remove a resource.

  • Returns status 200 OK or 204 NO CONTENT if successful.

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

FeatureREST APIGraphQL
FlexibilityFixed endpointsClient chooses fields
EfficiencyMay require multiple callsSingle query fetches all data
Over-fetchingReturns extra dataOnly requested fields
Under-fetchingSometimes needs extra callsAlways gets all needed data
ComplexityEasier to startMore 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. πŸš€