Convert Figma logo to code with AI

encode logohttpx

A next generation HTTP client for Python. 🦋

12,973
824
12,973
71

Top Related Projects

14,938

Asynchronous HTTP client/server framework for asyncio and Python

51,964

A simple, yet elegant, HTTP library.

3,759

urllib3 is a user-friendly HTTP client library for Python

1,049

HTTP/2 for Python.

6,078

Trio – a friendly Python library for async concurrency and I/O

Quick Overview

HTTPX is a fully featured HTTP client for Python 3, which provides sync and async APIs. It supports HTTP/1.1 and HTTP/2, and includes a command-line client. HTTPX is designed to be a modern, user-friendly alternative to other HTTP libraries like Requests.

Pros

  • Supports both synchronous and asynchronous APIs
  • Built-in HTTP/2 support
  • Extensive feature set, including connection pooling, cookie persistence, and proxy support
  • Type annotations for better IDE integration and code quality

Cons

  • Slightly slower performance compared to some other HTTP libraries
  • Relatively new project, which may lead to more frequent changes and updates
  • Larger dependency footprint compared to simpler HTTP clients
  • May require additional learning for developers familiar with other HTTP libraries

Code Examples

  1. Simple GET request:
import httpx

response = httpx.get('https://api.github.com/repos/encode/httpx')
print(response.json()['description'])
  1. Asynchronous POST request:
import asyncio
import httpx

async def main():
    async with httpx.AsyncClient() as client:
        response = await client.post('https://httpbin.org/post', data={'key': 'value'})
        print(response.json())

asyncio.run(main())
  1. Using HTTP/2:
import httpx

with httpx.Client(http2=True) as client:
    response = client.get('https://nghttp2.org')
    print(response.http_version)  # Should print 'HTTP/2'

Getting Started

To get started with HTTPX, first install it using pip:

pip install httpx

Then, you can use it in your Python code:

import httpx

# Make a GET request
response = httpx.get('https://api.github.com/repos/encode/httpx')
print(response.status_code)
print(response.json())

# Make a POST request
data = {'key': 'value'}
response = httpx.post('https://httpbin.org/post', json=data)
print(response.json())

For more advanced usage, including async support and customization options, refer to the official documentation.

Competitor Comparisons

14,938

Asynchronous HTTP client/server framework for asyncio and Python

Pros of aiohttp

  • More mature and established project with a larger ecosystem
  • Supports both client and server-side HTTP operations
  • Offers more fine-grained control over connection pooling and SSL settings

Cons of aiohttp

  • Less intuitive API, especially for beginners
  • Slower development cycle and less frequent updates
  • Requires more boilerplate code for common tasks

Code Comparison

aiohttp example:

async with aiohttp.ClientSession() as session:
    async with session.get('https://api.example.com') as response:
        data = await response.json()

httpx example:

async with httpx.AsyncClient() as client:
    response = await client.get('https://api.example.com')
    data = response.json()

Key Differences

  • httpx provides a more modern and user-friendly API
  • aiohttp offers more advanced features for complex use cases
  • httpx has better support for HTTP/2 and automatic redirects
  • aiohttp has a larger community and more third-party extensions

Performance Considerations

  • aiohttp generally performs better in high-concurrency scenarios
  • httpx has improved performance in recent versions, narrowing the gap
  • Both libraries are suitable for most asynchronous HTTP tasks

Conclusion

Choose aiohttp for complex server-side applications or when you need fine-grained control. Opt for httpx if you prefer a more intuitive API and don't require advanced features. Both libraries are solid choices for asynchronous HTTP operations in Python.

51,964

A simple, yet elegant, HTTP library.

Pros of Requests

  • Widely adopted and battle-tested in production environments
  • Extensive documentation and community support
  • Simple and intuitive API for common HTTP operations

Cons of Requests

  • Lacks native async support
  • No built-in HTTP/2 support
  • Limited type hinting compared to modern Python libraries

Code Comparison

Requests:

import requests

response = requests.get('https://api.example.com/data')
data = response.json()

HTTPX:

import httpx

async with httpx.AsyncClient() as client:
    response = await client.get('https://api.example.com/data')
    data = response.json()

Key Differences

  • HTTPX provides native async support, while Requests requires third-party libraries for asynchronous operations
  • HTTPX supports HTTP/2 out of the box, whereas Requests is limited to HTTP/1.1
  • HTTPX offers more comprehensive type hinting, enhancing code reliability and IDE support
  • Requests has a larger ecosystem of extensions and plugins due to its longer history and wider adoption

Both libraries offer similar core functionality for making HTTP requests, but HTTPX is designed with modern Python features in mind, making it more suitable for projects leveraging async programming and newer HTTP standards.

3,759

urllib3 is a user-friendly HTTP client library for Python

Pros of urllib3

  • Widely used and battle-tested library with extensive compatibility
  • Supports connection pooling and thread safety
  • Automatic retry and redirect handling

Cons of urllib3

  • Less modern API design compared to HTTPX
  • Lacks native async support
  • More verbose syntax for common operations

Code Comparison

urllib3:

import urllib3

http = urllib3.PoolManager()
r = http.request('GET', 'https://example.com')
print(r.status)
print(r.data)

HTTPX:

import httpx

with httpx.Client() as client:
    r = client.get('https://example.com')
    print(r.status_code)
    print(r.text)

Key Differences

  • HTTPX offers a more modern and intuitive API
  • HTTPX provides built-in async support
  • urllib3 has broader compatibility with older Python versions
  • HTTPX includes features like automatic HTTP/2 and connection pooling by default
  • urllib3 requires manual SSL certificate verification, while HTTPX handles it automatically

