Course contentsShow
← Web Development
Lesson 1490 of 2,98227. REST API Design for FrontendFree lesson

4xx Client Error Codes: 400 and 401

Learn when APIs return 400 Bad Request vs 401 Unauthorized and how to handle them.

4xx Client Error Codes: 400 and 401

You'll learn how to distinguish between two common client error codes and handle them appropriately in your frontend applications.

Understanding 400 Bad Request

The 400 Bad Request status code tells you that the server couldn't understand or process your request due to a client-side problem. This usually means:

  • Malformed JSON syntax in the request body
  • Missing required fields
  • Invalid data types (sending a string where a number is expected)
  • Query parameters in the wrong format

Think of it like ordering food but mumbling so badly the server can't understand what you want. The problem is how you asked, not who you are.

// Example: Missing required field triggers 400
fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice' }) // missing required 'email'
})
.then(response => {
  if (response.status === 400) {
    console.log('Bad request - check your data format');
  }
});

Understanding 401 Unauthorized

The 401 Unauthorized status code means the request lacks valid authentication credentials. You're essentially an unknown visitor trying to access protected resources. Common causes:

  • Missing authentication token
  • Expired token
  • Invalid credentials
  • Token in wrong format or header

This is like showing up at a members-only club without your membership card—the issue is proving who you are, not what you're asking for.

// Example: Missing auth token triggers 401
fetch('/api/profile', {
  method: 'GET'
  // Oops! Forgot to include Authorization header
})
.then(response => {
  if (response.status === 401) {
    console.log('Not authenticated - redirect to login');
  }
});

Key Takeaway: Use 400 Bad Request for malformed or invalid request data, and 401 Unauthorized for missing or invalid authentication—one says "I don't understand your request," the other says "I don't know who you are."