DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

🌐 MODULE 4: REST API & Architecture (Interview + Real Project Ready)

This module is extremely important for full-stack and frontend engineers.

Companies don’t just check if you can call APIs.
They check if you understand architecture, scalability, and clean structure.

Let’s go step by step.


βœ… 4.1 REST Principles

REST = Representational State Transfer

It is an architectural style for designing APIs.


πŸ”Ή 1️⃣ Stateless

Every request must contain all information required to process it.

Server does NOT remember previous request.

Example:

GET /users/123
Authorization: Bearer token
Enter fullscreen mode Exit fullscreen mode

If token missing β†’ request fails.

Server does not β€œremember” user automatically.


Why Stateless is Important?

  • Easier to scale
  • Load balancers work better
  • No session memory dependency

πŸ”Ή 2️⃣ Resource-Based

In REST, everything is a resource.

Examples:

/users
/users/1
/orders
/products/10
Enter fullscreen mode Exit fullscreen mode

NOT:

/getUser
/createProduct
/deleteOrder
Enter fullscreen mode Exit fullscreen mode

Use nouns, not verbs.


πŸ”Ή 3️⃣ HTTP Methods

Actions are defined by HTTP methods, not URL.

Example:

GET /users
POST /users
PUT /users/1
DELETE /users/1
Enter fullscreen mode Exit fullscreen mode

Clean. Predictable. Standardized.


βœ… 4.2 HTTP Methods (Deep Understanding)


πŸ”Ή GET

Used to retrieve data.

  • No body
  • Should not modify data
  • Cacheable

Example:

GET /products
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή POST

Used to create new resource.

  • Has request body
  • Not idempotent

Example:

POST /users
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή PUT

Used to fully update resource.

Replaces entire resource.

Example:

PUT /users/1
Enter fullscreen mode Exit fullscreen mode

If field missing β†’ overwritten.


πŸ”Ή PATCH

Used to partially update resource.

Example:

PATCH /users/1
{
  "name": "Nadim"
}
Enter fullscreen mode Exit fullscreen mode

Only updates name.


πŸ”Ή DELETE

Deletes resource.

DELETE /users/1
Enter fullscreen mode Exit fullscreen mode

πŸ”₯ Interview Question

Difference between PUT and PATCH?

PUT β†’ Full replacement
PATCH β†’ Partial update


βœ… 4.3 Important Status Codes

These are extremely common in interviews.


πŸ”Ή 200 OK

Request successful.

Used for:

  • GET success
  • Update success

πŸ”Ή 201 Created

Resource successfully created.

Used after POST.


πŸ”Ή 400 Bad Request

Client sent invalid data.

Example:

  • Missing required field
  • Invalid JSON

πŸ”Ή 401 Unauthorized

User not authenticated.

  • Missing token
  • Invalid token

πŸ”Ή 403 Forbidden

User authenticated but not allowed.

Example:
User role = user
Trying to access admin route.


πŸ”Ή 404 Not Found

Resource doesn’t exist.


πŸ”Ή 500 Internal Server Error

Server crashed or unexpected error.

Never expose sensitive details here.


βœ… 4.4 API Integration (Frontend Side)

Now we move to practical frontend architecture.


πŸ”Ή Axios Interceptors

Interceptors allow you to intercept requests or responses globally.


Add Token Automatically

axios.interceptors.request.use(config => {
  const token = localStorage.getItem("token");

  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  return config;
});
Enter fullscreen mode Exit fullscreen mode

Global Response Handling

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      console.log("Unauthorized");
    }
    return Promise.reject(error);
  }
);
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Global Error Handling

Instead of handling errors everywhere:

Create one centralized handler.

Example:

function handleApiError(error) {
  if (error.response) {
    console.log(error.response.data.message);
  } else {
    console.log("Network error");
  }
}
Enter fullscreen mode Exit fullscreen mode

Keeps UI clean.


πŸ”Ή Retry Mechanism

If request fails due to network issue:

Retry automatically.

Basic example:

async function fetchWithRetry(fn, retries = 3) {
  try {
    return await fn();
  } catch (err) {
    if (retries === 0) throw err;
    return fetchWithRetry(fn, retries - 1);
  }
}
Enter fullscreen mode Exit fullscreen mode

Useful for:

  • Temporary network failures
  • Microservice communication

πŸ”Ή Refresh Token Logic (Frontend Flow)

Typical flow:

  1. Access token expires
  2. API returns 401
  3. Interceptor detects 401
  4. Call /refresh endpoint
  5. Get new access token
  6. Retry original request

Example Pattern:

axios.interceptors.response.use(
  res => res,
  async error => {
    if (error.response.status === 401) {
      await refreshToken();
      return axios(error.config);
    }
    return Promise.reject(error);
  }
);
Enter fullscreen mode Exit fullscreen mode

Important:
Avoid infinite loops.


βœ… 4.5 Frontend Architecture

This is where junior and senior developers differ.


πŸ”Ή Feature-Based Folder Structure

Instead of:

components/
pages/
utils/
services/
Enter fullscreen mode Exit fullscreen mode

Use:

features/
  auth/
    components/
    services/
    hooks/
  products/
    components/
    services/
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Scalable
  • Easy to maintain
  • Clear ownership

πŸ”Ή Service Layer Abstraction

Never call API directly inside component.

❌ Bad:

useEffect(() => {
  axios.get("/users");
}, []);
Enter fullscreen mode Exit fullscreen mode

βœ… Good:

// services/userService.js
export const getUsers = () => api.get("/users");
Enter fullscreen mode Exit fullscreen mode

Then use inside component.

Benefits:

  • Reusable
  • Testable
  • Clean separation

πŸ”Ή Clean Code Principles

  1. Meaningful variable names
  2. Small functions
  3. Avoid duplication
  4. Single responsibility
  5. Clear error handling

πŸ”Ή Separation of Concerns

UI should NOT handle:

  • Business logic
  • API details
  • Data transformation

Each layer should have one responsibility:

  • UI Layer β†’ Display
  • Service Layer β†’ API communication
  • Business Logic Layer β†’ Processing
  • Utility Layer β†’ Helpers

🧠 Interview-Level Thinking

They may ask:

❓ How would you structure a scalable frontend app?

Strong answer:

  • Feature-based structure
  • Centralized API layer
  • Axios interceptors
  • Token refresh logic
  • Global error handling
  • Reusable hooks
  • Clean separation of concerns

🎯 Final Understanding

If you master:

  • REST principles
  • Proper HTTP usage
  • Status codes
  • Secure API integration
  • Token refresh flow
  • Clean architecture

You are not just coding.

You are building production-ready systems.

Top comments (0)