Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle an API response in two stages: first decide what its HTTP status means for the endpoint, then parse the body only if that response is expected to contain one. In Python, Requests and HTTPX both provide raise_for_status(), but status errors are different from network failures such as timeouts. Treat those cases separately, and avoid assuming that every successful response contains JSON.

What an HTTP status code tells you

An HTTP status code is a three-digit value from 100 to 599. Its first digit identifies a broad class: 1xx informational, 2xx successful, 3xx redirection, 4xx client error, or 5xx server error. The class is useful orientation, not a complete description of what your program should do. The API contract and request method determine whether a particular status is expected and what response body or follow-up action applies. See RFC 9110.

Status Typical meaning for a client Practical handling
200 OK The request succeeded; the response content depends on the method. For a GET, the body commonly represents the requested resource, but follow the endpoint contract.
201 Created The request succeeded and created one or more resources. Check for a Location header if the API uses it to identify the primary created resource.
202 Accepted The request was accepted for processing, but processing is not complete. Use the API’s documented polling or completion mechanism; acceptance does not promise eventual success.
204 No Content The request succeeded and has no response content. Return an empty result or another application-appropriate value; do not decode JSON.
3xx Redirection; another action may be needed. Check the client library’s redirect behavior and the API’s expectations.
4xx Client-error class, often indicating an issue with the request or its context. Handle expected cases, such as a documented 404, explicitly. Read an error body only according to the API contract.
429 Too Many Requests The server is limiting requests. If supplied, respect Retry-After and your application’s deadline.
5xx Server-error class. Decide whether a retry is safe for this operation; a 503 may include Retry-After.
304 Not Modified A conditional request indicates that the cached representation remains current. Use the cached representation as appropriate; the response has no content.

Clients are expected to understand the status class even when they do not recognize a particular registered code. Do not equate “below 400” with the exact success condition your endpoint requires: a redirect, for example, may call for different handling from a final 2xx response.

A reliable response-handling sequence

  1. Set a finite timeout suited to the application rather than letting a request wait indefinitely.
  2. Issue the request and distinguish failures while communicating with the server from a response that has an HTTP status.
  3. Handle statuses that are ordinary control flow for the endpoint, such as 404 for a missing resource or 204 for a successful empty result.
  4. For other error statuses, either raise an HTTP-status exception or inspect the response and its documented error fields.
  5. Parse the body only when the status, media type, and API contract indicate that a body is expected. JSON decoding can fail even when an HTTP response was received.

This separates three different outcomes: a response the endpoint considers successful, an HTTP error response from the server, and a request or transport failure where a response may not be available.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Handle responses with Requests

Requests’ raise_for_status() raises HTTPError for an HTTP error status. Its ok property is true when the status is below 400, including redirects; it does not mean “exactly 200.” Its json() method can raise JSONDecodeError if the response body is not valid JSON. The Requests documentation covers these behaviors in its API reference.

import requests

try:
    response = requests.get(
        "https://api.example.com/items/42",
        timeout=10,
    )
    response.raise_for_status()
except requests.exceptions.Timeout:
    # The request exceeded the timeout.
    raise
except requests.exceptions.HTTPError as exc:
    # The server returned an HTTP error status.
    status = exc.response.status_code
    # Inspect documented error fields if the API defines them.
    raise
except requests.exceptions.RequestException:
    # Another Requests-level failure, such as a connection error.
    raise

if response.status_code == 204:
    result = None
else:
    result = response.json()

The example treats a 204 response as an empty result before attempting JSON decoding. Extend that branch for other endpoint-specific outcomes. Do not assume every error response contains JSON: an API may return no body, text, or a different format.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Handle responses with HTTPX

HTTPX distinguishes an HTTP status error from a failure while making the request. Calling raise_for_status() raises HTTPStatusError for a non-2xx status; request and transport problems, including timeouts, belong to the RequestError family. HTTPX documents the distinction in its quickstart and exception reference.

import httpx

try:
    response = httpx.get(
        "https://api.example.com/items/42",
        timeout=10,
    )
    response.raise_for_status()
except httpx.RequestError as exc:
    # A network, timeout, or other request/transport failure.
    raise RuntimeError(f"Request failed for {exc.request.url}") from exc
except httpx.HTTPStatusError as exc:
    # The server returned a non-2xx status.
    raise RuntimeError(
        f"HTTP {exc.response.status_code} for {exc.request.url}"
    ) from exc

if response.status_code == 204:
    result = None
else:
    result = response.json()

HTTPX does not follow redirects by default for its request calls. If an endpoint relies on redirects, configure or handle that behavior deliberately rather than assuming the final response will already be returned.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

When to inspect a status and when to raise

  • Inspect explicitly when a status is an expected branch in the application, such as “not found” or “accepted for asynchronous processing.” This lets you preserve the difference between normal control flow and unexpected errors.
  • Use raise_for_status() when treating HTTP error responses as exceptions makes the surrounding control flow clearer. Catch the library’s status exception if you need the status code or documented error fields.
  • Catch request failures separately from HTTP status errors. A timeout or connection failure does not establish that the server rejected the operation.
  • Check body expectations independently of status handling. A status can be successful while the body is empty, non-JSON, or otherwise different from what the client expected.

For a 404, decide whether “not found” is an expected result for that particular endpoint. If so, inspect and handle it before turning other HTTP errors into exceptions. If the API documents a structured error body, read its specified fields; do not presume a universal error schema.

Parse the body only when the response calls for it

A valid HTTP response does not guarantee a JSON body. RFC 9110 specifies that 204 and 304 responses have no content, and an endpoint may also return text, binary data, or an empty body for other statuses. Choose the parser from the endpoint’s response contract and, where relevant, the response media type.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

When response.json() fails, treat that as a body-decoding problem, not proof that the HTTP request itself failed. Check the status, whether that status should have a body, and what content the API documents. If a response may legitimately be empty, branch before decoding; if the endpoint promises JSON, surface the unexpected body as a separate error rather than silently treating it as a successful result.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Retry carefully, especially after a timeout

Retries can duplicate side effects. RFC 9110 defines safe methods and PUT and DELETE as idempotent: repeating them has the same intended effect as making the request once. A client should not automatically retry a non-idempotent request unless it knows the operation is safe to repeat or can determine the original request was not applied. A timeout on a write does not prove the server did nothing; it may have completed the operation before the connection failed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

If a response includes Retry-After, its value can be a delay in seconds or an HTTP date. RFC 9110 discusses its use with 503, and RFC 6585 permits it with 429 responses. Parse the value according to its format, then bound the wait by your overall deadline and the API’s documented limits. See RFC 6585.

Do not retry every exception or every 5xx automatically. Decide based on the operation’s idempotency, whether you received a response, any server-provided delay, and the endpoint’s retry policy.

Use Python’s standard library with urllib

If you use urllib.request.urlopen(), account for its exception model rather than applying Requests or HTTPX patterns directly. It handles some responses such as redirects, and raises urllib.error.HTTPError for responses it cannot handle; the exception includes the integer status code. Handle HTTPError and URLError according to your application’s needs. See the Python urllib.error documentation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.