
Product
Introducing Supply Chain Attack Campaigns Tracking in the Socket Dashboard
Campaign-level threat intelligence in Socket now shows when active supply chain attacks affect your repositories and packages.
web3http
Advanced tools
HTTPX - A next-generation HTTP client for Python.
HTTPX is a fully featured HTTP client for Python 3, which provides sync and async APIs, and support for both HTTP/1.1 and HTTP/2.
Note: HTTPX should be considered in beta. We believe we've got the public API to
a stable point now, but would strongly recommend pinning your dependencies to the 0.17.*
release, so that you're able to properly review API changes between package updates. A 1.0 release is expected to be issued sometime in 2021.
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 async API...
Use IPython or Python 3.8+ with python -m asyncio to try this code interactively.
>>> import httpx
>>> async with httpx.AsyncClient() as client:
... r = await client.get('https://www.example.org/')
...
>>> r
<Response [200 OK]>
HTTPX builds on the well-established usability of requests, and gives you:
Plus all the standard features of requests...
Install with pip:
$ pip install httpx
Or, to include the optional HTTP/2 support, use:
$ pip install httpx[http2]
HTTPX requires Python 3.6+.
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.
If you want to contribute with HTTPX check out the Contributing Guide to learn how to start.
The HTTPX project relies on these excellent libraries:
httpcore - The underlying transport implementation for httpx.
h11 - HTTP/1.1 support.h2 - HTTP/2 support. (Optional)certifi - SSL certificates.rfc3986 - URL parsing & normalization.
idna - Internationalized domain name support.sniffio - Async library autodetection.brotlipy - Decoding for "brotli" compressed responses. (Optional)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 & built in Brighton, England.
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog.
httpx.MockTransport(), allowing to mock out a transport using pre-determined responses. (Pull #1401, Pull #1449)httpx.HTTPTransport() and httpx.AsyncHTTPTransport() default transports. (Pull #1399)httpx.Client(mounts=...). (Pull #1362)chunk_size parameter to iter_raw(), iter_bytes(), iter_text(). (Pull #1277)keepalive_expiry parameter to httpx.Limits() configuration. (Pull #1398)httpx.Cookies to display available cookies. (Pull #1411)params=<tuple> (previously only params=<list> was supported). (Pull #1426)raw_path to ASGI scope. (Pull #1357)create_ssl_context defaults to use trust_env=True. (Pull #1447)PATH_INFO. (Pull #1391)base_url. (Pull #1407)request.aclose(). (Pull #1465)response.next() and response.anext() methods in favour of response.next_request attribute. (Pull #1339)__enter__/__exit__/__aenter__/__aexit__ in a way that supports subclasses of Client and AsyncClient. (Pull #1336)response.next_request (Pull #1334)Headers and dicts or lists of two-tuples. Eg. assert response.headers == {"Content-Length": 24} (Pull #1326).read() when Response instances are created with content=<str> (Pull #1324)response.elapsed property. (Pull #1313).stream(). (Pull #1312)path component, as-per the ASGI spec. (Pull #1307)response.num_bytes_downloaded. (Pull #1268)Request(content=...) for byte content, instead of overloading Request(data=...) (Pull #1266)url.copy_with(...). (Pull #1285)Request instances, vs default client.headers. (Pull #1248)AsyncClient instances will now raise warnings if garbage collected. (Pull #1197)Response(content=..., text=..., html=..., json=...) for creating usable response instances in code. (Pull #1265, #1297)url.path is now URL escaped. (Pull #1285)url.userinfo and url.query are not URL escaped, and so return bytes. (Pull #1285)url.authority property in favour of url.netloc, since "authority" was semantically incorrect. (Pull #1285)url.full_path property in favour of url.raw_path, for better consistency with other parts of the API. (Pull #1285)chardet library for auto-detecting charsets, instead defaulting to a simpler approach when no charset is specified. (#1269).netrc lookups should use host, not host+port. (Pull #1298)URLLib3Transport class no longer exists. We've published it instead as an example of a custom transport class. (Pull #1182)request.timer attribute, which was being used internally to set response.elapsed. (Pull #1249)response.decoder attribute, which was being used internally. (Pull #1276)Request.prepare() is now a private method. (Pull #1284)Headers.getlist() method had previously been deprecated in favour of Headers.get_list(). It is now fully removed.QueryParams.getlist() method had previously been deprecated in favour of QueryParams.get_list(). It is now fully removed.URL.is_ssl property had previously been deprecated in favour of URL.scheme == "https". It is now fully removed.httpx.PoolLimits class had previously been deprecated in favour of httpx.Limits. It is now fully removed.max_keepalive setting had previously been deprecated in favour of the more explicit max_keepalive_connections. It is now fully removed.httpx.Timeout(5.0, connect_timeout=60.0) style had previously been deprecated in favour of httpx.Timeout(5.0, connect=60.0). It is now fully removed.httpx.Timeout(connect=60.0), had previously been deprecated in favour of enforcing a more explicit style, such as httpx.Timeout(5.0, connect=60.0). This is now strictly enforced.http.Response() may now be instantiated without a request=... parameter. Useful for some unit testing cases. (Pull #1238)103 Early Hints and 425 Too Early status codes. (Pull #1244)DigestAuth now handles responses that include multiple 'WWW-Authenticate' headers. (Pull #1240)__enter__/__exit__ or __aenter__/__aexit__ when client is used in a context manager style. (Pull #1218)client.get(..., auth=None) to bypass the default authentication on a clients. (Pull #1115)client.auth = ... property setter. (Pull #1185)httpx.get(..., proxies=...) on top-level request functions. (Pull #1198)cookies=[(key, value)] list-of-two-tuples style usage. (Pull #1211)Content-Length header on streaming requests. (Pull #1170)HEAD requests, setting allow_redirects=True. (Pull #1183)httpx exception, not the underlying httpcore exception. (Pull #1190)httpcore traceback, when transport exceptions occur. (Pull #1199)httpx.URL(...) class now raises httpx.InvalidURL on invalid URLs, rather than exposing the underlying rfc3986 exception. If a redirect response includes an invalid 'Location' header, then a RemoteProtocolError exception is raised, which will be associated with the request that caused it. (Pull #1163)Set-Cookie headers became broken in the 0.14.0 release, and is now resolved. (Pull #1156)The 0.14 release includes a range of improvements to the public API, intended on preparing for our upcoming 1.0 release.
pip install httpx[http2] if you want to include the HTTP/2 dependancies.http to https if the host is on the HSTS list can be beneficial in avoiding roundtrips to incorrectly formed URLs, but on balance we've decided to remove this feature, on the principle of least surprise. Most programmatic clients do not include HSTS support, and for now we're opting to remove our support for it.httpx.HTTPError usage, but we've got a clearer overall structure now. See https://www.python-httpx.org/exceptions/ for more details.When upgrading you should be aware of the following public API changes. Note that deprecated usages will currently continue to function, but will issue warnings.
httpx.codes consistently instead of httpx.StatusCodes.httpx.Timeout() should now always include an explicit default. Eg. httpx.Timeout(None, pool=5.0).httpx.Timeout(), we now have more concisely named keyword arguments. Eg. read=5.0, instead of read_timeout=5.0.httpx.Limits() instead of httpx.PoolLimits(), and limits=... instead of pool_limits=....httpx.Limits(max_keepalive=...) argument is now deprecated in favour of a more explicit httpx.Limits(max_keepalive_connections=...).Client(proxies={...}) should now be in the style of {"http://": ...}, rather than {"http": ...}.Headers.getlist() and QueryParams.getlist() are deprecated in favour of more consistent .get_list() variants.URL.is_ssl property is deprecated in favour of URL.scheme == "https".URL.join(relative_url=...) method is now URL.join(url=...). This change does not support warnings for the deprecated usage style.One notable aspect of the 0.14.0 release is that it tightens up the public API for httpx, by ensuring that several internal attributes and methods have now become strictly private.
The following previously had nominally public names on the client, but were all undocumented and intended solely for internal usage. They are all now replaced with underscored names, and should not be relied on or accessed.
These changes should not affect users who have been working from the httpx documentation.
.merge_url(), .merge_headers(), .merge_cookies(), .merge_queryparams().build_auth(), .build_redirect_request().redirect_method(), .redirect_url(), .redirect_headers(), .redirect_stream().send_handling_redirects(), .send_handling_auth(), .send_single_request().init_transport(), .init_proxy_transport().proxies, .transport, .netrc, .get_proxy_map()See pull requests #997, #1065, #1071.
Some areas of API which were already on the deprecation path, and were raising warnings or errors in 0.13.x have now been escalated to being fully removed.
ASGIDispatch, WSGIDispatch, which have been replaced by ASGITransport, WSGITransport.dispatch=...`` on client, which has been replaced by transport=...``soft_limit, hard_limit, which have been replaced by max_keepalive and max_connections.Response.stream and Response.raw, which have been replaced by ``.aiter_bytes and .aiter_raw.proxies=<transport instance> in favor of proxies=httpx.Proxy(...).See pull requests #1057, #1058.
httpx.HTTPStatusError for .raise_for_status() exceptions. (Pull #1072)httpx.create_ssl_context() helper function. (Pull #996)proxies={"https://www.example.com": None}. (Pull #1099)QueryParams(None) and client.params = None. (Pull #1060)httpx.codes consistently in favour of httpx.StatusCodes which is placed into deprecation. (Pull #1088)httpx.Timeout() should now always include an explicit default. Eg. httpx.Timeout(None, pool=5.0). (Pull #1085)httpx.Timeout() keyword arguments. Eg. read=5.0, instead of read_timeout=5.0. (Pull #1111)httpx.Limits() instead of httpx.PoolLimits(), and limits=... instead of pool_limits=.... (Pull #1113)Client(proxies={...}) should now be in the style of {"http://": ...}, rather than {"http": ...}. (Pull #1127)Headers.getlist and QueryParams.getlist are deprecated in favour of more consistent .get_list() variants. (Pull #1089)URL.port becomes Optional[int]. Now only returns a port if one is explicitly included in the URL string. (Pull #1080)URL(..., allow_relative=[bool]) parameter no longer exists. All URL instances may be relative. (Pull #1073)url.full_path = ... property setter. (Pull #1069)URL.join(relative_url=...) method is now URL.join(url=...). (Pull #1129)URL.is_ssl property is deprecated in favour of URL.scheme == "https". (Pull #1128)Response.next() method. (Pull #1055)Response.iter_lines(). (Pull #1033, #1075).netrc files. (Pull #1104)HTTP_PROXY etc... environment variables. (Pull #1120)app=... or transport=... bypasses any environment based proxy defaults. (Pull #1122).base_url when a path component is included in the base URL. (Pull #1130)http2 option to httpx.Client. (Pull #982)httpx.URLLib3ProxyTransport in top-level API. (Pull #979)This release switches to httpcore for all the internal networking, which means:
urllib3 dependency for our sync client, although there is still an optional URLLib3Transport class.It also means we've had to remove our UDS support, since maintaining that would have meant having to push back our work towards a 1.0 release, which isn't a trade-off we wanted to make.
We also now have a public "Transport API", which you can use to implement custom transport implementations against. This formalises and replaces our previously private "Dispatch API".
httpcore for underlying HTTP transport. Drop urllib3 requirement. (Pull #804, #967)soft_limit/hard_limit to max_keepalive/max_connections. (Pull #968)transport=.... The ASGIDispatch and WSGIDispatch class naming is deprecated in favour of ASGITransport and WSGITransport. (Pull #963)URLLib3Transport class for optional urllib3 transport support. (Pull #804, #963)Response.stream and Response.raw. (Pull #908)files=.... (Pull #976)Client(uds=...) (Pull #804)The 0.13.0.dev2 is a pre-release version. To install it, use pip install httpx --pre.
app=<ASGI app> observe neater disconnect behaviour instead of sending empty body messages. (Pull #919)The 0.13.0.dev1 is a pre-release version. To install it, use pip install httpx --pre.
http2 flag to proxy dispatchers. (Pull #934)httpcore v0.8.3
which addresses problems in handling of headers when using proxies.The 0.13.0.dev0 is a pre-release version. To install it, use pip install httpx --pre.
This release switches to httpcore for all the internal networking, which means:
urllib3 dependency for our sync client, although there is still an optional URLLib3Dispatcher class.It also means we've had to remove our UDS support, since maintaining that would have meant having to push back our work towards a 1.0 release, which isn't a trade-off we wanted to make.
httpcore for underlying HTTP transport. Drop urllib3 requirement. (Pull #804)URLLib3Dispatcher class for optional urllib3 transport support. (Pull #804)Response.stream and Response.raw. (Pull #908)Client(uds=...) (Pull #804)The 0.12 release tightens up the API expectations for httpx by switching to private module names to enforce better clarity around public API.
All imports of httpx should import from the top-level package only, such as from httpx import Request, rather than importing from privately namespaced modules such as from httpx._models import Request.
.requires_response_body. (Pull #803)NetworkError exception. (Pull #814)NO_PROXY environment variable. (Pull #835)RedirectLoop exception, instead using TooManyRedirects. (Pull #819)backend=... parameter on AsyncClient, in favour of always autodetecting trio/asyncio. (Pull #791)httpx.Proxy(url, mode="FORWARD_ONLY") configuration. (Pull #788)cert parameters even if verify=False. (Pull #796)data=.... (Pull #811)proxies=... on Client(). (Pull #763)zlib and deflate style encodings on Content-Encoding: deflate. (Pull #758)allow_redirects=False. (Pull #766)The 0.11 release reintroduces our sync support, so that httpx now supports both a standard thread-concurrency API, and an async API.
Existing async httpx users that are upgrading to 0.11 should ensure that:
httpx.AsyncClient(), instead of httpx.Client().httpx.Proxy() class, instead of the previous httpx.HTTPProxy(). This new configuration class works for configuring both sync and async clients.We believe the API is now pretty much stable, and are aiming for a 1.0 release sometime on or before April 2020.
httpx.get(url, ...), httpx.post(url, ...), httpx.request(method, url, ...) becomes synchronous.httpx.Client() for synchronous clients, with httpx.AsyncClient being used for async clients.proxies=httpx.Proxy(...) for proxy configuration.httpx.NetworkError, rather than exposing lower-level exception types directly.request.url.origin property and httpx.Origin class are no longer available.cert, verify, and trust_env arguments are escalated from raising errors if used, to no longer being available. These arguments should be used on a per-client instance instead, or in the top-level API.stream argument has escalated from raising an error when used, to no longer being available. Use the client.stream(...) or httpx.stream() streaming API instead.(method, url) rather than url. (Pull #734)The 0.10.0 release makes some changes that will allow us to support both sync and async interfaces.
In particular with streaming responses the response.read() method becomes response.aread(), and the response.close() method becomes response.aclose().
If following redirects explicitly the response.next() method becomes response.anext().
Response.request: switch from Optional[Request] to Request. (Pull #666)Response.elapsed now reflects the entire download time. (Pull #687, #692)AsyncClient as a synonym for Client. (Pull #680)response.aread() for conditionally reading streaming responses. (Pull #674)response.aclose() and client.aclose() for explicit closing. (Pull #674, #675)response.anext() for resolving the next redirect response. (Pull #676)verify, cert, and trust_env have now escalated from raising a warning to raising an error. You should set these arguments on the client instead. (Pull #617)request.read(), since end users should not require it.:80 port is included in URL. (Pull #649)params=... argument. (Pull #653)Content-Type header to take precedence over the encoding default. (Pull #633)The 0.9 releases brings some major new features, including:
We've also removed all private types from the top-level package export.
In order to ensure you are only ever working with public API you should make
sure to only import the top-level package eg. import httpx, rather than
importing modules within the package.
Client(backend='trio') and Client(backend='asyncio') API. (Pull #585)response.stream_lines() API. (Pull #575)response.is_error API. (Pull #574)timeout=Timeout(5.0, connect_timeout=60.0) styles. (Pull #593)timeout=None now correctly always disable timeouts. (Pull #592).netrc authentication info. (Commit 095b691)httpx.stream() API. Using stream=True now results in a warning. (Pull #600, #610)Client(http2=True) API from Client(http_versions=["HTTP/1.1", "HTTP/2"]). (Pull #586)verify, cert, and trust_env now raise warnings if used per-request when using a Client instance. They should always be set on the Client instance itself. (Pull #597)proxy_mode argument. The HTTPProxyMode enum still exists, but its usage will raise warnings. (#610)httpx.Timeout(...), not httpx.TimeoutConfig(...). The old version currently remains as a synonym for backwards compatability. (Pull #591)proxies parameter from the high-level API. (Pull #485)str file contents. (Pull #482)getproxies for all proxy environment variables. (Pull #470)asyncio stream to close when closing a connection. (Pull #494)params. (Pull #386)ASGIDispatch, WSGIDispatch are now available in the httpx.dispatch namespace. (Pull #407)HTTPError is now available in the httpx namespace. (Pull #421)start_tls() to the Trio concurrency backend. (Pull #467)Host header when basic authentication
credentials are supplied via the URL. (Pull #417).delete() function no longer has json, data, or files parameters
to match the expected semantics of the DELETE method. (Pull #408)trio extra. Trio support is detected automatically. (Pull #390)params parameter to Client for setting default query parameters. (Pull #372)SSL_CERT_FILE and SSL_CERT_DIR environment variables. (Pull #307)Client without timeouts in Python 3.6. (Pull #383)Client configuration to HTTP proxies. (Pull #377).build_request() method to Client and AsyncClient. (Pull #319).elapsed property on responses. (Pull #351)SSLKEYLOGFILE in Python 3.8b4+. (Pull #301)Host header when redirecting cross-origin. (Pull #321)Content-Length headers on GET redirects. (Pull #310)KeyError if header isn't found in Headers. (Pull #324)NotRedirectResponse in response.next() if there is no redirection to perform. (Pull #297)httpx.AsyncioBackend for the synchronous client. (Pull #232)httpx.ConnectionPool will properly release a dropped connection. (Pull #230)raise_app_exceptions argument from Client. (Pull #238)DecodeError will no longer be raised for an empty body encoded with Brotli. (Pull #237)http_versions parameter to Client. (Pull #250)httpx.get(). (Pull #284)Client.cookies and Client.headers when set as a property. (Pull #274)HTTPX_DEBUG=1 enables debug logging on all requests. (Pull #277)trust_env property to BaseClient. (Pull #187)links property to BaseResponse. (Pull #211)ssl.SSLContext instances into SSLConfig(verify=...). (Pull #215)Response.stream_text() with incremental encoding detection. (Pull #183)Host header when a redirect changes the origin. (Pull #199)Content-Encoding headers. (Pull #196)~/.netrc and ~/_netrc files by default when trust_env=True. (Pull #189)HTTPError with request and response properties. (Pull #162)BaseClient to upgrade HTTP URLs to HTTPS. (Pull #184)headers proeprty to BaseClient. (Pull #159)brotli library. (Pull #156)SSLConfig. (Pull #155)URL.join(...) to work similarly to RFC 3986 URL joining. (Pull #144)ConnectionPool.keepalive_connections (Pull #145)URL objects (Pull #139)commonName for hostname checking for OpenSSL 1.1.0+ (Pull #118)Response.json() (Pull #116)USER_AGENT (Pull #110)Connection: keep-alive by default to HTTP/1.1 connections. (Pull #110)Host header by default. (Pull #109)DEFAULT_CIPHERS for the SSLConfig object. (Pull #100)base_url on the Client.local_flow_control_window for HTTP/2 connections (Pull #98)FAQs
The next generation HTTP client for Web3.
We found that web3http demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Campaign-level threat intelligence in Socket now shows when active supply chain attacks affect your repositories and packages.

Research
Malicious PyPI package sympy-dev targets SymPy users, a Python symbolic math library with 85 million monthly downloads.

Security News
Node.js 25.4.0 makes require(esm) stable, formalizing CommonJS and ESM compatibility across supported Node versions.