Table of Contents
What is Httpx
Installing Httpx
Sending HTTP requests
Send asynchronous HTTP requests
Setting request headers
Set request parameters
Send Request Body
Send JSON data
Set timeout
Error handling
Certificate Verification
Using a proxy
Upload files
使用 Cookie
Home Backend Development Python Tutorial How to use python httpx

How to use python httpx

Apr 18, 2023 pm 11:43 PM
python httpx

What is Httpx

Httpx is a Python library that provides a modern, easy-to-use HTTP client and server. Httpx works with Python's asynchronous framework and supports WebSocket and HTTP/2. Httpx offers excellent performance, security, and flexible configuration for a variety of different protocols, encodings, and authentication schemes.

Installing Httpx

Installing the Httpx library is very simple. Just run the following command using the pip package manager:

pip install httpx

If you are using Python 3.7 or earlier, you need to install Httpx's asynchronous dependency aiohttp.

You can install it by running the following command:

pip install httpx[aiohttp]

Sending HTTP requests

Sending HTTP requests using Httpx is very simple. Here is a simple example that uses Httpx to send a GET request:

import httpx

response = httpx.get('https://www.baidu.com')
print(response.status_code)
print(response.text)

In this example, we sent a GET request using the get method of Httpx. The requested URL is https://www.baidu.com. This method returns a Response object that we can use to access the response status code and response text.

Httpx supports many different HTTP methods, including GET, POST, PUT, DELETE, HEAD, and OPTIONS. You can use Httpx methods to send these requests.

Here are some examples:

import httpx

response = httpx.post('https://www.baidu.com', data={'key': 'value'})
response = httpx.put('https://www.baidu.com', data={'key': 'value'})
response = httpx.delete('https://www.baidu.com')
response = httpx.head('https://www.baidu.com')
response = httpx.options('https://www.baidu.com')

Each request in the above examples can be sent using Httpx methods. Most of these methods support passing parameters such as data, headers, and query parameters.

Send asynchronous HTTP requests

Httpx also supports asynchronous HTTP requests. The following is a simple example that uses Httpx to send an asynchronous GET request:

import httpx
import asyncio

async def get_request():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://www.baidu.com')
        print(response.status_code)
        print(response.text)

asyncio.run(get_request())

In this example, we create an asynchronous function named get_request that uses the AsyncClient class of Httpx to send an asynchronous GET ask. In the asynchronous function, we use the async with statement to create an asynchronous client of Httpx. Creating the client this way ensures that the client is automatically closed after the request is completed. We then use the await keyword to asynchronously wait for the response and access the response status code and response text from the response object.

Similar to synchronous requests, Httpx's asynchronous client also supports many different HTTP methods.

Here are some examples:

import httpx
import asyncio

async def post_request():
    async with httpx.AsyncClient() as client:
        response = await client.post('https://www.baidu.com', data={'key': 'value'})
        print(response.status_code)
        print(response.text)

asyncio.run(post_request())

Setting request headers

When sending an HTTP request, you typically need to set request headers. Httpx allows you to set request headers by passing the headers parameter in the request method.

Here is an example:

import httpx

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

response = httpx.get('https://www.baidu.com', headers=headers)
print(response.status_code)
print(response.text)

In this example, we set a request header named User-Agent using the headers parameter.

Set request parameters

Httpx allows you to set request parameters when sending an HTTP request.

Here are some examples:

import httpx

params = {'key1': 'value1', 'key2': 'value2'}

response = httpx.get('https://www.baidu.com', params=params)
print(response.status_code)
print(response.text)

In this example, we set two query parameters key1 and key2 using the params parameter.

Send Request Body

When sending POST, PUT, and DELETE requests, you typically need to include data in the request body. Httpx allows you to set data in the request body using the data parameter.

The following is an example:

import httpx

data = {'key': 'value'}

response = httpx.post('https://www.baidu.com', data=data)
print(response.status_code)
print(response.text)

In this example, we use the data parameter to set a request body parameter named key.

Send JSON data

Httpx allows you to send JSON data using the json parameter.

The following is an example:

import httpx

data = {'key': 'value'}

response = httpx.post('https://www.baidu.com', json=data)
print(response.status_code)
print(response.text)

In this example, we use the json parameter to set a JSON request body parameter named key.

Set timeout

When sending an HTTP request, you usually need to set a timeout. Httpx allows you to set a timeout using the timeout parameter.

Here is an example:

import httpx

response = httpx.get('https://www.baidu.com', timeout=5)
print(response.status_code)
print(response.text)

In this example, we set a timeout of 5 seconds using the timeout parameter.

Error handling

Httpx can throw a variety of different types of exceptions to help you diagnose and solve problems. Here are some common exceptions:

  • httpx.HTTPError: Raised when an HTTP error occurs.

  • httpx.RequestError: Raised when a request error occurs.

  • httpx.NetworkError: Raised when a network error occurs.

  • httpx.TimeoutException: Raised when a timeout occurs.

When handling these exceptions, you can use try/except statements to catch the exception and take appropriate action. Here is an example:

import httpx

try:
    response = httpx.get('https://www.baidu.com')
    response.raise_for_status()
except httpx.HTTPError as http_error:
    print(f'HTTP error occurred: {http_error}')
except httpx.RequestError as request_error:
    print(f'Request error occurred: {request_error}')
except httpx.NetworkError as network_error:
    print(f'Network error occurred: {network_error}')
except httpx.TimeoutException as timeout_error:
    print(f'Timeout error occurred: {timeout_error}')
