Last modified: Jan 29, 2025 By Alexander Williams

Python httpx.head() Guide: HTTP HEAD Requests

Python's httpx library is a powerful tool for making HTTP requests. Among its many functions, httpx.head() is particularly useful for sending HTTP HEAD requests. This guide will walk you through how to use it effectively.

What is httpx.head()?

The httpx.head() method sends a HEAD request to a specified URL. Unlike GET requests, HEAD requests do not return the response body. They only fetch the headers. This makes them ideal for checking resource availability or metadata.

Why Use httpx.head()?

Using httpx.head() can save bandwidth and time. Since it doesn't download the response body, it's faster and more efficient for tasks like checking if a resource exists or verifying its last-modified date.

Basic Usage of httpx.head()

Here's a simple example of how to use httpx.head() in Python:


import httpx

response = httpx.head('https://example.com')
print(response.status_code)
print(response.headers)

In this example, we send a HEAD request to 'https://example.com'. The response includes the status code and headers, but no body.

Example Output

Running the above code might produce output like this:


200
{'Content-Type': 'text/html', 'Content-Length': '1270', ...}

The status code 200 indicates success. The headers provide metadata about the resource.

Handling Errors

It's important to handle errors when making HTTP requests. Here's how you can do it with httpx.head():


import httpx

try:
    response = httpx.head('https://example.com/nonexistent')
    response.raise_for_status()
except httpx.HTTPStatusError as e:
    print(f"Error: {e}")

This code attempts to send a HEAD request to a non-existent resource. If the request fails, it catches the exception and prints an error message.

Common Use Cases

httpx.head() is commonly used for:

  • Checking if a resource exists without downloading it.
  • Verifying the last-modified date of a resource.
  • Fetching metadata like content type and length.

Comparing httpx.head() with Other Methods

While httpx.head() is great for fetching headers, other methods like httpx.get() and httpx.post() are better suited for different tasks. For example, httpx.get() retrieves the full response, including the body.

Conclusion

The httpx.head() method is a powerful tool for making HTTP HEAD requests in Python. It's efficient, easy to use, and perfect for tasks that require only headers. By mastering httpx.head(), you can optimize your web requests and improve your application's performance.

For more information on related topics, check out our guides on httpx.delete() and httpx.put().