انتقل إلى المحتوى
أمين أبوزيد
منشورBEG-052-L03

رموز الحالة (Status codes)

  • الدرس 3 من 7
  • 10 دقيقة قراءة
  • مبتدئ
في هذا الدرس 11 موضوعات

هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.

Lesson Overview

The kitchen's note on the dish has a short verdict at the top: "here it is", "we do not have that", "you did not say how you want the steak", "the stove broke". HTTP puts the verdict in a three-digit number, the status code, in the first line of every response.

The first digit sorts the verdict into a class: 2 for success, 3 for redirect, 4 for a problem with the request, 5 for a problem on the server. Knowing the class tells you at once whose job it is to fix things: the caller's (4xx) or the server's (5xx).

This lesson teaches the five classes and the dozen codes you will meet daily, and the habit of choosing the most accurate code instead of using 500 for everything. It builds on lesson 1 (the status line) and lesson 2 (which method produces which result).

Learning Objectives

By the end of this lesson you will be able to:

  • Name the five status code classes and what each means.
  • Interpret 200, 201, 204, 301, 302, 304, 400, 401, 403, 404, 500, and 503.
  • Tell 401 from 403.
  • Decide, for a given situation, whether the fault is the client's (4xx) or the server's (5xx).
  • Explain why returning 500 for every error is a mistake.
  • Group codes by class in Java using integer division.

Written Explanation

The five classes

ClassRangeMeaning
1xx100 to 199Informational: an interim response, the request is still in progress
2xx200 to 299Success: the request was received, understood, and accepted
3xx300 to 399Redirection: more action is needed, usually going to another URL
4xx400 to 499Client error: the request has a problem the client must fix
5xx500 to 599Server error: the server failed to fulfil a valid request

You will rarely deal with 1xx at this stage. The other four matter every day. The class is the first digit, so code / 100 in Java gives it.

Codes worth knowing

2xx, it worked

CodeNameTypical use
200OKGeneral success; for a GET, the body holds the resource
201CreatedA new resource was created, typically after POST
204No ContentSuccess with no body, for instance after DELETE

3xx, look elsewhere

CodeNameMeaning
301Moved PermanentlyThe URL has changed for good; the new one is in the response
302FoundA temporary move; keep using the original URL later
304Not ModifiedYour cached copy is still valid; reuse it

4xx, the caller got something wrong

CodeNameMeaning
400Bad RequestThe request looks malformed or invalid (broken syntax, bad data)
401UnauthorizedYou must authenticate to get this
403ForbiddenThe server understood you but refuses to allow it
404Not FoundThe server cannot find the resource

5xx, the server failed

CodeNameMeaning
500Internal Server ErrorA generic failure; the server has no more specific code for it
503Service UnavailableThe server is not ready, for example overloaded or in maintenance; temporary

401 versus 403

The names mislead. MDN explains that 401 really means not authenticated: the server does not know who you are, so you must provide valid credentials. 403 means the server knows who you are but your identity lacks permission, so logging in again will not help. In the restaurant: 401 is "I need to see your membership card", 403 is "your card is fine, but this room is for staff only". MDN also notes that a server may answer 404 instead of 403 to hide that a resource exists at all.

Whose fault?

The class answers this. A 4xx says "fix the request and try again": wrong data, missing login, unknown address. Repeating the same request will fail the same way. A 5xx says "the request was fine, we failed": a bug, a crashed database, an overloaded server. Trying again later might work.

This matters in practice. Monitoring raises an alarm on 5xx because it signals something broken on your side. If a user mistyping a URL produced a 500, your alarms would fill with false alarms, and real server errors would drown in the noise.

Choose the most accurate code

SituationBetter codePoor choice
Book 99 does not exist404500
Request body is not valid400500
No login was provided401200 with an error message in the body
Logged in but not allowed403404 or 500, unless you deliberately hide the resource
The database is down500 or 503200

Do not use 200 for failures, either: many clients check only the status code.

Examples

Example 1: Reading a status line (simple)

text
HTTP/1.1 404 Not Found

The first digit is 4, so the class is client error. The code 404 says the resource was not found. The fault is on the caller's side (a wrong URL or an id that does not exist); the server worked.

Example 2: Choosing codes for a book API (practical)

RequestResultCode
GET /books/7Book exists200
GET /books/999No such book404
POST /books with valid dataCreated201
POST /books with {"title":}Broken data400
DELETE /books/7Deleted, nothing to return204
DELETE /books/7 without a loginNot authenticated401
DELETE /books/7 as a normal memberAuthenticated, not allowed403
GET /books while the database is downServer failed500 (or 503)

Each answer tells the client exactly what to do next: show the data, fix the URL, correct the input, log in, ask for more rights, or try later.

Example 3: Sorting codes by class in Java (realistic)

A client program often branches on the class instead of listing every code.

java
public class L03 {
    static String classOf(int code) {
        int first = code / 100;
        if (first == 2) return "success";
        if (first == 3) return "redirect";
        if (first == 4) return "client error";
        if (first == 5) return "server error";
        return "other";
    }
    public static void main(String[] args) {
        int[] codes = {200, 201, 204, 301, 400, 401, 403, 404, 500, 503};
        for (int c : codes) {
            System.out.println(c + " -> " + classOf(c));
        }
    }
}

Output (compiled and run with JDK 21):

text
200 -> success
201 -> success
204 -> success
301 -> redirect
400 -> client error
401 -> client error
403 -> client error
404 -> client error
500 -> server error
503 -> server error

Integer division drops the remainder, so 404 / 100 is 4. A real client would retry on 503, show a login screen on 401, and show an error message on 400, all decisions based on the class.

Backend Insight