Both libraries are actively maintained and have their strengths. urllib3 is a solid choice for projects requiring broad compatibility, while HTTPX offers a more modern experience with async support and a cleaner API. The choice between them often depends on specific project requirements and personal preferences.

1,049

HTTP/2 for Python.

Pros of hyper

  • Focuses on HTTP/2 support, providing advanced features for this protocol
  • Implements the HTTP/2 protocol in pure Python, offering better compatibility across platforms
  • Provides a lower-level API, giving developers more control over connection management

Cons of hyper

  • Less actively maintained compared to httpx
  • Limited support for older HTTP versions (primarily focused on HTTP/2)
  • Steeper learning curve due to its lower-level API and focus on HTTP/2 specifics

Code Comparison

httpx example:

import httpx

with httpx.Client() as client:
    response = client.get('https://example.com')
    print(response.text)

hyper example:

from hyper import HTTP20Connection

conn = HTTP20Connection('example.com')
conn.request('GET', '/')
resp = conn.get_response()
print(resp.read())

The code examples highlight the difference in API design. httpx provides a higher-level, more user-friendly interface, while hyper offers a lower-level API that requires more manual connection management but provides greater control over HTTP/2 specific features.

6,078

Trio – a friendly Python library for async concurrency and I/O

Pros of Trio

  • Designed for structured concurrency, making it easier to manage complex asynchronous workflows
  • Provides a more intuitive and safer approach to handling cancellation and timeouts
  • Offers a unique nursery system for managing child tasks

Cons of Trio

  • Limited ecosystem compared to asyncio, which HTTPX is built upon
  • Steeper learning curve for developers familiar with traditional async/await patterns
  • Not as widely adopted in the Python community as asyncio-based libraries

Code Comparison

Trio example:

import trio

async def main():
    async with trio.open_nursery() as nursery:
        nursery.start_soon(task1)
        nursery.start_soon(task2)

trio.run(main)

HTTPX example:

import asyncio
import httpx

async def main():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://example.com')
        print(response.text)

asyncio.run(main())

While both libraries support asynchronous programming, Trio focuses on structured concurrency and task management, whereas HTTPX is specifically designed for making HTTP requests. HTTPX can be used with asyncio or Trio, providing flexibility in choosing the async framework. Trio's nursery system offers a more explicit way of managing concurrent tasks, while HTTPX leverages the familiar async/await syntax for handling HTTP operations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

HTTPX

HTTPX - A next-generation HTTP client for Python.

Test Suite Package version

HTTPX is a fully featured HTTP client library for Python 3. It includes an integrated command line client, has support for both HTTP/1.1 and HTTP/2, and provides both sync and async APIs.


Install HTTPX using pip:

pip install httpx

Now, let's get started:

>>> import httpx
>>> r = httpx.get('https://www.example.org/')
>>> r
<Response [200 OK]>
>>> r.status_code
200
>>> r.headers['content-type']
'text/html; charset=UTF-8'
>>> r.text
'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'

Or, using the command-line client.

pip install 'httpx[cli]'  # The command line client is an optional dependency.

Which now allows us to use HTTPX directly from the command-line...

httpx --help

Sending a request...

httpx http://httpbin.org/json

Features

HTTPX builds on the well-established usability of requests, and gives you:

Plus all the standard features of requests...

  • International Domains and URLs
  • Keep-Alive & Connection Pooling
  • Sessions with Cookie Persistence
  • Browser-style SSL Verification
  • Basic/Digest Authentication
  • Elegant Key/Value Cookies
  • Automatic Decompression
  • Automatic Content Decoding
  • Unicode Response Bodies
  • Multipart File Uploads
  • HTTP(S) Proxy Support
  • Connection Timeouts
  • Streaming Downloads
  • .netrc Support
  • Chunked Requests

Installation

Install with pip:

pip install httpx

Or, to include the optional HTTP/2 support, use:

pip install httpx[http2]

HTTPX requires Python 3.8+.

Documentation

Project documentation is available at https://www.python-httpx.org/.

For a run-through of all the basics, head over to the QuickStart.

For more advanced topics, see the Advanced Usage section, the async support section, or the HTTP/2 section.

The Developer Interface provides a comprehensive API reference.

To find out about tools that integrate with HTTPX, see Third Party Packages.

Contribute

If you want to contribute with HTTPX check out the Contributing Guide to learn how to start.

Dependencies

The HTTPX project relies on these excellent libraries:

  • httpcore - The underlying transport implementation for httpx.
    • h11 - HTTP/1.1 support.
  • certifi - SSL certificates.
  • idna - Internationalized domain name support.
  • sniffio - Async library autodetection.

As well as these optional installs:

  • h2 - HTTP/2 support. (Optional, with httpx[http2])
  • socksio - SOCKS proxy support. (Optional, with httpx[socks])
  • rich - Rich terminal support. (Optional, with httpx[cli])
  • click - Command line client support. (Optional, with httpx[cli])
  • brotli or brotlicffi - Decoding for "brotli" compressed responses. (Optional, with httpx[brotli])
  • zstandard - Decoding for "zstd" compressed responses. (Optional, with httpx[zstd])

A huge amount of credit is due to requests for the API layout that much of this work follows, as well as to urllib3 for plenty of design inspiration around the lower-level networking details.


HTTPX is BSD licensed code.
Designed & crafted with care.

— 🦋 —