Practical Example: Matching HTTP Status Codes

๐Ÿท๏ธ Conditional Logic and Decision Making / The Match Statement


๐ŸŒ Context Introduction

When building or troubleshooting web applications, you will frequently encounter HTTP status codes. These three-digit numbers tell you whether a request succeeded, failed, or requires further action. Instead of writing long chains of if-elif-else statements to handle each code, Python's match statement (introduced in Python 3.10) offers a cleaner and more readable approach. This practical example will show you how to map HTTP status codes to their meanings using pattern matching.


โš™๏ธ What Are HTTP Status Codes?

HTTP status codes are grouped into five categories:

  • 1xx (Informational) โ€“ The request was received, continuing process.
  • 2xx (Successful) โ€“ The request was successfully received, understood, and accepted.
  • 3xx (Redirection) โ€“ Further action needs to be taken to complete the request.
  • 4xx (Client Error) โ€“ The request contains bad syntax or cannot be fulfilled.
  • 5xx (Server Error) โ€“ The server failed to fulfill a valid request.

๐Ÿ› ๏ธ Building the Status Code Matcher

Let's create a function that takes an HTTP status code as input and returns a human-readable description. We will use the match statement to handle different code ranges and specific codes.

Step 1: Define the function and match structure

We start by defining a function called describe_status_code that accepts a single parameter: code. Inside the function, we use the match keyword followed by the variable we want to evaluate.

Step 2: Match specific codes first

The match statement allows us to check for exact values. We will handle the most common status codes explicitly:

  • If code equals 200, return "OK โ€“ Request succeeded"
  • If code equals 201, return "Created โ€“ Resource successfully created"
  • If code equals 301, return "Moved Permanently โ€“ Resource has moved"
  • If code equals 400, return "Bad Request โ€“ Invalid syntax"
  • If code equals 401, return "Unauthorized โ€“ Authentication required"
  • If code equals 403, return "Forbidden โ€“ Access denied"
  • If code equals 404, return "Not Found โ€“ Resource does not exist"
  • If code equals 500, return "Internal Server Error โ€“ Server encountered an error"

Step 3: Match ranges using wildcard patterns

For codes we do not handle explicitly, we can match entire ranges using the wildcard (_) pattern combined with conditional guards. The guard is an if condition placed after the pattern:

  • If code is between 100 and 199, return "Informational โ€“ Request is processing"
  • If code is between 200 and 299, return "Success โ€“ Request completed"
  • If code is between 300 and 399, return "Redirection โ€“ Further action needed"
  • If code is between 400 and 499, return "Client Error โ€“ Check your request"
  • If code is between 500 and 599, return "Server Error โ€“ Try again later"

Step 4: Handle invalid codes

Finally, we add a catch-all pattern using the wildcard _ to handle any code outside the valid HTTP range. This returns "Unknown status code".


๐Ÿ“Š Comparison: Match vs. If-Elif-Else

Feature Match Statement If-Elif-Else Chain
Readability Cleaner for multiple conditions Can become cluttered
Pattern matching Supports ranges, wildcards, and guards Requires explicit comparisons
Performance Optimized for pattern matching Evaluates each condition sequentially
Best use case Matching against fixed values or patterns Complex boolean logic

๐Ÿ•ต๏ธ How the Match Statement Works

The match statement evaluates the subject (our code variable) against a series of patterns. Each pattern is checked in order, from top to bottom. When a pattern matches, the corresponding block of code runs, and the match statement exits.

Key concepts to remember:

  • Literal patterns โ€“ Match exact values like 200 or 404
  • Wildcard pattern (_) โ€“ Matches anything, used as a default case
  • Guard conditions โ€“ Additional if checks placed after a pattern to refine matches
  • Order matters โ€“ More specific patterns should come before general ones

๐Ÿงช Testing the Function

To verify our function works correctly, we can call it with different status codes:

  • Calling describe_status_code(200) returns "OK โ€“ Request succeeded"
  • Calling describe_status_code(404) returns "Not Found โ€“ Resource does not exist"
  • Calling describe_status_code(302) returns "Redirection โ€“ Further action needed"
  • Calling describe_status_code(503) returns "Server Error โ€“ Try again later"
  • Calling describe_status_code(999) returns "Unknown status code"

๐ŸŽฏ Key Takeaways

  • The match statement provides a more readable alternative to long if-elif-else chains when working with fixed values or patterns.
  • Use exact literal patterns for specific status codes and wildcard patterns with guards for ranges.
  • Always include a default case using the wildcard pattern to handle unexpected inputs.
  • This approach scales well as you add more status codes or categories in the future.

๐Ÿ“š Next Steps

Now that you understand how to match HTTP status codes, try extending the function to include additional codes like 204 (No Content), 304 (Not Modified), or 429 (Too Many Requests). You can also experiment with matching against tuples or lists to handle multiple codes at once.


