Lesson 25 +10 XP

HTTP Status Codes & Standard Response Formatting

Consistent API Responses

Returning appropriate HTTP status codes and uniform JSON response envelopes enhances client API consumption and developer experience.

Common HTTP Status Code Ranges

  • 2xx Success:
  • 200 OK: Standard successful GET/PUT/DELETE.
  • 201 Created: Resource successfully created via POST.
  • 204 No Content: Success, but no response payload returned (e.g. DELETE).
  • 4xx Client Errors:
  • 400 Bad Request: Invalid body validation or syntax error.
  • 401 Unauthorized: Authentication missing or failed.
  • 403 Forbidden: Authenticated user lacks required permissions.
  • 404 Not Found: Requested URL path or database entity does not exist.
  • 409 Conflict: Resource state conflict (e.g. duplicate email registration).
  • 5xx Server Errors:
  • 500 Internal Server Error: Unhandled error on backend server.

Standardized Response Envelope Pattern

// Success Response Helper
function sendSuccess(res, statusCode, data, message = "Success") {
  return res.status(statusCode).json({
    status: "success",
    message,
    data
  });
}

// Error Response Helper
function sendError(res, statusCode, message) {
  return res.status(statusCode).json({
    status: "fail",
    message
  });
}

TL;DR

  • Always return relevant HTTP status codes (200, 201, 400, 401, 404, 500).
  • Adopt a consistent JSON envelope shape ({ status, data, message }).