HTTP Status Codes ও Response

লেসন ৪৩ / ৪৪

HTTP Status Codes

Server প্রতিটি response-এ একটি 3-digit status code পাঠায় যা request-এর ফলাফল বোঝায়।

1xx — Informational

  • 100 Continue — client, request এর বাকি অংশ পাঠাতে পারে
  • 101 Switching Protocols — WebSocket upgrade

2xx — Success ✅

  • 200 OK — সফল (GET, PUT এ)
  • 201 Created — নতুন resource তৈরি (POST)
  • 202 Accepted — গৃহীত কিন্তু এখনো প্রক্রিয়াধীন
  • 204 No Content — সফল, কিন্তু body নেই (DELETE)

3xx — Redirection 🔁

  • 301 Moved Permanently — স্থায়ীভাবে স্থানান্তর
  • 302 Found — সাময়িক redirect
  • 304 Not Modified — cache থেকে load করো

4xx — Client Error ❌

  • 400 Bad Request — ভুল ডেটা পাঠিয়েছে
  • 401 Unauthorized — login প্রয়োজন
  • 403 Forbidden — login আছে কিন্তু permission নেই
  • 404 Not Found — resource পাওয়া যায়নি
  • 405 Method Not Allowed — GET এর জায়গায় POST পাঠিয়েছে
  • 409 Conflict — ডুপ্লিকেট (email already exists)
  • 422 Unprocessable Entity — validation fail
  • 429 Too Many Requests — rate limit পার হয়েছে

5xx — Server Error 💥

  • 500 Internal Server Error — সার্ভারে অজানা ভুল
  • 502 Bad Gateway — upstream server সমস্যা
  • 503 Service Unavailable — সার্ভার overloaded/down
  • 504 Gateway Timeout — upstream server timeout

JavaScript-এ Status Code চেক

const res = await fetch(url);

if (res.status === 200) {
    // সফল
} else if (res.status === 401) {
    // Login পেজে পাঠাও
    window.location = "/login";
} else if (res.status === 404) {
    showError("পাওয়া যায়নি");
} else if (res.status >= 500) {
    showError("সার্ভারে সমস্যা");
}

// Shortcut: res.ok = status 200-299 হলে true
if (res.ok) {
    const data = await res.json();
} else {
    throw new Error(`HTTP ${res.status}`);
}

Standard API Response Format

// ✅ Success
{
    "success": true,
    "data": {
        "id": 42,
        "name": "করিম"
    },
    "message": "User fetched successfully"
}

// ❌ Error
{
    "success": false,
    "error": {
        "code": "VALIDATION_FAILED",
        "message": "ইমেইল সঠিক নয়",
        "fields": {
            "email": "Invalid email format"
        }
    }
}

Request/Response Headers (গুরুত্বপূর্ণ)

// Common Request Headers
Content-Type: application/json
Accept: application/json
Authorization: Bearer TOKEN
User-Agent: Mozilla/5.0...
Cookie: session=abc123

// Common Response Headers
Content-Type: application/json; charset=utf-8
Content-Length: 1234
Cache-Control: max-age=3600
Set-Cookie: session=...
Access-Control-Allow-Origin: *

Browser DevTools → Network Tab

যেকোনো API call debug করতে F12 → Network ট্যাব খুলুন। দেখুন:

  • Request URL, method
  • Request headers ও body
  • Response status, headers, body
  • Timing (কতক্ষণ লেগেছে)