Last modified: Jan 28, 2025 By Alexander Williams

Install httpx in Python: Step-by-Step Guide

Python is a versatile language. It offers many libraries for various tasks. One such library is httpx. It is used for making HTTP requests.

In this guide, we will walk you through the steps to install httpx in Python. We will also provide examples to help you get started.

What is httpx?

httpx is a fully featured HTTP client for Python. It supports both synchronous and asynchronous requests. It is designed to be a modern alternative to the popular requests library.

With httpx, you can easily make HTTP requests. It also supports HTTP/2 and connection pooling. This makes it a powerful tool for web scraping and API interactions.

Step 1: Install Python

Before installing httpx, ensure Python is installed on your system. You can check this by running the following command in your terminal:


python --version

If Python is installed, you will see the version number. If not, download and install Python from the official website.

Step 2: Install httpx

Once Python is installed, you can install httpx using pip. Open your terminal and run the following command:


pip install httpx

This command will download and install the httpx library. It will also install any dependencies required by httpx.

Step 3: Verify Installation

After installation, verify that httpx is installed correctly. You can do this by running the following Python code:


import httpx
print(httpx.__version__)

If the installation was successful, this code will print the version of httpx installed on your system.

Step 4: Make Your First Request

Now that httpx is installed, let's make a simple HTTP GET request. The following code demonstrates how to do this:


import httpx

response = httpx.get('https://httpbin.org/get')
print(response.json())

This code sends a GET request to https://httpbin.org/get. It then prints the JSON response returned by the server.

Step 5: Handling Errors

When making HTTP requests, errors can occur. httpx provides a way to handle these errors gracefully. The following code shows how to handle errors:


import httpx

try:
    response = httpx.get('https://httpbin.org/status/404')
    response.raise_for_status()
except httpx.HTTPStatusError as e:
    print(f"Error: {e}")

This code attempts to make a GET request to a URL that returns a 404 status code. If the request fails, it catches the exception and prints an error message.

Conclusion

Installing httpx in Python is straightforward. With this guide, you should be able to install and start using httpx for your HTTP requests.

Remember to handle errors properly. This will ensure your application remains robust. For more advanced features, refer to the official httpx documentation.

Happy coding!