Skip to main content
RESTful Principles
CHAPTER 07 Beginner

HTTP Status Codes

Updated: May 13, 2026
5 min read

# CHAPTER 7

HTTP Status Codes

1. Introduction

When you ask the waiter for a specific dish, they might say "Here it is," "We are sold out," or "You aren't allowed to order that." In the language of HTTP, servers don't use words to communicate these results; they use Status Codes. In Chapter 7, we will learn the vocabulary of the web. Understanding these three-digit numbers is essential for building APIs that clients can easily understand and troubleshoot.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain the 5 different classes of HTTP status codes (1xx, 2xx, 3xx, 4xx, 5xx).
  • Use standard 2xx codes to indicate success.
  • Differentiate between 401 Unauthorized and 403 Forbidden.
  • Understand the proper use of 404 Not Found in an API context.
  • Implement HTTP status codes in a PHP API response.

3. Beginner-Friendly Explanation

Think of HTTP status codes as the traffic lights of the web.
  • 200s (Green Light): Success! Everything went perfectly.
  • 300s (Yellow Light / Detour): Redirection. The thing you want is somewhere else.
  • 400s (Red Light - Driver's Fault): Client Error. You asked for something that doesn't exist, you typed it wrong, or you don't have permission. It's your fault.
  • 500s (Red Light - Road Closed): Server Error. The server crashed, the database is down, or there is a bug in the code. It's the server's fault.

4. Real-World Examples

  • 404 Not Found: You click a dead link on a website, and a funny page pops up saying "Oops, this page doesn't exist." That's a 404.
  • 401 Unauthorized: You try to access a private dashboard without logging in, and the site kicks you back to the login page.
  • 500 Internal Server Error: A website is completely broken because the developers accidentally introduced a bug that crashes the database connection.

5. Detailed Code Examples

In PHP, setting an HTTP status code is very straightforward using the httpresponsecode() function.
php
12345678910111213141516171819202122
<?php
// A simple API endpoint demonstrating status codes
$userId = $_GET[&#039;id'] ?? null;

if (!$userId) {
    // Client didn't provide an ID - Client error!
    http_response_code(400); 
    echo json_encode(["error" => "User ID is required (Bad Request)"]);
    exit;
}

// Simulate database lookup
if ($userId == 5) {
    // Success!
    http_response_code(200);
    echo json_encode(["id" => 5, "name" => "Sarah"]);
} else {
    // ID provided, but not found in database
    http_response_code(404);
    echo json_encode(["error" => "User not found"]);
}
?>

6. Request/Response Examples

Let's see what a successful resource creation looks like. When a POST request succeeds, you shouldn't just send a 200 OK; you should send a 201 Created.

Response:

http
12345678
HTTP/1.1 201 Created
Location: /users/99
Content-Type: application/json

{
  "message": "User successfully created",
  "user_id": 99
}

7. HTTP Examples

Here is a quick cheat sheet of the most important status codes for REST APIs:
  • 200 OK: Standard success. (GET, PUT, PATCH)
  • 201 Created: Success, and a new resource was created. (POST)
  • 204 No Content: Success, but there is no data to return. (Often used for DELETE)
  • 400 Bad Request: The JSON sent by the client was invalid or missing fields.
  • 401 Unauthorized: The client didn't provide an API token, or the token is invalid.
  • 403 Forbidden: The client provided a valid token, but that user doesn't have admin rights to do this action.
  • 404 Not Found: The URL is wrong, or the specific resource ID doesn't exist.
  • 500 Internal Server Error: A generic catch-all for when the PHP script crashes.

8. JSON Examples

When returning a 4xx or 5xx status code, it is best practice to return a JSON body explaining *why* it failed.
json
1234567
{
  "error": {
    "code": 403,
    "message": "Forbidden. You must be an administrator to delete posts.",
    "documentation_url": "https://api.docs.com/errors#403"
  }
}

9. Best Practices

  • Never return a 200 OK for an error: Some bad APIs always return a 200 status code, but put "error": true in the JSON. This is an anti-pattern. Always use the proper HTTP status code so automated tools and libraries know the request failed without having to parse the JSON.
  • Keep it simple: You don't need to use all 60+ status codes. Stick to the common ones (200, 201, 204, 400, 401, 403, 404, 500) and you will cover 99% of use cases.

10. Common Mistakes

  • Confusing 401 and 403:
  • 401 = "I don't know who you are. Go log in." (Authentication issue)
  • 403 = "I know exactly who you are, but you are a standard user and this is an admin action." (Authorization issue)
  • Leaking info in 500 errors: When a 500 error happens, never output the raw PHP SQL error to the client, as hackers can use this to understand your database structure. Return a generic message instead.

11. Mini Exercises

  1. 1. What status code would you return if a user tries to POST JSON, but they forgot a closing bracket so the JSON is completely unreadable?
*(Answer: 400 Bad Request)*
  1. 2. What status code would you return if an API request is made to /users/999, but there are only 50 users in the database?
*(Answer: 404 Not Found)*

12. Coding Challenges

Challenge 1: Write a small PHP script that attempts to connect to a fake database. Wrap the connection in a try...catch block. If it fails, output a 500 Internal Server Error status code along with a safe, generic JSON error message.

13. MCQs with Answers

Question 1

What class of status codes indicates a problem on the client's end (like a typo in the URL)?

Question 2

Which code is specifically meant to say "A new resource has been successfully created"?

Question 3

If a user is logged in, but tries to access a VIP-only page without a VIP membership, what status should the server return?

14. Interview Questions

  • Q: Explain the difference between 401 Unauthorized and 403 Forbidden.
  • Q: Why is it considered bad practice to return a 200 OK status code with an error message in the JSON body?
  • Q: In what scenario would an API appropriately return a 204 No Content status code?

15. FAQs

Q: Is there a status code for "Rate Limit Exceeded"? A: Yes! If a user is spamming your API with too many requests, the standard response is 429 Too Many Requests.

Q: I saw a 418 I'm a teapot code. Is that real? A: Yes, but it's an internet joke. It was created as an April Fools' joke by the IETF in 1998, though some servers actually implement it as an Easter egg!

16. Summary

In Chapter 7, we learned that HTTP Status Codes are the primary way a server communicates the outcome of a request. The 200s mean success, the 400s mean the client messed up the request, and the 500s mean the server crashed. We also discussed the importance of pairing these status codes with descriptive JSON error payloads to make debugging easier for developers.

17. Next Chapter Recommendation

Now that we have covered the URL, the HTTP method, and the status codes, let's look at the actual data being sent back and forth. Proceed to Chapter 8: Request and Response Structure to deep dive into HTTP headers and content negotiation.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·