This example demonstrates how to use Python's match statement to categorize HTTP status codes into their standard meaning groups.


๐ŸŸข Example 1: Basic single status code match

This example shows the simplest form of matching a single HTTP status code to its description.

status_code = 200

match status_code:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Internal Server Error")

๐Ÿ“ค Output: OK


๐ŸŸก Example 2: Matching multiple status codes with OR patterns

This example shows how to match several status codes that share the same meaning using the pipe | operator.

status_code = 301

match status_code:
    case 200:
        print("Success")
    case 301 | 302 | 307:
        print("Redirect")
    case 404:
        print("Not Found")

๐Ÿ“ค Output: Redirect


๐Ÿ”ต Example 3: Using wildcard for any other status code

This example shows how to use the underscore _ as a wildcard to catch all unmatched status codes.

status_code = 418

match status_code:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case _:
        print("Unknown status code")

๐Ÿ“ค Output: Unknown status code


๐ŸŸ  Example 4: Grouping status codes by category

This example shows how to match status codes by their hundreds-digit category using a guard condition.

status_code = 403

match status_code:
    case code if 100 <= code <= 199:
        print("Informational")
    case code if 200 <= code <= 299:
        print("Success")
    case code if 300 <= code <= 399:
        print("Redirect")
    case code if 400 <= code <= 499:
        print("Client Error")
    case code if 500 <= code <= 599:
        print("Server Error")
    case _:
        print("Unknown")

๐Ÿ“ค Output: Client Error


๐Ÿ”ด Example 5: Matching with variable binding for specific ranges

This example shows how to bind the matched value to a variable and use it in a response message.

status_code = 201

match status_code:
    case 200:
        print("OK")
    case 201:
        print("Created")
    case 204:
        print("No Content")
    case code:
        print(f"Status code {code} is not a standard success code")

๐Ÿ“ค Output: Created


๐Ÿ“Š Comparison Table: HTTP Status Code Categories

Status Code Range Category Common Examples
100โ€“199 Informational 100 Continue
200โ€“299 Success 200 OK, 201 Created
300โ€“399 Redirect 301 Moved, 304 Not Modified
400โ€“499 Client Error 400 Bad Request, 404 Not Found
500โ€“599 Server Error 500 Internal Server Error

๐ŸŒ Context Introduction

When building or troubleshooting web applications, you will frequently encounter HTTP status codes. These three-digit numbers tell you whether a request succeeded, failed, or requires further action. Instead of writing long chains of if-elif-else statements to handle each code, Python's match statement (introduced in Python 3.10) offers a cleaner and more readable approach. This practical example will show you how to map HTTP status codes to their meanings using pattern matching.


โš™๏ธ What Are HTTP Status Codes?

HTTP status codes are grouped into five categories:

  • 1xx (Informational) โ€“ The request was received, continuing process.
  • 2xx (Successful) โ€“ The request was successfully received, understood, and accepted.
  • 3xx (Redirection) โ€“ Further action needs to be taken to complete the request.
  • 4xx (Client Error) โ€“ The request contains bad syntax or cannot be fulfilled.
  • 5xx (Server Error) โ€“ The server failed to fulfill a valid request.

๐Ÿ› ๏ธ Building the Status Code Matcher

Let's create a function that takes an HTTP status code as input and returns a human-readable description. We will use the match statement to handle different code ranges and specific codes.

Step 1: Define the function and match structure

We start by defining a function called describe_status_code that accepts a single parameter: code. Inside the function, we use the match keyword followed by the variable we want to evaluate.

Step 2: Match specific codes first

The match statement allows us to check for exact values. We will handle the most common status codes explicitly:

  • If code equals 200, return "OK โ€“ Request succeeded"
  • If code equals 201, return "Created โ€“ Resource successfully created"
  • If code equals 301, return "Moved Permanently โ€“ Resource has moved"
  • If code equals 400, return "Bad Request โ€“ Invalid syntax"
  • If code equals 401, return "Unauthorized โ€“ Authentication required"
  • If code equals 403, return "Forbidden โ€“ Access denied"
  • If code equals 404, return "Not Found โ€“ Resource does not exist"
  • If code equals 500, return "Internal Server Error โ€“ Server encountered an error"

Step 3: Match ranges using wildcard patterns

For codes we do not handle explicitly, we can match entire ranges using the wildcard (_) pattern combined with conditional guards. The guard is an if condition placed after the pattern:

  • If code is between 100 and 199, return "Informational โ€“ Request is processing"
  • If code is between 200 and 299, return "Success โ€“ Request completed"
  • If code is between 300 and 399, return "Redirection โ€“ Further action needed"
  • If code is between 400 and 499, return "Client Error โ€“ Check your request"
  • If code is between 500 and 599, return "Server Error โ€“ Try again later"