Your backend decides the status code for every response. Frameworks you will meet later set a default, but you choose the meaning: a missing book should lead to 404, not to an unhandled exception that becomes 500.

Treat each unexpected exception as a 500 only when it really is your bug. Anything the caller can fix (bad data, missing record, no permission) gets a 4xx. That honesty makes the system debuggable: when a client reports "I get 400", you know to check the request; when monitoring shows 500s, you know to check the server and its logs.

Also pair the code with a useful body. A 400 with an empty body forces the caller to guess what was wrong; a short message such as which field was invalid saves hours.

Common Mistakes

Mistake 1: Treating every error as 500

  • Incorrect: returning 500 when a book is not found.
  • Correct: 404 for a missing resource, 400 for invalid input, 401 or 403 for access problems; 500 only when the server itself failed.

Mistake 2: Returning 200 with an error message

  • Incorrect: 200 OK with the body {"error":"not logged in"}.
  • Correct: 401 with the same message in the body.

Mistake 3: Confusing 401 and 403

  • Incorrect: "401 means you are not allowed."
  • Correct: 401 means the server does not know who you are; 403 means it knows and says no.

Mistake 4: Retrying a 4xx unchanged

  • Incorrect: "I got 400, so I will send the exact same request again."
  • Correct: a 4xx means the request must change first; only some 5xx codes, such as 503, are worth retrying.

Exercises

Level A: Foundation

A1. Name the class of each code: 201, 301, 403, 503, 200.

أظهر الحل A1

A1. 201 success (2xx); 301 redirect (3xx); 403 client error (4xx); 503 server error (5xx); 200 success.

A2. What do 404 and 500 each mean, and whose fault does each point to?

أظهر الحل A2

A2. 404: the server cannot find the resource, the caller's side (wrong address). 500: a generic failure on the server, the server's side.

A3. Which code fits "a new member was created"?

أظهر الحل A3

A3. 201 Created.

Level B: Application

B1. Give the most accurate code: (a) a user asks for /movies/abc where ids must be numbers; (b) a user asks for an existing movie; (c) a user without login tries to rate a movie; (d) a bug throws a NullPointerException while answering.

أظهر الحل B1

B1. (a) 400, the input is malformed (404 could also be argued if you treat it as an unknown resource; the key point is that it is a 4xx). (b) 200. (c) 401. (d) 500.

B2. A teammate wants 500 for "user typed a wrong password". Reply with a better code and a reason.

أظهر الحل B2

B2. The caller made the mistake, so a 4xx is right: typically 401, since the credentials were not accepted. A 500 would raise false alarms in monitoring and tell clients the server is broken.

B3. What is the difference between 301 and 302, and what does a browser do on seeing them?

أظهر الحل B3

B3. 301 says the move is permanent; 302 says it is temporary and the original URL should keep being used. Both tell the browser to go to another URL, which the response supplies (in a header; headers are the next lesson).

Level C: Challenge

C1. Extend the Java method classOf so that it also returns "informational" for 1xx and "invalid" for numbers below 100 or above 599. Show your code and the result for 100, 150, 99, and 600.

أظهر الحل C1

C1.

java
static String classOf(int code) {
    if (code < 100 || code > 599) return "invalid";
    int first = code / 100;
    if (first == 1) return "informational";
    if (first == 2) return "success";
    if (first == 3) return "redirect";
    if (first == 4) return "client error";
    return "server error";
}

Results: 100 informational, 150 informational, 99 invalid, 600 invalid (compiled and run).

C2. An API returns 200 for everything and puts "status":"error" in the body on failures. List two problems this causes for clients and monitoring.

أظهر الحل C2

C2. Clients that check only the status code treat failures as success; generic tools such as caches and gateways also see all responses as successes. Monitoring that counts 5xx or 4xx sees no errors, so real problems are invisible.

Mini Challenge

Write five realistic requests for a library API (for example GET /books/4, POST /loans, DELETE /members/2). For each, give one success outcome and one failure outcome, with the status code and a one-line reason. Use at least one 201, one 204, one 400, one 401 or 403, and one 404.

Check your work: every failure has a 4xx unless the server itself broke; no code is 200 for a failure; 401 and 403 are not mixed up.

Summary & Next Lesson

Key takeaways

  • The first digit gives the class: 2 success, 3 redirect, 4 client error, 5 server error.
  • 401 means "who are you?" and 403 means "I know you, and no".
  • 4xx says the request must change; 5xx says the server failed.
  • Choose the most accurate code: 404 for missing, 400 for bad input, 201 for created, 204 for no content. Never 200 for an error.

Next lesson

The next lesson, "Headers", looks at the name-value lines between the first line and the body, such as Content-Type, Accept, and Authorization.

Self-check

  1. What class is 404, and whose fault is it?
  2. What class is 500?
  3. What does 201 mean?
  4. What is the difference between 401 and 403?
  5. Why is "200 OK with an error message" a bad practice?
أظهر الإجابات
  1. 4xx client error; the request (the address) was wrong.
  2. 5xx server error.
  3. A new resource was created.
  4. 401: not authenticated; 403: authenticated but not allowed.
  5. Clients and tools check the status code first, so the failure looks like success.

References

  • MDN: HTTP response status codes. Supports the five classes, the meanings of 200, 201, 204, 301, 302, 304, 400, 401, 403, 404, 500, and 503, the 401 versus 403 distinction, and that a server may use 404 to hide a resource.
  • MDN: HTTP messages. Supports the status line and that 201 and 204 responses may have no body.

Not verified from a source: the advice about monitoring alarms and retry behaviour is common practice stated as guidance, not a quotation.

التطبيق

طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.

المختبر والتمارين الاختبار

تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.

اكتب للبحث في المستويات والمراحل والوحدات والدروس.