else:
    print(response.status_code)
    print(response.text)

In this example, we use try/except statements to catch all exceptions that may occur and take appropriate action based on the exception type.

Certificate Verification

Httpx allows you to verify SSL certificates to ensure a secure connection to your server. By default, Httpx verifies SSL certificates. If you need to disable certificate verification, you can set the verify parameter to False.

Here is an example:

import httpx

response = httpx.get('https://www.baidu.com', verify=False)
print(response.status_code)
print(response.text)

In this example, we set the verify parameter to False to disable SSL certificate verification.

Using a proxy

Httpx allows you to use a proxy to send HTTP requests. Here is an example:

import httpx

proxies = {
    'http://http-proxy-server:8080',
    'https://https-proxy-server:8080'
}

response = httpx.get('https://www.baidu.com', proxies=proxies)
print(response.status_code)
print(response.text)

In this example, we set up two proxy servers using the proxies parameter.

Upload files

Httpx allows you to upload files using the files parameter. Here is an example:

import httpx

files = {'file': ('file.txt', open('file.txt', 'rb'))}

response = httpx.post('https://www.baidu.com', files=files)
print(response.status_code)
print(response.text)

在这个示例中,我们使用 files 参数上传了名为 file.txt 的文件。

Httpx 允许您使用 cookies 参数发送 cookie。以下是一个示例:

import httpx

cookies = {'name': 'value'}

response = httpx.get('https://www.baidu.com', cookies=cookies)
print(response.status_code)
print(response.text)

在这个示例中,我们使用 cookies 参数发送了名为 name 的 cookie。

The above is the detailed content of How to use python httpx. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to install packages from a requirements.txt file in Python How to install packages from a requirements.txt file in Python Sep 18, 2025 am 04:24 AM

Run pipinstall-rrequirements.txt to install the dependency package. It is recommended to create and activate the virtual environment first to avoid conflicts, ensure that the file path is correct and that the pip has been updated, and use options such as --no-deps or --user to adjust the installation behavior if necessary.

How to test Python code with pytest How to test Python code with pytest Sep 20, 2025 am 12:35 AM

Python is a simple and powerful testing tool in Python. After installation, test files are automatically discovered according to naming rules. Write a function starting with test_ for assertion testing, use @pytest.fixture to create reusable test data, verify exceptions through pytest.raises, supports running specified tests and multiple command line options, and improves testing efficiency.

How to handle command line arguments in Python How to handle command line arguments in Python Sep 21, 2025 am 03:49 AM

Theargparsemoduleistherecommendedwaytohandlecommand-lineargumentsinPython,providingrobustparsing,typevalidation,helpmessages,anderrorhandling;usesys.argvforsimplecasesrequiringminimalsetup.

What is BIP? Why are they so important to the future of Bitcoin? What is BIP? Why are they so important to the future of Bitcoin? Sep 24, 2025 pm 01:51 PM

Table of Contents What is Bitcoin Improvement Proposal (BIP)? Why is BIP so important? How does the historical BIP process work for Bitcoin Improvement Proposal (BIP)? What is a BIP type signal and how does a miner send it? Taproot and Cons of Quick Trial of BIP Conclusion‍Any improvements to Bitcoin have been made since 2011 through a system called Bitcoin Improvement Proposal or “BIP.” Bitcoin Improvement Proposal (BIP) provides guidelines for how Bitcoin can develop in general, there are three possible types of BIP, two of which are related to the technological changes in Bitcoin each BIP starts with informal discussions among Bitcoin developers who can gather anywhere, including Twi

From beginners to experts: 10 must-have free public dataset websites From beginners to experts: 10 must-have free public dataset websites Sep 15, 2025 pm 03:51 PM

For beginners in data science, the core of the leap from "inexperience" to "industry expert" is continuous practice. The basis of practice is the rich and diverse data sets. Fortunately, there are a large number of websites on the Internet that offer free public data sets, which are valuable resources to improve skills and hone your skills.

How to choose a computer that is suitable for big data analysis? Configuration Guide for High Performance Computing How to choose a computer that is suitable for big data analysis? Configuration Guide for High Performance Computing Sep 15, 2025 pm 01:54 PM

Big data analysis needs to focus on multi-core CPU, large-capacity memory and tiered storage. Multi-core processors such as AMDEPYC or RyzenThreadripper are preferred, taking into account the number of cores and single-core performance; memory is recommended to start with 64GB, and ECC memory is preferred to ensure data integrity; storage uses NVMeSSD (system and hot data), SATASSD (common data) and HDD (cold data) to improve overall processing efficiency.

How can you create a context manager using the @contextmanager decorator in Python? How can you create a context manager using the @contextmanager decorator in Python? Sep 20, 2025 am 04:50 AM

Import@contextmanagerfromcontextlibanddefineageneratorfunctionthatyieldsexactlyonce,wherecodebeforeyieldactsasenterandcodeafteryield(preferablyinfinally)actsas__exit__.2.Usethefunctioninawithstatement,wheretheyieldedvalueisaccessibleviaas,andthesetup

How to write automation scripts for daily tasks in Python How to write automation scripts for daily tasks in Python Sep 21, 2025 am 04:45 AM

Identifyrepetitivetasksworthautomating,suchasorganizingfilesorsendingemails,focusingonthosethatoccurfrequentlyandtakesignificanttime.2.UseappropriatePythonlibrarieslikeos,shutil,glob,smtplib,requests,BeautifulSoup,andseleniumforfileoperations,email,w

See all articles