Step 4: Handle invalid codes

Finally, we add a catch-all pattern using the wildcard _ to handle any code outside the valid HTTP range. This returns "Unknown status code".


๐Ÿ“Š Comparison: Match vs. If-Elif-Else

Feature Match Statement If-Elif-Else Chain
Readability Cleaner for multiple conditions Can become cluttered
Pattern matching Supports ranges, wildcards, and guards Requires explicit comparisons
Performance Optimized for pattern matching Evaluates each condition sequentially
Best use case Matching against fixed values or patterns Complex boolean logic

๐Ÿ•ต๏ธ How the Match Statement Works

The match statement evaluates the subject (our code variable) against a series of patterns. Each pattern is checked in order, from top to bottom. When a pattern matches, the corresponding block of code runs, and the match statement exits.

Key concepts to remember:

  • Literal patterns โ€“ Match exact values like 200 or 404
  • Wildcard pattern (_) โ€“ Matches anything, used as a default case
  • Guard conditions โ€“ Additional if checks placed after a pattern to refine matches
  • Order matters โ€“ More specific patterns should come before general ones

๐Ÿงช Testing the Function

To verify our function works correctly, we can call it with different status codes:

  • Calling describe_status_code(200) returns "OK โ€“ Request succeeded"
  • Calling describe_status_code(404) returns "Not Found โ€“ Resource does not exist"
  • Calling describe_status_code(302) returns "Redirection โ€“ Further action needed"
  • Calling describe_status_code(503) returns "Server Error โ€“ Try again later"
  • Calling describe_status_code(999) returns "Unknown status code"

๐ŸŽฏ Key Takeaways

  • The match statement provides a more readable alternative to long if-elif-else chains when working with fixed values or patterns.
  • Use exact literal patterns for specific status codes and wildcard patterns with guards for ranges.
  • Always include a default case using the wildcard pattern to handle unexpected inputs.
  • This approach scales well as you add more status codes or categories in the future.

๐Ÿ“š Next Steps

Now that you understand how to match HTTP status codes, try extending the function to include additional codes like 204 (No Content), 304 (Not Modified), or 429 (Too Many Requests). You can also experiment with matching against tuples or lists to handle multiple codes at once.

Interactive Views

You are currently in ๐Ÿ“š All-in-One mode. Use the tabs at the top to switch to ๐Ÿ“– Theory Only or ๐Ÿ’ป Code Only views.

This example demonstrates how to use Python's match statement to categorize HTTP status codes into their standard meaning groups.


๐ŸŸข Example 1: Basic single status code match

This example shows the simplest form of matching a single HTTP status code to its description.

status_code = 200

match status_code:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Internal Server Error")

๐Ÿ“ค Output: OK


๐ŸŸก Example 2: Matching multiple status codes with OR patterns

This example shows how to match several status codes that share the same meaning using the pipe | operator.

status_code = 301

match status_code:
    case 200:
        print("Success")
    case 301 | 302 | 307:
        print("Redirect")
    case 404:
        print("Not Found")

๐Ÿ“ค Output: Redirect


๐Ÿ”ต Example 3: Using wildcard for any other status code

This example shows how to use the underscore _ as a wildcard to catch all unmatched status codes.

status_code = 418

match status_code:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case _:
        print("Unknown status code")

๐Ÿ“ค Output: Unknown status code


๐ŸŸ  Example 4: Grouping status codes by category

This example shows how to match status codes by their hundreds-digit category using a guard condition.

status_code = 403

match status_code:
    case code if 100 <= code <= 199:
        print("Informational")
    case code if 200 <= code <= 299:
        print("Success")
    case code if 300 <= code <= 399:
        print("Redirect")
    case code if 400 <= code <= 499:
        print("Client Error")
    case code if 500 <= code <= 599:
        print("Server Error")
    case _:
        print("Unknown")

๐Ÿ“ค Output: Client Error


๐Ÿ”ด Example 5: Matching with variable binding for specific ranges

This example shows how to bind the matched value to a variable and use it in a response message.

status_code = 201

match status_code:
    case 200:
        print("OK")
    case 201:
        print("Created")
    case 204:
        print("No Content")
    case code:
        print(f"Status code {code} is not a standard success code")

๐Ÿ“ค Output: Created


๐Ÿ“Š Comparison Table: HTTP Status Code Categories

Status Code Range Category Common Examples
100โ€“199 Informational 100 Continue
200โ€“299 Success 200 OK, 201 Created
300โ€“399 Redirect 301 Moved, 304 Not Modified
400โ€“499 Client Error 400 Bad Request, 404 Not Found
500โ€“599 Server Error 500 Internal Server Error