<li>An instance of subclasses of <code>httpx.Auth</code>.</li>
</ul>
<p>The most involved of these is the last, which allows you to create authentication flows involving one or more requests. A subclass of <code>httpx.Auth</code> should implement <code>def auth_flow(request)</code>, and yield any requests that need to be made...</p>
-<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
- <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">class</span><span class="w"> </span><span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">token</span> <span class="o">=</span> <span class="n">token</span>
- <span class="k">def</span> <span class="nf">auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="c1"># Send the request, with a custom `X-Authentication` header.</span>
<span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s1">'X-Authentication'</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">token</span>
<span class="k">yield</span> <span class="n">request</span>
</code></pre></div>
<p>If the auth flow requires more than one request, you can issue multiple yields, and obtain the response in each case...</p>
-<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
- <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">class</span><span class="w"> </span><span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">token</span> <span class="o">=</span> <span class="n">token</span>
- <span class="k">def</span> <span class="nf">auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="n">response</span> <span class="o">=</span> <span class="k">yield</span> <span class="n">request</span>
<span class="k">if</span> <span class="n">response</span><span class="o">.</span><span class="n">status_code</span> <span class="o">==</span> <span class="mi">401</span><span class="p">:</span>
<span class="c1"># If the server issues a 401 response then resend the request,</span>
<p>Custom authentication classes are designed to not perform any I/O, so that they may be used with both sync and async client instances. If you are implementing an authentication scheme that requires the request body, then you need to indicate this on the class using a <code>requires_request_body</code> property.</p>
<p>You will then be able to access <code>request.content</code> inside the <code>.auth_flow()</code> method.</p>
-<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">class</span><span class="w"> </span><span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
<span class="n">requires_request_body</span> <span class="o">=</span> <span class="kc">True</span>
- <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">token</span> <span class="o">=</span> <span class="n">token</span>
- <span class="k">def</span> <span class="nf">auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="n">response</span> <span class="o">=</span> <span class="k">yield</span> <span class="n">request</span>
<span class="k">if</span> <span class="n">response</span><span class="o">.</span><span class="n">status_code</span> <span class="o">==</span> <span class="mi">401</span><span class="p">:</span>
<span class="c1"># If the server issues a 401 response then resend the request,</span>
<span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s1">'X-Authentication'</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">sign_request</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="k">yield</span> <span class="n">request</span>
- <span class="k">def</span> <span class="nf">sign_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">sign_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="c1"># Create a request signature, based on `request.method`, `request.url`,</span>
<span class="c1"># `request.headers`, and `request.content`.</span>
<span class="o">...</span>
</code></pre></div>
<p>Similarly, if you are implementing a scheme that requires access to the response body, then use the <code>requires_response_body</code> property. You will then be able to access response body properties and methods such as <code>response.content</code>, <code>response.text</code>, <code>response.json()</code>, etc.</p>
-<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">class</span><span class="w"> </span><span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
<span class="n">requires_response_body</span> <span class="o">=</span> <span class="kc">True</span>
- <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">access_token</span><span class="p">,</span> <span class="n">refresh_token</span><span class="p">,</span> <span class="n">refresh_url</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">access_token</span><span class="p">,</span> <span class="n">refresh_token</span><span class="p">,</span> <span class="n">refresh_url</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">access_token</span> <span class="o">=</span> <span class="n">access_token</span>
<span class="bp">self</span><span class="o">.</span><span class="n">refresh_token</span> <span class="o">=</span> <span class="n">refresh_token</span>
<span class="bp">self</span><span class="o">.</span><span class="n">refresh_url</span> <span class="o">=</span> <span class="n">refresh_url</span>
- <span class="k">def</span> <span class="nf">auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s2">"X-Authentication"</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">access_token</span>
<span class="n">response</span> <span class="o">=</span> <span class="k">yield</span> <span class="n">request</span>
<span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s2">"X-Authentication"</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">access_token</span>
<span class="k">yield</span> <span class="n">request</span>
- <span class="k">def</span> <span class="nf">build_refresh_request</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">build_refresh_request</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="c1"># Return an `httpx.Request` for refreshing tokens.</span>
<span class="o">...</span>
- <span class="k">def</span> <span class="nf">update_tokens</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">response</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">update_tokens</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">response</span><span class="p">):</span>
<span class="c1"># Update the `.access_token` and `.refresh_token` tokens</span>
<span class="c1"># based on a refresh response.</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">json</span><span class="p">()</span>
</code></pre></div>
<p>If you <em>do</em> need to perform I/O other than HTTP requests, such as accessing a disk-based cache, or you need to use concurrency primitives, such as locks, then you should override <code>.sync_auth_flow()</code> and <code>.async_auth_flow()</code> (instead of <code>.auth_flow()</code>). The former will be used by <code>httpx.Client</code>, while the latter will be used by <code>httpx.AsyncClient</code>.</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">asyncio</span>
-<span class="kn">import</span> <span class="nn">threading</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">threading</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
-<span class="k">class</span> <span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
- <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+<span class="k">class</span><span class="w"> </span><span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_sync_lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">RLock</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_async_lock</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
- <span class="k">def</span> <span class="nf">sync_get_token</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">sync_get_token</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">_sync_lock</span><span class="p">:</span>
<span class="o">...</span>
- <span class="k">def</span> <span class="nf">sync_auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">sync_auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="n">token</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">sync_get_token</span><span class="p">()</span>
<span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s2">"Authorization"</span><span class="p">]</span> <span class="o">=</span> <span class="sa">f</span><span class="s2">"Token </span><span class="si">{</span><span class="n">token</span><span class="si">}</span><span class="s2">"</span>
<span class="k">yield</span> <span class="n">request</span>
- <span class="k">async</span> <span class="k">def</span> <span class="nf">async_get_token</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">async_get_token</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">async</span> <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">_async_lock</span><span class="p">:</span>
<span class="o">...</span>
- <span class="k">async</span> <span class="k">def</span> <span class="nf">async_auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">async_auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="n">token</span> <span class="o">=</span> <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">async_get_token</span><span class="p">()</span>
<span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s2">"Authorization"</span><span class="p">]</span> <span class="o">=</span> <span class="sa">f</span><span class="s2">"Token </span><span class="si">{</span><span class="n">token</span><span class="si">}</span><span class="s2">"</span>
<span class="k">yield</span> <span class="n">request</span>
</code></pre></div>
<p>If you only want to support one of the two methods, then you should still override it, but raise an explicit <code>RuntimeError</code>.</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">import</span> <span class="nn">sync_only_library</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">sync_only_library</span>
-<span class="k">class</span> <span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
- <span class="k">def</span> <span class="nf">sync_auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+<span class="k">class</span><span class="w"> </span><span class="nc">MyCustomAuth</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">Auth</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">sync_auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="n">token</span> <span class="o">=</span> <span class="n">sync_only_library</span><span class="o">.</span><span class="n">get_token</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s2">"Authorization"</span><span class="p">]</span> <span class="o">=</span> <span class="sa">f</span><span class="s2">"Token </span><span class="si">{</span><span class="n">token</span><span class="si">}</span><span class="s2">"</span>
<span class="k">yield</span> <span class="n">request</span>
- <span class="k">async</span> <span class="k">def</span> <span class="nf">async_auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">async_auth_flow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">"Cannot use a sync authentication class with httpx.AsyncClient"</span><span class="p">)</span>
</code></pre></div>
<span class="gp">... </span> <span class="n">r</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'https://example.com'</span><span class="p">,</span> <span class="n">auth</span><span class="o">=</span><span class="p">(</span><span class="s1">'alice'</span><span class="p">,</span> <span class="s1">'ecila123'</span><span class="p">))</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">_</span><span class="p">,</span> <span class="n">_</span><span class="p">,</span> <span class="n">auth</span> <span class="o">=</span> <span class="n">r</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s1">'Authorization'</span><span class="p">]</span><span class="o">.</span><span class="n">partition</span><span class="p">(</span><span class="s1">' '</span><span class="p">)</span>
-<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">base64</span>
+<span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">base64</span>
<span class="gp">>>> </span><span class="n">base64</span><span class="o">.</span><span class="n">b64decode</span><span class="p">(</span><span class="n">auth</span><span class="p">)</span>
<span class="go">b'alice:ecila123'</span>
</code></pre></div>
<p>If you need to monitor download progress of large responses, you can use response streaming and inspect the <code>response.num_bytes_downloaded</code> property.</p>
<p>This interface is required for properly determining download progress, because the total number of bytes returned by <code>response.content</code> or <code>response.iter_content()</code> will not always correspond with the raw content length of the response if HTTP response compression is being used.</p>
<p>For example, showing a progress bar using the <a href="https://github.com/tqdm/tqdm"><code>tqdm</code></a> library while a response is being downloaded could be done like this…</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">tempfile</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">tempfile</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">from</span> <span class="nn">tqdm</span> <span class="kn">import</span> <span class="n">tqdm</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">from</span><span class="w"> </span><span class="nn">tqdm</span><span class="w"> </span><span class="kn">import</span> <span class="n">tqdm</span>
<span class="k">with</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">NamedTemporaryFile</span><span class="p">()</span> <span class="k">as</span> <span class="n">download_file</span><span class="p">:</span>
<span class="n">url</span> <span class="o">=</span> <span class="s2">"https://speed.hetzner.de/100MB.bin"</span>
<p><img alt="tqdm progress bar" src="../../img/tqdm-progress.gif" /></p>
<p>Or an alternate example, this time using the <a href="https://github.com/willmcgugan/rich"><code>rich</code></a> library…</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">tempfile</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">import</span> <span class="nn">rich.progress</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">tempfile</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">rich.progress</span>
<span class="k">with</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">NamedTemporaryFile</span><span class="p">()</span> <span class="k">as</span> <span class="n">download_file</span><span class="p">:</span>
<span class="n">url</span> <span class="o">=</span> <span class="s2">"https://speed.hetzner.de/100MB.bin"</span>
<h2 id="monitoring-upload-progress">Monitoring upload progress</h2>
<p>If you need to monitor upload progress of large responses, you can use request content generator streaming.</p>
<p>For example, showing a progress bar using the <a href="https://github.com/tqdm/tqdm"><code>tqdm</code></a> library.</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">io</span>
-<span class="kn">import</span> <span class="nn">random</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">io</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">random</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">from</span> <span class="nn">tqdm</span> <span class="kn">import</span> <span class="n">tqdm</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">from</span><span class="w"> </span><span class="nn">tqdm</span><span class="w"> </span><span class="kn">import</span> <span class="n">tqdm</span>
-<span class="k">def</span> <span class="nf">gen</span><span class="p">():</span>
+<span class="k">def</span><span class="w"> </span><span class="nf">gen</span><span class="p">():</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> this is a complete example with generated random bytes.</span>
<span class="sd"> you can replace `io.BytesIO` with real file object.</span>
<p>As mentioned in the <a href="../../quickstart/#sending-multipart-file-uploads">quickstart</a>
multipart file encoding is available by passing a dictionary with the
name of the payloads as keys and either tuple of elements or a file-like object or a string as values.</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'upload-file'</span><span class="p">:</span> <span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">),</span> <span class="s1">'application/vnd.ms-excel'</span><span class="p">)}</span>
-<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">report_file</span><span class="p">:</span>
+<span class="gp">... </span> <span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'upload-file'</span><span class="p">:</span> <span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="n">report_file</span><span class="p">,</span> <span class="s1">'application/vnd.ms-excel'</span><span class="p">)}</span>
+<span class="gp">... </span> <span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">r</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
<span class="go">{</span>
<span class="go"> ...</span>
<p>You can also send multiple files in one go with a multiple file field form.
To do that, pass a list of <code>(field, <file>)</code> items instead of a dictionary, allowing you to pass multiple items with the same <code>field</code>.
For instance this request sends 2 files, <code>foo.png</code> and <code>bar.png</code> in one request on the <code>images</code> form field:</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="n">files</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">'images'</span><span class="p">,</span> <span class="p">(</span><span class="s1">'foo.png'</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'foo.png'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">),</span> <span class="s1">'image/png'</span><span class="p">)),</span>
-<span class="go"> ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]</span>
-<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'foo.png'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">foo_file</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'bar.png'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">bar_file</span><span class="p">:</span>
+<span class="gp">... </span> <span class="n">files</span> <span class="o">=</span> <span class="p">[</span>
+<span class="gp">... </span> <span class="p">(</span><span class="s1">'images'</span><span class="p">,</span> <span class="p">(</span><span class="s1">'foo.png'</span><span class="p">,</span> <span class="n">foo_file</span><span class="p">,</span> <span class="s1">'image/png'</span><span class="p">)),</span>
+<span class="gp">... </span> <span class="p">(</span><span class="s1">'images'</span><span class="p">,</span> <span class="p">(</span><span class="s1">'bar.png'</span><span class="p">,</span> <span class="n">bar_file</span><span class="p">,</span> <span class="s1">'image/png'</span><span class="p">)),</span>
+<span class="gp">... </span> <span class="p">]</span>
+<span class="gp">... </span> <span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
</code></pre></div>
<li><code>response</code> - Called after the response has been fetched from the network, but before it is returned to the caller. Passed the <code>response</code> instance.</li>
</ul>
<p>These allow you to install client-wide functionality such as logging, monitoring or tracing.</p>
-<div class="highlight"><pre><span></span><code><span class="k">def</span> <span class="nf">log_request</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">def</span><span class="w"> </span><span class="nf">log_request</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"Request event hook: </span><span class="si">{</span><span class="n">request</span><span class="o">.</span><span class="n">method</span><span class="si">}</span><span class="s2"> </span><span class="si">{</span><span class="n">request</span><span class="o">.</span><span class="n">url</span><span class="si">}</span><span class="s2"> - Waiting for response"</span><span class="p">)</span>
-<span class="k">def</span> <span class="nf">log_response</span><span class="p">(</span><span class="n">response</span><span class="p">):</span>
+<span class="k">def</span><span class="w"> </span><span class="nf">log_response</span><span class="p">(</span><span class="n">response</span><span class="p">):</span>
<span class="n">request</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">request</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"Response event hook: </span><span class="si">{</span><span class="n">request</span><span class="o">.</span><span class="n">method</span><span class="si">}</span><span class="s2"> </span><span class="si">{</span><span class="n">request</span><span class="o">.</span><span class="n">url</span><span class="si">}</span><span class="s2"> - Status </span><span class="si">{</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<p>You can also use these hooks to install response processing code, such as this
example, which creates a client instance that always raises <code>httpx.HTTPStatusError</code>
on 4xx and 5xx responses.</p>
-<div class="highlight"><pre><span></span><code><span class="k">def</span> <span class="nf">raise_on_4xx_5xx</span><span class="p">(</span><span class="n">response</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">def</span><span class="w"> </span><span class="nf">raise_on_4xx_5xx</span><span class="p">(</span><span class="n">response</span><span class="p">):</span>
<span class="n">response</span><span class="o">.</span><span class="n">raise_for_status</span><span class="p">()</span>
<span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Client</span><span class="p">(</span><span class="n">event_hooks</span><span class="o">=</span><span class="p">{</span><span class="s1">'response'</span><span class="p">:</span> <span class="p">[</span><span class="n">raise_on_4xx_5xx</span><span class="p">]})</span>
need to call <code>response.read()</code>, or for AsyncClients, <code>response.aread()</code>.</p>
</div>
<p>The hooks are also allowed to modify <code>request</code> and <code>response</code> objects.</p>
-<div class="highlight"><pre><span></span><code><span class="k">def</span> <span class="nf">add_timestamp</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">def</span><span class="w"> </span><span class="nf">add_timestamp</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="n">request</span><span class="o">.</span><span class="n">headers</span><span class="p">[</span><span class="s1">'x-request-timestamp'</span><span class="p">]</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">(</span><span class="n">tz</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">utc</span><span class="p">)</span><span class="o">.</span><span class="n">isoformat</span><span class="p">()</span>
<span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Client</span><span class="p">(</span><span class="n">event_hooks</span><span class="o">=</span><span class="p">{</span><span class="s1">'request'</span><span class="p">:</span> <span class="p">[</span><span class="n">add_timestamp</span><span class="p">]})</span>
<p>The trace extension allows a callback handler to be installed to monitor the internal
flow of events within the underlying <code>httpcore</code> transport.</p>
<p>The simplest way to explain this is with an example:</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
-<span class="k">def</span> <span class="nf">log</span><span class="p">(</span><span class="n">event_name</span><span class="p">,</span> <span class="n">info</span><span class="p">):</span>
+<span class="k">def</span><span class="w"> </span><span class="nf">log</span><span class="p">(</span><span class="n">event_name</span><span class="p">,</span> <span class="n">info</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="n">event_name</span><span class="p">,</span> <span class="n">info</span><span class="p">)</span>
<span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Client</span><span class="p">()</span>
<p>If you're using a <code>Client()</code> instance you should pass any <code>verify=<...></code> configuration when instantiating the client.</p>
<p>By default the <a href="https://certifiio.readthedocs.io/en/latest/">certifi CA bundle</a> is used for SSL verification.</p>
<p>For more complex configurations you can pass an <a href="https://docs.python.org/3/library/ssl.html">SSL Context</a> instance...</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">certifi</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">import</span> <span class="nn">ssl</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">certifi</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">ssl</span>
<span class="c1"># This SSL context is equivelent to the default `verify=True`.</span>
<span class="n">ctx</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">create_default_context</span><span class="p">(</span><span class="n">cafile</span><span class="o">=</span><span class="n">certifi</span><span class="o">.</span><span class="n">where</span><span class="p">())</span>
</code></pre></div>
<p>Using <a href="https://truststore.readthedocs.io/">the <code>truststore</code> package</a> to support system certificate stores...</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">ssl</span>
-<span class="kn">import</span> <span class="nn">truststore</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">ssl</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">truststore</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="c1"># Use system certificate stores.</span>
<span class="n">ctx</span> <span class="o">=</span> <span class="n">truststore</span><span class="o">.</span><span class="n">SSLContext</span><span class="p">(</span><span class="n">ssl</span><span class="o">.</span><span class="n">PROTOCOL_TLS_CLIENT</span><span class="p">)</span>
</code></pre></div>
<p>Loding an alternative certificate verification store using <a href="https://docs.python.org/3/library/ssl.html">the standard SSL context API</a>...</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">import</span> <span class="nn">ssl</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">ssl</span>
<span class="c1"># Use an explicitly configured certificate store.</span>
<span class="n">ctx</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">create_default_context</span><span class="p">(</span><span class="n">cafile</span><span class="o">=</span><span class="s2">"path/to/certs.pem"</span><span class="p">)</span> <span class="c1"># Either cafile or capath.</span>
</code></pre></div>
<h3 id="working-with-ssl_cert_file-and-ssl_cert_dir">Working with <code>SSL_CERT_FILE</code> and <code>SSL_CERT_DIR</code></h3>
-<p>Unlike <code>requests</code>, the <code>httpx</code> package does not automatically pull in <a href="https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_default_verify_paths.html">the environment variables <code>SSL_CERT_FILE</code> or <code>SSL_CERT_DIR</code></a>. If you want to use these they need to be enabled explicitly.</p>
-<p>For example...</p>
-<div class="highlight"><pre><span></span><code><span class="c1"># Use `SSL_CERT_FILE` or `SSL_CERT_DIR` if configured.</span>
-<span class="c1"># Otherwise default to certifi.</span>
-<span class="n">ctx</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">create_default_context</span><span class="p">(</span>
- <span class="n">cafile</span><span class="o">=</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">"SSL_CERT_FILE"</span><span class="p">,</span> <span class="n">certifi</span><span class="o">.</span><span class="n">where</span><span class="p">()),</span>
- <span class="n">capath</span><span class="o">=</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">"SSL_CERT_DIR"</span><span class="p">),</span>
-<span class="p">)</span>
-<span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Client</span><span class="p">(</span><span class="n">verify</span><span class="o">=</span><span class="n">ctx</span><span class="p">)</span>
-</code></pre></div>
-
+<p><code>httpx</code> does respect the <code>SSL_CERT_FILE</code> and <code>SSL_CERT_DIR</code> environment variables by default. For details, refer to <a href="../../environment_variables/#ssl_cert_file">the section on the environment variables page</a>.</p>
<h3 id="making-https-requests-to-a-local-server">Making HTTPS requests to a local server</h3>
<p>When making requests to local servers, such as a development server running on <code>localhost</code>, you will typically be using unencrypted HTTP connections.</p>
<p>If you do need to make HTTPS connections to a local server, for example to test an HTTPS-only service, you will need to create and use your own certificates. Here's one way to do it...</p>
<p>In cases where no charset information is included on the response, the default behaviour is to assume "utf-8" encoding, which is by far the most widely used text encoding on the internet.</p>
<h2 id="using-the-default-encoding">Using the default encoding</h2>
<p>To understand this better let's start by looking at the default behaviour for text decoding...</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="c1"># Instantiate a client with the default configuration.</span>
<span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Client</span><span class="p">()</span>
<span class="c1"># Using the client...</span>
<p>This is normally absolutely fine. Most servers will respond with a properly formatted Content-Type header, including a charset encoding. And in most cases where no charset encoding is included, UTF-8 is very likely to be used, since it is so widely adopted.</p>
<h2 id="using-an-explicit-encoding">Using an explicit encoding</h2>
<p>In some cases we might be making requests to a site where no character set information is being set explicitly by the server, but we know what the encoding is. In this case it's best to set the default encoding explicitly on the client.</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="c1"># Instantiate a client with a Japanese character set as the default encoding.</span>
<span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Client</span><span class="p">(</span><span class="n">default_encoding</span><span class="o">=</span><span class="s2">"shift-jis"</span><span class="p">)</span>
<span class="c1"># Using the client...</span>
</code></pre></div>
<p>Once <code>chardet</code> is installed, we can configure a client to use character-set autodetection.</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">import</span> <span class="nn">chardet</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">chardet</span>
-<span class="k">def</span> <span class="nf">autodetect</span><span class="p">(</span><span class="n">content</span><span class="p">):</span>
+<span class="k">def</span><span class="w"> </span><span class="nf">autodetect</span><span class="p">(</span><span class="n">content</span><span class="p">):</span>
<span class="k">return</span> <span class="n">chardet</span><span class="o">.</span><span class="n">detect</span><span class="p">(</span><span class="n">content</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">"encoding"</span><span class="p">)</span>
<span class="c1"># Using a client with character-set autodetection enabled.</span>
<p>For some advanced configuration you might need to instantiate a transport
class directly, and pass it to the client instance. One example is the
<code>local_address</code> configuration which is only available via this low-level API.</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="gp">>>> </span><span class="n">transport</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">HTTPTransport</span><span class="p">(</span><span class="n">local_address</span><span class="o">=</span><span class="s2">"0.0.0.0"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Client</span><span class="p">(</span><span class="n">transport</span><span class="o">=</span><span class="n">transport</span><span class="p">)</span>
</code></pre></div>
<p>Connection retries are also available via this interface. Requests will be retried the given number of times in case an <code>httpx.ConnectError</code> or an <code>httpx.ConnectTimeout</code> occurs, allowing smoother operation under flaky networks. If you need other forms of retry behaviors, such as handling read/write errors or reacting to <code>503 Service Unavailable</code>, consider general-purpose tools such as <a href="https://github.com/jd/tenacity">tenacity</a>.</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="gp">>>> </span><span class="n">transport</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">HTTPTransport</span><span class="p">(</span><span class="n">retries</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Client</span><span class="p">(</span><span class="n">transport</span><span class="o">=</span><span class="n">transport</span><span class="p">)</span>
</code></pre></div>
<p>Similarly, instantiating a transport directly provides a <code>uds</code> option for
connecting via a Unix Domain Socket that is only available via this low-level API:</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="gp">>>> </span><span class="c1"># Connect to the Docker API via a Unix Socket.</span>
<span class="gp">>>> </span><span class="n">transport</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">HTTPTransport</span><span class="p">(</span><span class="n">uds</span><span class="o">=</span><span class="s2">"/var/run/docker.sock"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Client</span><span class="p">(</span><span class="n">transport</span><span class="o">=</span><span class="n">transport</span><span class="p">)</span>
</ul>
<h3 id="example">Example</h3>
<p>Here's an example of integrating against a Flask application:</p>
-<div class="highlight"><pre><span></span><code><span class="kn">from</span> <span class="nn">flask</span> <span class="kn">import</span> <span class="n">Flask</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">from</span><span class="w"> </span><span class="nn">flask</span><span class="w"> </span><span class="kn">import</span> <span class="n">Flask</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="n">app</span> <span class="o">=</span> <span class="n">Flask</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>
<span class="nd">@app</span><span class="o">.</span><span class="n">route</span><span class="p">(</span><span class="s2">"/"</span><span class="p">)</span>
-<span class="k">def</span> <span class="nf">hello</span><span class="p">():</span>
+<span class="k">def</span><span class="w"> </span><span class="nf">hello</span><span class="p">():</span>
<span class="k">return</span> <span class="s2">"Hello World!"</span>
<span class="n">transport</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">WSGITransport</span><span class="p">(</span><span class="n">app</span><span class="o">=</span><span class="n">app</span><span class="p">)</span>
</ul>
<h3 id="example_1">Example</h3>
<p>Let's take this Starlette application as an example:</p>
-<div class="highlight"><pre><span></span><code><span class="kn">from</span> <span class="nn">starlette.applications</span> <span class="kn">import</span> <span class="n">Starlette</span>
-<span class="kn">from</span> <span class="nn">starlette.responses</span> <span class="kn">import</span> <span class="n">HTMLResponse</span>
-<span class="kn">from</span> <span class="nn">starlette.routing</span> <span class="kn">import</span> <span class="n">Route</span>
+<div class="highlight"><pre><span></span><code><span class="kn">from</span><span class="w"> </span><span class="nn">starlette.applications</span><span class="w"> </span><span class="kn">import</span> <span class="n">Starlette</span>
+<span class="kn">from</span><span class="w"> </span><span class="nn">starlette.responses</span><span class="w"> </span><span class="kn">import</span> <span class="n">HTMLResponse</span>
+<span class="kn">from</span><span class="w"> </span><span class="nn">starlette.routing</span><span class="w"> </span><span class="kn">import</span> <span class="n">Route</span>
-<span class="k">async</span> <span class="k">def</span> <span class="nf">hello</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
+<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">hello</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">HTMLResponse</span><span class="p">(</span><span class="s2">"Hello World!"</span><span class="p">)</span>
<p>See the <code>handle_request</code> and <code>handle_async_request</code> docstrings for more details
on the specifics of the Transport API.</p>
<p>A complete example of a custom transport implementation would be:</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">json</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">json</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
-<span class="k">class</span> <span class="nc">HelloWorldTransport</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
+<span class="k">class</span><span class="w"> </span><span class="nc">HelloWorldTransport</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> A mock transport that always returns a JSON "Hello, world!" response.</span>
<span class="sd"> """</span>
- <span class="k">def</span> <span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Response</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="n">json</span><span class="o">=</span><span class="p">{</span><span class="s2">"text"</span><span class="p">:</span> <span class="s2">"Hello, world!"</span><span class="p">})</span>
</code></pre></div>
<p>Or this example, which uses a custom transport and <code>httpx.Mounts</code> to always redirect <code>http://</code> requests.</p>
-<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">HTTPSRedirect</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">class</span><span class="w"> </span><span class="nc">HTTPSRedirect</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> A transport that always redirects to HTTPS.</span>
<span class="sd"> """</span>
- <span class="k">def</span> <span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="n">url</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">url</span><span class="o">.</span><span class="n">copy_with</span><span class="p">(</span><span class="n">scheme</span><span class="o">=</span><span class="s2">"https"</span><span class="p">)</span>
<span class="k">return</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Response</span><span class="p">(</span><span class="mi">303</span><span class="p">,</span> <span class="n">headers</span><span class="o">=</span><span class="p">{</span><span class="s2">"Location"</span><span class="p">:</span> <span class="nb">str</span><span class="p">(</span><span class="n">url</span><span class="p">)})</span>
</code></pre></div>
<p>A useful pattern here is custom transport classes that wrap the default HTTP implementation. For example...</p>
-<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">DebuggingTransport</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
- <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">class</span><span class="w"> </span><span class="nc">DebuggingTransport</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_wrapper</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">HTTPTransport</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
- <span class="k">def</span> <span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">">>> </span><span class="si">{</span><span class="n">request</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_wrapper</span><span class="o">.</span><span class="n">handle_request</span><span class="p">(</span><span class="n">request</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"<<< </span><span class="si">{</span><span class="n">response</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="k">return</span> <span class="n">response</span>
- <span class="k">def</span> <span class="nf">close</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">close</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_wrapper</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">transport</span> <span class="o">=</span> <span class="n">DebuggingTransport</span><span class="p">()</span>
</code></pre></div>
<p>Here's another case, where we're using a round-robin across a number of different proxies...</p>
-<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">ProxyRoundRobin</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
- <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">proxies</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">class</span><span class="w"> </span><span class="nc">ProxyRoundRobin</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">proxies</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_transports</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">httpx</span><span class="o">.</span><span class="n">HTTPTransport</span><span class="p">(</span><span class="n">proxy</span><span class="o">=</span><span class="n">proxy</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="k">for</span> <span class="n">proxy</span> <span class="ow">in</span> <span class="n">proxies</span>
<span class="p">]</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_idx</span> <span class="o">=</span> <span class="mi">0</span>
- <span class="k">def</span> <span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
<span class="n">transport</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_transports</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">_idx</span><span class="p">]</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_idx</span> <span class="o">=</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_idx</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="o">%</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_transports</span><span class="p">)</span>
<span class="k">return</span> <span class="n">transport</span><span class="o">.</span><span class="n">handle_request</span><span class="p">(</span><span class="n">request</span><span class="p">)</span>
- <span class="k">def</span> <span class="nf">close</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">close</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">for</span> <span class="n">transport</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_transports</span><span class="p">:</span>
<span class="n">transport</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
and return pre-determined responses, rather than making actual network requests.</p>
<p>The <code>httpx.MockTransport</code> class accepts a handler function, which can be used
to map requests onto pre-determined responses:</p>
-<div class="highlight"><pre><span></span><code><span class="k">def</span> <span class="nf">handler</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
+<div class="highlight"><pre><span></span><code><span class="k">def</span><span class="w"> </span><span class="nf">handler</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Response</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="n">json</span><span class="o">=</span><span class="p">{</span><span class="s2">"text"</span><span class="p">:</span> <span class="s2">"Hello, world!"</span><span class="p">})</span>
<p>You can also mount transports against given schemes or domains, to control
which transport an outgoing request should be routed via, with <a href="#routing">the same style
used for specifying proxy routing</a>.</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
-<span class="k">class</span> <span class="nc">HTTPSRedirectTransport</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
+<span class="k">class</span><span class="w"> </span><span class="nc">HTTPSRedirectTransport</span><span class="p">(</span><span class="n">httpx</span><span class="o">.</span><span class="n">BaseTransport</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> A transport that always redirects to HTTPS.</span>
<span class="sd"> """</span>
- <span class="k">def</span> <span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">headers</span><span class="p">,</span> <span class="n">stream</span><span class="p">,</span> <span class="n">extensions</span><span class="p">):</span>
+ <span class="k">def</span><span class="w"> </span><span class="nf">handle_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">headers</span><span class="p">,</span> <span class="n">stream</span><span class="p">,</span> <span class="n">extensions</span><span class="p">):</span>
<span class="n">scheme</span><span class="p">,</span> <span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">,</span> <span class="n">path</span> <span class="o">=</span> <span class="n">url</span>
<span class="k">if</span> <span class="n">port</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">location</span> <span class="o">=</span> <span class="sa">b</span><span class="s2">"https://</span><span class="si">%s%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">path</span><span class="p">)</span>
<p>Mocking requests to a given domain:</p>
<div class="highlight"><pre><span></span><code><span class="c1"># All requests to "example.org" should be mocked out.</span>
<span class="c1"># Other requests occur as usual.</span>
-<span class="k">def</span> <span class="nf">handler</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
+<span class="k">def</span><span class="w"> </span><span class="nf">handler</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">httpx</span><span class="o">.</span><span class="n">Response</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="n">json</span><span class="o">=</span><span class="p">{</span><span class="s2">"text"</span><span class="p">:</span> <span class="s2">"Hello, World!"</span><span class="p">})</span>
<span class="n">mounts</span> <span class="o">=</span> <span class="p">{</span><span class="s2">"all://example.org"</span><span class="p">:</span> <span class="n">httpx</span><span class="o">.</span><span class="n">MockTransport</span><span class="p">(</span><span class="n">handler</span><span class="p">)}</span>
</span>
</a>
+</li>
+
+ <li class="md-nav__item">
+ <a href="#proxy" class="md-nav__link">
+ <span class="md-ellipsis">
+ Proxy
+ </span>
+ </a>
+
</li>
</ul>
</span>
</a>
+</li>
+
+ <li class="md-nav__item">
+ <a href="#proxy" class="md-nav__link">
+ <span class="md-ellipsis">
+ Proxy
+ </span>
+ </a>
+
</li>
</ul>
</ul>
<p><strong>Returns:</strong> <code>Response</code></p>
<p>Usage:</p>
-<div class="highlight"><pre><span></span><code><span class="o">>>></span><span class="w"> </span><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
-<span class="o">>>></span><span class="w"> </span><span class="n">response</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">httpx</span><span class="o">.</span><span class="n">request</span><span class="p">(</span><span class="s1">'GET'</span><span class="p">,</span><span class="w"> </span><span class="s1">'https://httpbin.org/get'</span><span class="p">)</span>
-<span class="o">>>></span><span class="w"> </span><span class="n">response</span>
-<span class="o"><</span><span class="n">Response</span><span class="w"> </span><span class="p">[</span><span class="mi">200</span><span class="w"> </span><span class="n">OK</span><span class="p">]</span><span class="o">></span>
+<div class="highlight"><pre><span></span><code><span class="o">>>></span> <span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="o">>>></span> <span class="n">response</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">request</span><span class="p">(</span><span class="s1">'GET'</span><span class="p">,</span> <span class="s1">'https://httpbin.org/get'</span><span class="p">)</span>
+<span class="o">>>></span> <span class="n">response</span>
+<span class="o"><</span><span class="n">Response</span> <span class="p">[</span><span class="mi">200</span> <span class="n">OK</span><span class="p">]</span><span class="o">></span>
</code></pre></div></div>
</div>
<div class="autodoc">
<div class="autodoc-signature"><code><strong>auth</strong></code></div>
<div class="autodoc-docstring"><p>Authentication class used when none is passed at the request-level.</p>
<p>See also <a href="/quickstart/#authentication">Authentication</a>.</p></div>
-<div class="autodoc-signature"><code><strong>request</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>request</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Build and send a request.</p>
<p>Equivalent to:</p>
<div class="highlight"><pre><span></span><code><span class="n">request</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">build_request</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<p>See <code>Client.build_request()</code>, <code>Client.send()</code> and
<a href="/advanced/clients/#merging-of-configuration">Merging of configuration</a> for how the various parameters
are merged with client-level configuration.</p></div>
-<div class="autodoc-signature"><code><strong>get</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>get</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>GET</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><code><strong>head</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>head</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>HEAD</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><code><strong>options</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>options</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send an <code>OPTIONS</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><code><strong>post</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>post</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>POST</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><code><strong>put</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>put</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>PUT</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><code><strong>patch</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>patch</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>PATCH</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><code><strong>delete</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>delete</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>DELETE</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><code><strong>stream</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>stream</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Alternative to <code>httpx.request()</code> that streams the response body
instead of loading it into memory at once.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p>
<p>See also: <a href="/quickstart#streaming-responses">Streaming Responses</a></p></div>
-<div class="autodoc-signature"><code><strong>build_request</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>build_request</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Build and return a request instance.</p>
<ul>
<li>The <code>params</code>, <code>headers</code> and <code>cookies</code> arguments
<li>The <code>url</code> argument is merged with any <code>base_url</code> set on the client.</li>
</ul>
<p>See also: <a href="/advanced/clients/#request-instances">Request instances</a></p></div>
-<div class="autodoc-signature"><code><strong>send</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">request</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">stream=False</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>send</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">request</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">stream=False</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a request.</p>
<p>The request is sent as-is, unmodified.</p>
<p>Typically you'll want to build one with <code>Client.build_request()</code>
<div class="autodoc-signature"><code><strong>auth</strong></code></div>
<div class="autodoc-docstring"><p>Authentication class used when none is passed at the request-level.</p>
<p>See also <a href="/quickstart/#authentication">Authentication</a>.</p></div>
-<div class="autodoc-signature"><em>async </em><code><strong>request</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><em>async </em><code><strong>request</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Build and send a request.</p>
<p>Equivalent to:</p>
<div class="highlight"><pre><span></span><code><span class="n">request</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">build_request</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<p>See <code>AsyncClient.build_request()</code>, <code>AsyncClient.send()</code>
and <a href="/advanced/clients/#merging-of-configuration">Merging of configuration</a> for how the various parameters
are merged with client-level configuration.</p></div>
-<div class="autodoc-signature"><em>async </em><code><strong>get</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><em>async </em><code><strong>get</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>GET</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><em>async </em><code><strong>head</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><em>async </em><code><strong>head</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>HEAD</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><em>async </em><code><strong>options</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><em>async </em><code><strong>options</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send an <code>OPTIONS</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><em>async </em><code><strong>post</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><em>async </em><code><strong>post</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>POST</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><em>async </em><code><strong>put</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><em>async </em><code><strong>put</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>PUT</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><em>async </em><code><strong>patch</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><em>async </em><code><strong>patch</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>PATCH</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><em>async </em><code><strong>delete</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><em>async </em><code><strong>delete</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a <code>DELETE</code> request.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p></div>
-<div class="autodoc-signature"><code><strong>stream</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>stream</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Alternative to <code>httpx.request()</code> that streams the response body
instead of loading it into memory at once.</p>
<p><strong>Parameters</strong>: See <code>httpx.request</code>.</p>
<p>See also: <a href="/quickstart#streaming-responses">Streaming Responses</a></p></div>
-<div class="autodoc-signature"><code><strong>build_request</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><code><strong>build_request</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">method</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">url</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">content=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">data=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">files=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">json=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">params=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">headers=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">cookies=None</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">timeout=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">extensions=None</em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Build and return a request instance.</p>
<ul>
<li>The <code>params</code>, <code>headers</code> and <code>cookies</code> arguments
<li>The <code>url</code> argument is merged with any <code>base_url</code> set on the client.</li>
</ul>
<p>See also: <a href="/advanced/clients/#request-instances">Request instances</a></p></div>
-<div class="autodoc-signature"><em>async </em><code><strong>send</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">request</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">stream=False</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x7fbd8b024e50></em><span class="autodoc-punctuation">)</span></div>
+<div class="autodoc-signature"><em>async </em><code><strong>send</strong></code><span class="autodoc-punctuation">(</span><em class="autodoc-param">self</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">request</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">*</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">stream=False</em><span class="autodoc-punctuation">, </span><em class="autodoc-param">auth=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">, </span><em class="autodoc-param">follow_redirects=<httpx._client.UseClientDefault object at 0x1045fe270></em><span class="autodoc-punctuation">)</span></div>
<div class="autodoc-docstring"><p>Send a request.</p>
<p>The request is sent as-is, unmodified.</p>
<p>Typically you'll want to build one with <code>AsyncClient.build_request()</code>
<li><code>def clear([domain], [path])</code></li>
<li><em>Standard mutable mapping interface</em></li>
</ul>
+<h2 id="proxy"><code>Proxy</code></h2>
+<p><em>A configuration of the proxy server.</em></p>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="n">proxy</span> <span class="o">=</span> <span class="n">Proxy</span><span class="p">(</span><span class="s2">"http://proxy.example.com:8030"</span><span class="p">)</span>
+<span class="gp">>>> </span><span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">(</span><span class="n">proxy</span><span class="o">=</span><span class="n">proxy</span><span class="p">)</span>
+</code></pre></div>
+
+<ul>
+<li><code>def __init__(url, [ssl_context], [auth], [headers])</code></li>
+<li><code>.url</code> - <strong>URL</strong></li>
+<li><code>.auth</code> - <strong>tuple[str, str]</strong></li>
+<li><code>.headers</code> - <strong>Headers</strong></li>
+<li><code>.ssl_context</code> - <strong>SSLContext</strong></li>
+</ul>
<div class="admonition tip">
<p class="admonition-title">Tip</p>
-<p>Use <a href="https://ipython.readthedocs.io/en/stable/">IPython</a> or Python 3.8+ with <code>python -m asyncio</code> to try this code interactively, as they support executing <code>async</code>/<code>await</code> expressions in the console.</p>
+<p>Use <a href="https://ipython.readthedocs.io/en/stable/">IPython</a> or Python 3.9+ with <code>python -m asyncio</code> to try this code interactively, as they support executing <code>async</code>/<code>await</code> expressions in the console.</p>
</div>
<h2 id="api-differences">API Differences</h2>
<p>If you're using an async client then there are a few bits of API that
</ul>
<p>For situations when context block usage is not practical, it is possible to enter "manual mode" by sending a <a href="../advanced/clients/#request-instances"><code>Request</code> instance</a> using <code>client.send(..., stream=True)</code>.</p>
<p>Example in the context of forwarding the response to a streaming web endpoint with <a href="https://www.starlette.io">Starlette</a>:</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">from</span> <span class="nn">starlette.background</span> <span class="kn">import</span> <span class="n">BackgroundTask</span>
-<span class="kn">from</span> <span class="nn">starlette.responses</span> <span class="kn">import</span> <span class="n">StreamingResponse</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">from</span><span class="w"> </span><span class="nn">starlette.background</span><span class="w"> </span><span class="kn">import</span> <span class="n">BackgroundTask</span>
+<span class="kn">from</span><span class="w"> </span><span class="nn">starlette.responses</span><span class="w"> </span><span class="kn">import</span> <span class="n">StreamingResponse</span>
<span class="n">client</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">AsyncClient</span><span class="p">()</span>
-<span class="k">async</span> <span class="k">def</span> <span class="nf">home</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
+<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">home</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="n">req</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">build_request</span><span class="p">(</span><span class="s2">"GET"</span><span class="p">,</span> <span class="s2">"https://www.example.com/"</span><span class="p">)</span>
<span class="n">r</span> <span class="o">=</span> <span class="k">await</span> <span class="n">client</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">req</span><span class="p">,</span> <span class="n">stream</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="k">return</span> <span class="n">StreamingResponse</span><span class="p">(</span><span class="n">r</span><span class="o">.</span><span class="n">aiter_text</span><span class="p">(),</span> <span class="n">background</span><span class="o">=</span><span class="n">BackgroundTask</span><span class="p">(</span><span class="n">r</span><span class="o">.</span><span class="n">aclose</span><span class="p">))</span>
</div>
<h3 id="streaming-requests">Streaming requests</h3>
<p>When sending a streaming request body with an <code>AsyncClient</code> instance, you should use an async bytes generator instead of a bytes generator:</p>
-<div class="highlight"><pre><span></span><code><span class="k">async</span> <span class="k">def</span> <span class="nf">upload_bytes</span><span class="p">():</span>
+<div class="highlight"><pre><span></span><code><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">upload_bytes</span><span class="p">():</span>
<span class="o">...</span> <span class="c1"># yield byte content</span>
<span class="k">await</span> <span class="n">client</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">content</span><span class="o">=</span><span class="n">upload_bytes</span><span class="p">())</span>
<h3 id="explicit-transport-instances">Explicit transport instances</h3>
<p>When instantiating a transport instance directly, you need to use <code>httpx.AsyncHTTPTransport</code>.</p>
<p>For instance:</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="gp">>>> </span><span class="n">transport</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">AsyncHTTPTransport</span><span class="p">(</span><span class="n">retries</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="k">async</span> <span class="k">with</span> <span class="n">httpx</span><span class="o">.</span><span class="n">AsyncClient</span><span class="p">(</span><span class="n">transport</span><span class="o">=</span><span class="n">transport</span><span class="p">)</span> <span class="k">as</span> <span class="n">client</span><span class="p">:</span>
<span class="gp">>>> </span> <span class="o">...</span>
<h3 id="asyncio"><a href="https://docs.python.org/3/library/asyncio.html">AsyncIO</a></h3>
<p>AsyncIO is Python's <a href="https://docs.python.org/3/library/asyncio.html">built-in library</a>
for writing concurrent code with the async/await syntax.</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">asyncio</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
-<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
+<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>
<span class="k">async</span> <span class="k">with</span> <span class="n">httpx</span><span class="o">.</span><span class="n">AsyncClient</span><span class="p">()</span> <span class="k">as</span> <span class="n">client</span><span class="p">:</span>
<span class="n">response</span> <span class="o">=</span> <span class="k">await</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'https://www.example.com/'</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">response</span><span class="p">)</span>
<h3 id="trio"><a href="https://github.com/python-trio/trio">Trio</a></h3>
<p>Trio is <a href="https://trio.readthedocs.io/en/stable/">an alternative async library</a>,
designed around the <a href="https://en.wikipedia.org/wiki/Structured_concurrency">the principles of structured concurrency</a>.</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">import</span> <span class="nn">trio</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">trio</span>
-<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
+<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>
<span class="k">async</span> <span class="k">with</span> <span class="n">httpx</span><span class="o">.</span><span class="n">AsyncClient</span><span class="p">()</span> <span class="k">as</span> <span class="n">client</span><span class="p">:</span>
<span class="n">response</span> <span class="o">=</span> <span class="k">await</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'https://www.example.com/'</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">response</span><span class="p">)</span>
</div>
<h3 id="anyio"><a href="https://github.com/agronholm/anyio">AnyIO</a></h3>
<p>AnyIO is an <a href="https://anyio.readthedocs.io/">asynchronous networking and concurrency library</a> that works on top of either <code>asyncio</code> or <code>trio</code>. It blends in with native libraries of your chosen backend (defaults to <code>asyncio</code>).</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">httpx</span>
-<span class="kn">import</span> <span class="nn">anyio</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">anyio</span>
-<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
+<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>
<span class="k">async</span> <span class="k">with</span> <span class="n">httpx</span><span class="o">.</span><span class="n">AsyncClient</span><span class="p">()</span> <span class="k">as</span> <span class="n">client</span><span class="p">:</span>
<span class="n">response</span> <span class="o">=</span> <span class="k">await</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'https://www.example.com/'</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">response</span><span class="p">)</span>
</span>
</a>
+</li>
+
+ <li class="md-nav__item">
+ <a href="#exceptions-and-errors" class="md-nav__link">
+ <span class="md-ellipsis">
+ Exceptions and Errors
+ </span>
+ </a>
+
</li>
</ul>
</span>
</a>
+</li>
+
+ <li class="md-nav__item">
+ <a href="#exceptions-and-errors" class="md-nav__link">
+ <span class="md-ellipsis">
+ Exceptions and Errors
+ </span>
+ </a>
+
</li>
</ul>
<p><code>requests</code> allows event hooks to mutate <code>Request</code> and <code>Response</code> objects. See <a href="https://requests.readthedocs.io/en/master/user/advanced/#event-hooks">examples</a> given in the documentation for <code>requests</code>.</p>
<p>In HTTPX, event hooks may access properties of requests and responses, but event hook callbacks cannot mutate the original request/response.</p>
<p>If you are looking for more control, consider checking out <a href="../advanced/transports/#custom-transports">Custom Transports</a>.</p>
+<h2 id="exceptions-and-errors">Exceptions and Errors</h2>
+<p><code>requests</code> exception hierarchy is slightly different to the <code>httpx</code> exception hierarchy. <code>requests</code> exposes a top level <code>RequestException</code>, where as <code>httpx</code> exposes a top level <code>HTTPError</code>. see the exceptions exposes in requests <a href="https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/">here</a>. See the <code>httpx</code> error hierarchy <a href="https://www.python-httpx.org/exceptions/">here</a>.</p>
</ul>
</nav>
+</li>
+
+ <li class="md-nav__item">
+ <a href="#ssl_cert_file" class="md-nav__link">
+ <span class="md-ellipsis">
+ SSL_CERT_FILE
+ </span>
+ </a>
+
+</li>
+
+ <li class="md-nav__item">
+ <a href="#ssl_cert_dir" class="md-nav__link">
+ <span class="md-ellipsis">
+ SSL_CERT_DIR
+ </span>
+ </a>
+
</li>
</ul>
</ul>
</nav>
+</li>
+
+ <li class="md-nav__item">
+ <a href="#ssl_cert_file" class="md-nav__link">
+ <span class="md-ellipsis">
+ SSL_CERT_FILE
+ </span>
+ </a>
+
+</li>
+
+ <li class="md-nav__item">
+ <a href="#ssl_cert_dir" class="md-nav__link">
+ <span class="md-ellipsis">
+ SSL_CERT_DIR
+ </span>
+ </a>
+
</li>
</ul>
python<span class="w"> </span>-c<span class="w"> </span><span class="s2">"import httpx; httpx.get('https://www.python-httpx.org')"</span>
</code></pre></div>
+<h2 id="ssl_cert_file"><code>SSL_CERT_FILE</code></h2>
+<p>Valid values: a filename</p>
+<p>If this environment variable is set then HTTPX will load
+CA certificate from the specified file instead of the default
+location.</p>
+<p>Example:</p>
+<div class="highlight"><pre><span></span><code><span class="go">SSL_CERT_FILE=/path/to/ca-certs/ca-bundle.crt python -c "import httpx; httpx.get('https://example.com')"</span>
+</code></pre></div>
+
+<h2 id="ssl_cert_dir"><code>SSL_CERT_DIR</code></h2>
+<p>Valid values: a directory following an <a href="https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html">OpenSSL specific layout</a>.</p>
+<p>If this environment variable is set and the directory follows an <a href="https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html">OpenSSL specific layout</a> (ie. you ran <code>c_rehash</code>) then HTTPX will load CA certificates from this directory instead of the default location.</p>
+<p>Example:</p>
+<div class="highlight"><pre><span></span><code><span class="go">SSL_CERT_DIR=/path/to/ca-certs/ python -c "import httpx; httpx.get('https://example.com')"</span>
+</code></pre></div>
+
</code></pre></div>
<p>Now, let's get started:</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'https://www.example.org/'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">r</span>
<span class="go"><Response [200 OK]></span>
<div class="highlight"><pre><span></span><code>$<span class="w"> </span>pip<span class="w"> </span>install<span class="w"> </span>httpx<span class="o">[</span>brotli,zstd<span class="o">]</span>
</code></pre></div>
-<p>HTTPX requires Python 3.8+</p>
+<p>HTTPX requires Python 3.9+</p>
<h1 id="logging">Logging</h1>
<p>If you need to inspect the internal behaviour of <code>httpx</code>, you can use Python's standard logging to output information about the underlying network behaviour.</p>
<p>For example, the following configuration...</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">logging</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">logging</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span>
<span class="nb">format</span><span class="o">=</span><span class="s2">"</span><span class="si">%(levelname)s</span><span class="s2"> [</span><span class="si">%(asctime)s</span><span class="s2">] </span><span class="si">%(name)s</span><span class="s2"> - </span><span class="si">%(message)s</span><span class="s2">"</span><span class="p">,</span>
</code></pre></div>
<p>Will send debug level output to the console, or wherever <code>stdout</code> is directed too...</p>
-<div class="highlight"><pre><span></span><code><span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">40</span><span class="p">]</span><span class="w"> </span><span class="n">httpx</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">load_ssl_context</span><span class="w"> </span><span class="n">verify</span><span class="o">=</span><span class="n">True</span><span class="w"> </span><span class="n">cert</span><span class="o">=</span><span class="n">None</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">40</span><span class="p">]</span><span class="w"> </span><span class="n">httpx</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">load_verify_locations</span><span class="w"> </span><span class="n">cafile</span><span class="o">=</span><span class="s1">'/Users/karenpetrosyan/oss/karhttpx/.venv/lib/python3.9/site-packages/certifi/cacert.pem'</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">40</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">connect_tcp</span><span class="o">.</span><span class="n">started</span><span class="w"> </span><span class="n">host</span><span class="o">=</span><span class="s1">'www.example.com'</span><span class="w"> </span><span class="n">port</span><span class="o">=</span><span class="mi">443</span><span class="w"> </span><span class="n">local_address</span><span class="o">=</span><span class="n">None</span><span class="w"> </span><span class="n">timeout</span><span class="o">=</span><span class="mf">5.0</span><span class="w"> </span><span class="n">socket_options</span><span class="o">=</span><span class="n">None</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">connect_tcp</span><span class="o">.</span><span class="n">complete</span><span class="w"> </span><span class="n">return_value</span><span class="o">=<</span><span class="n">httpcore</span><span class="o">.</span><span class="n">_backends</span><span class="o">.</span><span class="n">sync</span><span class="o">.</span><span class="n">SyncStream</span><span class="w"> </span><span class="n">object</span><span class="w"> </span><span class="n">at</span><span class="w"> </span><span class="mh">0x101f1e8e0</span><span class="o">></span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">start_tls</span><span class="o">.</span><span class="n">started</span><span class="w"> </span><span class="n">ssl_context</span><span class="o">=</span><span class="n">SSLContext</span><span class="p">(</span><span class="n">verify</span><span class="o">=</span><span class="n">True</span><span class="p">)</span><span class="w"> </span><span class="n">server_hostname</span><span class="o">=</span><span class="s1">'www.example.com'</span><span class="w"> </span><span class="n">timeout</span><span class="o">=</span><span class="mf">5.0</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">start_tls</span><span class="o">.</span><span class="n">complete</span><span class="w"> </span><span class="n">return_value</span><span class="o">=<</span><span class="n">httpcore</span><span class="o">.</span><span class="n">_backends</span><span class="o">.</span><span class="n">sync</span><span class="o">.</span><span class="n">SyncStream</span><span class="w"> </span><span class="n">object</span><span class="w"> </span><span class="n">at</span><span class="w"> </span><span class="mh">0x1020f49a0</span><span class="o">></span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">send_request_headers</span><span class="o">.</span><span class="n">started</span><span class="w"> </span><span class="n">request</span><span class="o">=<</span><span class="n">Request</span><span class="w"> </span><span class="p">[</span><span class="sa">b</span><span class="s1">'GET'</span><span class="p">]</span><span class="o">></span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">send_request_headers</span><span class="o">.</span><span class="n">complete</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">send_request_body</span><span class="o">.</span><span class="n">started</span><span class="w"> </span><span class="n">request</span><span class="o">=<</span><span class="n">Request</span><span class="w"> </span><span class="p">[</span><span class="sa">b</span><span class="s1">'GET'</span><span class="p">]</span><span class="o">></span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">send_request_body</span><span class="o">.</span><span class="n">complete</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">receive_response_headers</span><span class="o">.</span><span class="n">started</span><span class="w"> </span><span class="n">request</span><span class="o">=<</span><span class="n">Request</span><span class="w"> </span><span class="p">[</span><span class="sa">b</span><span class="s1">'GET'</span><span class="p">]</span><span class="o">></span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">receive_response_headers</span><span class="o">.</span><span class="n">complete</span><span class="w"> </span><span class="n">return_value</span><span class="o">=</span><span class="p">(</span><span class="sa">b</span><span class="s1">'HTTP/1.1'</span><span class="p">,</span><span class="w"> </span><span class="mi">200</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'OK'</span><span class="p">,</span><span class="w"> </span><span class="p">[(</span><span class="sa">b</span><span class="s1">'Content-Encoding'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'gzip'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Accept-Ranges'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'bytes'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Age'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'407727'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Cache-Control'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'max-age=604800'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Content-Type'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'text/html; charset=UTF-8'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Date'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'Sat, 28 Sep 2024 13:27:42 GMT'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Etag'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'"3147526947+gzip"'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Expires'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'Sat, 05 Oct 2024 13:27:42 GMT'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Last-Modified'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'Thu, 17 Oct 2019 07:18:26 GMT'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Server'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'ECAcc (dcd/7D43)'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Vary'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'Accept-Encoding'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'X-Cache'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'HIT'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="sa">b</span><span class="s1">'Content-Length'</span><span class="p">,</span><span class="w"> </span><span class="sa">b</span><span class="s1">'648'</span><span class="p">)])</span>
-<span class="n">INFO</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpx</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">HTTP</span><span class="w"> </span><span class="n">Request</span><span class="p">:</span><span class="w"> </span><span class="n">GET</span><span class="w"> </span><span class="n">https</span><span class="p">:</span><span class="o">//</span><span class="n">www</span><span class="o">.</span><span class="n">example</span><span class="o">.</span><span class="n">com</span><span class="w"> </span><span class="s2">"HTTP/1.1 200 OK"</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">receive_response_body</span><span class="o">.</span><span class="n">started</span><span class="w"> </span><span class="n">request</span><span class="o">=<</span><span class="n">Request</span><span class="w"> </span><span class="p">[</span><span class="sa">b</span><span class="s1">'GET'</span><span class="p">]</span><span class="o">></span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">receive_response_body</span><span class="o">.</span><span class="n">complete</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">response_closed</span><span class="o">.</span><span class="n">started</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">response_closed</span><span class="o">.</span><span class="n">complete</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">close</span><span class="o">.</span><span class="n">started</span>
-<span class="n">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="n">httpcore</span><span class="o">.</span><span class="n">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">close</span><span class="o">.</span><span class="n">complete</span>
+<div class="highlight"><pre><span></span><code><span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">40</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">connect_tcp</span><span class="p">.</span><span class="nx">started</span><span class="w"> </span><span class="nx">host</span><span class="p">=</span><span class="err">'</span><span class="nx">www</span><span class="p">.</span><span class="nx">example</span><span class="p">.</span><span class="nx">com</span><span class="err">'</span><span class="w"> </span><span class="nx">port</span><span class="p">=</span><span class="mi">443</span><span class="w"> </span><span class="nx">local_address</span><span class="p">=</span><span class="nx">None</span><span class="w"> </span><span class="nx">timeout</span><span class="p">=</span><span class="m m-Double">5.0</span><span class="w"> </span><span class="nx">socket_options</span><span class="p">=</span><span class="nx">None</span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">connect_tcp</span><span class="p">.</span><span class="nx">complete</span><span class="w"> </span><span class="nx">return_value</span><span class="p">=<</span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">_backends</span><span class="p">.</span><span class="nx">sync</span><span class="p">.</span><span class="nx">SyncStream</span><span class="w"> </span><span class="nx">object</span><span class="w"> </span><span class="nx">at</span><span class="w"> </span><span class="mh">0x101f1e8e0</span><span class="p">></span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">start_tls</span><span class="p">.</span><span class="nx">started</span><span class="w"> </span><span class="nx">ssl_context</span><span class="p">=</span><span class="nx">SSLContext</span><span class="p">(</span><span class="nx">verify</span><span class="p">=</span><span class="nx">True</span><span class="p">)</span><span class="w"> </span><span class="nx">server_hostname</span><span class="p">=</span><span class="err">'</span><span class="nx">www</span><span class="p">.</span><span class="nx">example</span><span class="p">.</span><span class="nx">com</span><span class="err">'</span><span class="w"> </span><span class="nx">timeout</span><span class="p">=</span><span class="m m-Double">5.0</span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">start_tls</span><span class="p">.</span><span class="nx">complete</span><span class="w"> </span><span class="nx">return_value</span><span class="p">=<</span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">_backends</span><span class="p">.</span><span class="nx">sync</span><span class="p">.</span><span class="nx">SyncStream</span><span class="w"> </span><span class="nx">object</span><span class="w"> </span><span class="nx">at</span><span class="w"> </span><span class="mh">0x1020f49a0</span><span class="p">></span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">send_request_headers</span><span class="p">.</span><span class="nx">started</span><span class="w"> </span><span class="nx">request</span><span class="p">=<</span><span class="nx">Request</span><span class="w"> </span><span class="p">[</span><span class="nx">b</span><span class="err">'</span><span class="nx">GET</span><span class="err">'</span><span class="p">]></span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">send_request_headers</span><span class="p">.</span><span class="nx">complete</span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">send_request_body</span><span class="p">.</span><span class="nx">started</span><span class="w"> </span><span class="nx">request</span><span class="p">=<</span><span class="nx">Request</span><span class="w"> </span><span class="p">[</span><span class="nx">b</span><span class="err">'</span><span class="nx">GET</span><span class="err">'</span><span class="p">]></span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">send_request_body</span><span class="p">.</span><span class="nx">complete</span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">receive_response_headers</span><span class="p">.</span><span class="nx">started</span><span class="w"> </span><span class="nx">request</span><span class="p">=<</span><span class="nx">Request</span><span class="w"> </span><span class="p">[</span><span class="nx">b</span><span class="err">'</span><span class="nx">GET</span><span class="err">'</span><span class="p">]></span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">receive_response_headers</span><span class="p">.</span><span class="nx">complete</span><span class="w"> </span><span class="nx">return_value</span><span class="p">=(</span><span class="nx">b</span><span class="err">'</span><span class="nx">HTTP</span><span class="o">/</span><span class="m m-Double">1.1</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="mi">200</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">OK</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="p">[(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Content</span><span class="o">-</span><span class="nx">Encoding</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">gzip</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Accept</span><span class="o">-</span><span class="nx">Ranges</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">bytes</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Age</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="mi">407727</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Cache</span><span class="o">-</span><span class="nx">Control</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">max</span><span class="o">-</span><span class="nx">age</span><span class="p">=</span><span class="mi">604800</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Content</span><span class="o">-</span><span class="nx">Type</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">text</span><span class="o">/</span><span class="nx">html</span><span class="p">;</span><span class="w"> </span><span class="nx">charset</span><span class="p">=</span><span class="nx">UTF</span><span class="o">-</span><span class="mi">8</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Date</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">Sat</span><span class="p">,</span><span class="w"> </span><span class="mi">28</span><span class="w"> </span><span class="nx">Sep</span><span class="w"> </span><span class="mi">2024</span><span class="w"> </span><span class="mi">13</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">42</span><span class="w"> </span><span class="nx">GMT</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Etag</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="s">"3147526947+gzip"</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Expires</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">Sat</span><span class="p">,</span><span class="w"> </span><span class="mi">05</span><span class="w"> </span><span class="nx">Oct</span><span class="w"> </span><span class="mi">2024</span><span class="w"> </span><span class="mi">13</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">42</span><span class="w"> </span><span class="nx">GMT</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Last</span><span class="o">-</span><span class="nx">Modified</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">Thu</span><span class="p">,</span><span class="w"> </span><span class="mi">17</span><span class="w"> </span><span class="nx">Oct</span><span class="w"> </span><span class="mi">2019</span><span class="w"> </span><span class="mi">07</span><span class="p">:</span><span class="mi">18</span><span class="p">:</span><span class="mi">26</span><span class="w"> </span><span class="nx">GMT</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Server</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">ECAcc</span><span class="w"> </span><span class="p">(</span><span class="nx">dcd</span><span class="o">/</span><span class="mi">7</span><span class="nx">D43</span><span class="p">)</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Vary</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">Accept</span><span class="o">-</span><span class="nx">Encoding</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">X</span><span class="o">-</span><span class="nx">Cache</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="nx">HIT</span><span class="err">'</span><span class="p">),</span><span class="w"> </span><span class="p">(</span><span class="nx">b</span><span class="err">'</span><span class="nx">Content</span><span class="o">-</span><span class="nx">Length</span><span class="err">'</span><span class="p">,</span><span class="w"> </span><span class="nx">b</span><span class="err">'</span><span class="mi">648</span><span class="err">'</span><span class="p">)])</span>
+<span class="nx">INFO</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpx</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">HTTP</span><span class="w"> </span><span class="nx">Request</span><span class="p">:</span><span class="w"> </span><span class="nx">GET</span><span class="w"> </span><span class="nx">https</span><span class="p">:</span><span class="c1">//www.example.com "HTTP/1.1 200 OK"</span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">receive_response_body</span><span class="p">.</span><span class="nx">started</span><span class="w"> </span><span class="nx">request</span><span class="p">=<</span><span class="nx">Request</span><span class="w"> </span><span class="p">[</span><span class="nx">b</span><span class="err">'</span><span class="nx">GET</span><span class="err">'</span><span class="p">]></span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">receive_response_body</span><span class="p">.</span><span class="nx">complete</span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">response_closed</span><span class="p">.</span><span class="nx">started</span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">http11</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">response_closed</span><span class="p">.</span><span class="nx">complete</span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">close</span><span class="p">.</span><span class="nx">started</span>
+<span class="nx">DEBUG</span><span class="w"> </span><span class="p">[</span><span class="mi">2024</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">28</span><span class="w"> </span><span class="mi">17</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">41</span><span class="p">]</span><span class="w"> </span><span class="nx">httpcore</span><span class="p">.</span><span class="nx">connection</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">close</span><span class="p">.</span><span class="nx">complete</span>
</code></pre></div>
<p>Logging output includes information from both the high-level <code>httpx</code> logger, and the network-level <code>httpcore</code> logger, which can be configured separately.</p>
<p>For handling more complex logging configurations you might want to use the dictionary configuration style...</p>
-<div class="highlight"><pre><span></span><code><span class="kn">import</span> <span class="nn">logging.config</span>
-<span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">logging.config</span>
+<span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
<span class="n">LOGGING_CONFIG</span> <span class="o">=</span> <span class="p">{</span>
<span class="s2">"version"</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
<h1 id="quickstart">QuickStart</h1>
<p>First, start by importing HTTPX:</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">httpx</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">httpx</span>
</code></pre></div>
<p>Now, let’s try to get a webpage.</p>
encoding will be supported. If <code>zstandard</code> is installed, then <code>zstd</code>
response encodings will also be supported.</p>
<p>For example, to create an image from binary data returned by a request, you can use the following code:</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">PIL</span> <span class="kn">import</span> <span class="n">Image</span>
-<span class="gp">>>> </span><span class="kn">from</span> <span class="nn">io</span> <span class="kn">import</span> <span class="n">BytesIO</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">PIL</span><span class="w"> </span><span class="kn">import</span> <span class="n">Image</span>
+<span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">io</span><span class="w"> </span><span class="kn">import</span> <span class="n">BytesIO</span>
<span class="gp">>>> </span><span class="n">i</span> <span class="o">=</span> <span class="n">Image</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">BytesIO</span><span class="p">(</span><span class="n">r</span><span class="o">.</span><span class="n">content</span><span class="p">))</span>
</code></pre></div>
<h2 id="sending-multipart-file-uploads">Sending Multipart File Uploads</h2>
<p>You can also upload files, using HTTP multipart encoding:</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'upload-file'</span><span class="p">:</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)}</span>
-<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">report_file</span><span class="p">:</span>
+<span class="gp">... </span> <span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'upload-file'</span><span class="p">:</span> <span class="n">report_file</span><span class="p">}</span>
+<span class="gp">... </span> <span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">r</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
<span class="go">{</span>
<span class="go"> ...</span>
<p>You can also explicitly set the filename and content type, by using a tuple
of items for the file value:</p>
-<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'upload-file'</span><span class="p">:</span> <span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">),</span> <span class="s1">'application/vnd.ms-excel'</span><span class="p">)}</span>
-<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
+<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="n">report_file</span><span class="p">:</span>
+<span class="gp">... </span> <span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'upload-file'</span><span class="p">:</span> <span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="n">report_file</span><span class="p">,</span> <span class="s1">'application/vnd.ms-excel'</span><span class="p">)}</span>
+<span class="gp">... </span> <span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">r</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
<span class="go">{</span>
<span class="go"> ...</span>
<p>If you need to include non-file data fields in the multipart form, use the <code>data=...</code> parameter:</p>
<div class="highlight"><pre><span></span><code><span class="gp">>>> </span><span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'message'</span><span class="p">:</span> <span class="s1">'Hello, world!'</span><span class="p">}</span>
-<span class="gp">>>> </span><span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'file'</span><span class="p">:</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)}</span>
-<span class="gp">>>> </span><span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">data</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
+<span class="gp">>>> </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'report.xls'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">report_file</span><span class="p">:</span>
+<span class="gp">... </span> <span class="n">files</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'file'</span><span class="p">:</span> <span class="n">report_file</span><span class="p">}</span>
+<span class="gp">... </span> <span class="n">r</span> <span class="o">=</span> <span class="n">httpx</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s2">"https://httpbin.org/post"</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">data</span><span class="p">,</span> <span class="n">files</span><span class="o">=</span><span class="n">files</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">r</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
<span class="go">{</span>
<span class="go"> ...</span>
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Introduction","text":"HTTPX A next-generation HTTP client for Python. <p>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.</p> <p>Install HTTPX using pip:</p> <pre><code>$ pip install httpx\n</code></pre> <p>Now, let's get started:</p> <pre><code>>>> import httpx\n>>> r = httpx.get('https://www.example.org/')\n>>> r\n<Response [200 OK]>\n>>> r.status_code\n200\n>>> r.headers['content-type']\n'text/html; charset=UTF-8'\n>>> r.text\n'<!doctype html>\\n<html>\\n<head>\\n<title>Example Domain</title>...'\n</code></pre> <p>Or, using the command-line client.</p> <pre><code># The command line client is an optional dependency.\n$ pip install 'httpx[cli]'\n</code></pre> <p>Which now allows us to use HTTPX directly from the command-line...</p> <p></p> <p>Sending a request...</p> <p></p>"},{"location":"#features","title":"Features","text":"<p>HTTPX builds on the well-established usability of <code>requests</code>, and gives you:</p> <ul> <li>A broadly requests-compatible API.</li> <li>Standard synchronous interface, but with async support if you need it.</li> <li>HTTP/1.1 and HTTP/2 support.</li> <li>Ability to make requests directly to WSGI applications or ASGI applications.</li> <li>Strict timeouts everywhere.</li> <li>Fully type annotated.</li> <li>100% test coverage.</li> </ul> <p>Plus all the standard features of <code>requests</code>...</p> <ul> <li>International Domains and URLs</li> <li>Keep-Alive & Connection Pooling</li> <li>Sessions with Cookie Persistence</li> <li>Browser-style SSL Verification</li> <li>Basic/Digest Authentication</li> <li>Elegant Key/Value Cookies</li> <li>Automatic Decompression</li> <li>Automatic Content Decoding</li> <li>Unicode Response Bodies</li> <li>Multipart File Uploads</li> <li>HTTP(S) Proxy Support</li> <li>Connection Timeouts</li> <li>Streaming Downloads</li> <li>.netrc Support</li> <li>Chunked Requests</li> </ul>"},{"location":"#documentation","title":"Documentation","text":"<p>For a run-through of all the basics, head over to the QuickStart.</p> <p>For more advanced topics, see the Advanced section, the async support section, or the HTTP/2 section.</p> <p>The Developer Interface provides a comprehensive API reference.</p> <p>To find out about tools that integrate with HTTPX, see Third Party Packages.</p>"},{"location":"#dependencies","title":"Dependencies","text":"<p>The HTTPX project relies on these excellent libraries:</p> <ul> <li><code>httpcore</code> - The underlying transport implementation for <code>httpx</code>.</li> <li><code>h11</code> - HTTP/1.1 support.</li> <li><code>certifi</code> - SSL certificates.</li> <li><code>idna</code> - Internationalized domain name support.</li> <li><code>sniffio</code> - Async library autodetection.</li> </ul> <p>As well as these optional installs:</p> <ul> <li><code>h2</code> - HTTP/2 support. (Optional, with <code>httpx[http2]</code>)</li> <li><code>socksio</code> - SOCKS proxy support. (Optional, with <code>httpx[socks]</code>)</li> <li><code>rich</code> - Rich terminal support. (Optional, with <code>httpx[cli]</code>)</li> <li><code>click</code> - Command line client support. (Optional, with <code>httpx[cli]</code>)</li> <li><code>brotli</code> or <code>brotlicffi</code> - Decoding for \"brotli\" compressed responses. (Optional, with <code>httpx[brotli]</code>)</li> <li><code>zstandard</code> - Decoding for \"zstd\" compressed responses. (Optional, with <code>httpx[zstd]</code>)</li> </ul> <p>A huge amount of credit is due to <code>requests</code> for the API layout that much of this work follows, as well as to <code>urllib3</code> for plenty of design inspiration around the lower-level networking details.</p>"},{"location":"#installation","title":"Installation","text":"<p>Install with pip:</p> <pre><code>$ pip install httpx\n</code></pre> <p>Or, to include the optional HTTP/2 support, use:</p> <pre><code>$ pip install httpx[http2]\n</code></pre> <p>To include the optional brotli and zstandard decoders support, use:</p> <pre><code>$ pip install httpx[brotli,zstd]\n</code></pre> <p>HTTPX requires Python 3.8+</p>"},{"location":"api/","title":"Developer Interface","text":""},{"location":"api/#helper-functions","title":"Helper Functions","text":"<p>Note</p> <p>Only use these functions if you're testing HTTPX in a console or making a small number of requests. Using a <code>Client</code> will enable HTTP/2 and connection pooling for more efficient and long-lived connections.</p> <code>httpx.request</code>(method, url, *, params=None, content=None, data=None, files=None, json=None, headers=None, cookies=None, auth=None, proxy=None, timeout=Timeout(timeout=5.0), follow_redirects=False, verify=True, trust_env=True) <p>Sends an HTTP request.</p> <p>Parameters:</p> <ul> <li>method - HTTP method for the new <code>Request</code> object: <code>GET</code>, <code>OPTIONS</code>, <code>HEAD</code>, <code>POST</code>, <code>PUT</code>, <code>PATCH</code>, or <code>DELETE</code>.</li> <li>url - URL for the new <code>Request</code> object.</li> <li>params - (optional) Query parameters to include in the URL, as a string, dictionary, or sequence of two-tuples.</li> <li>content - (optional) Binary content to include in the body of the request, as bytes or a byte iterator.</li> <li>data - (optional) Form data to include in the body of the request, as a dictionary.</li> <li>files - (optional) A dictionary of upload files to include in the body of the request.</li> <li>json - (optional) A JSON serializable object to include in the body of the request.</li> <li>headers - (optional) Dictionary of HTTP headers to include in the request.</li> <li>cookies - (optional) Dictionary of Cookie items to include in the request.</li> <li>auth - (optional) An authentication class to use when sending the request.</li> <li>proxy - (optional) A proxy URL where all the traffic should be routed.</li> <li>timeout - (optional) The timeout configuration to use when sending the request.</li> <li>follow_redirects - (optional) Enables or disables HTTP redirects.</li> <li>verify - (optional) Either <code>True</code> to use an SSL context with the default CA bundle, <code>False</code> to disable verification, or an instance of <code>ssl.SSLContext</code> to use a custom context.</li> <li>trust_env - (optional) Enables or disables usage of environment variables for configuration.</li> </ul> <p>Returns: <code>Response</code></p> <p>Usage:</p> <pre><code>>>> import httpx\n>>> response = httpx.request('GET', 'https://httpbin.org/get')\n>>> response\n<Response [200 OK]>\n</code></pre> <code>httpx.get</code>(url, *, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>GET</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>Note that the <code>data</code>, <code>files</code>, <code>json</code> and <code>content</code> parameters are not available on this function, as <code>GET</code> requests should not include a request body.</p> <code>httpx.options</code>(url, *, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends an <code>OPTIONS</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>Note that the <code>data</code>, <code>files</code>, <code>json</code> and <code>content</code> parameters are not available on this function, as <code>OPTIONS</code> requests should not include a request body.</p> <code>httpx.head</code>(url, *, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>HEAD</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>Note that the <code>data</code>, <code>files</code>, <code>json</code> and <code>content</code> parameters are not available on this function, as <code>HEAD</code> requests should not include a request body.</p> <code>httpx.post</code>(url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>POST</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>httpx.put</code>(url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>PUT</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>httpx.patch</code>(url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>PATCH</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>httpx.delete</code>(url, *, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, timeout=Timeout(timeout=5.0), verify=True, trust_env=True) <p>Sends a <code>DELETE</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>Note that the <code>data</code>, <code>files</code>, <code>json</code> and <code>content</code> parameters are not available on this function, as <code>DELETE</code> requests should not include a request body.</p> <code>httpx.stream</code>(method, url, *, params=None, content=None, data=None, files=None, json=None, headers=None, cookies=None, auth=None, proxy=None, timeout=Timeout(timeout=5.0), follow_redirects=False, verify=True, trust_env=True) <p>Alternative to <code>httpx.request()</code> that streams the response body instead of loading it into memory at once.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>See also: Streaming Responses</p>"},{"location":"api/#client","title":"<code>Client</code>","text":"class <code>httpx.Client</code>(*, auth=None, params=None, headers=None, cookies=None, verify=True, cert=None, trust_env=True, http1=True, http2=False, proxy=None, mounts=None, timeout=Timeout(timeout=5.0), follow_redirects=False, limits=Limits(max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0), max_redirects=20, event_hooks=None, base_url='', transport=None, default_encoding='utf-8') <p>An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.</p> <p>It can be shared between threads.</p> <p>Usage:</p> <pre><code>>>> client = httpx.Client()\n>>> response = client.get('https://example.org')\n</code></pre> <p>Parameters:</p> <ul> <li>auth - (optional) An authentication class to use when sending requests.</li> <li>params - (optional) Query parameters to include in request URLs, as a string, dictionary, or sequence of two-tuples.</li> <li>headers - (optional) Dictionary of HTTP headers to include when sending requests.</li> <li>cookies - (optional) Dictionary of Cookie items to include when sending requests.</li> <li>verify - (optional) Either <code>True</code> to use an SSL context with the default CA bundle, <code>False</code> to disable verification, or an instance of <code>ssl.SSLContext</code> to use a custom context.</li> <li>http2 - (optional) A boolean indicating if HTTP/2 support should be enabled. Defaults to <code>False</code>.</li> <li>proxy - (optional) A proxy URL where all the traffic should be routed.</li> <li>timeout - (optional) The timeout configuration to use when sending requests.</li> <li>limits - (optional) The limits configuration to use.</li> <li>max_redirects - (optional) The maximum number of redirect responses that should be followed.</li> <li>base_url - (optional) A URL to use as the base when building request URLs.</li> <li>transport - (optional) A transport class to use for sending requests over the network.</li> <li>trust_env - (optional) Enables or disables usage of environment variables for configuration.</li> <li>default_encoding - (optional) The default encoding to use for decoding response text, if no charset information is included in a response Content-Type header. Set to a callable for automatic character set detection. Default: \"utf-8\".</li> </ul> <code>headers</code> <p>HTTP headers to include when sending requests.</p> <code>cookies</code> <p>Cookie values to include when sending requests.</p> <code>params</code> <p>Query parameters to include in the URL when sending requests.</p> <code>auth</code> <p>Authentication class used when none is passed at the request-level.</p> <p>See also Authentication.</p> <code>request</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Build and send a request.</p> <p>Equivalent to:</p> <pre><code>request = client.build_request(...)\nresponse = client.send(request, ...)\n</code></pre> <p>See <code>Client.build_request()</code>, <code>Client.send()</code> and Merging of configuration for how the various parameters are merged with client-level configuration.</p> <code>get</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>GET</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>head</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>HEAD</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>options</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send an <code>OPTIONS</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>post</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>POST</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>put</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>PUT</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>patch</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>PATCH</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>delete</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>DELETE</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>stream</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Alternative to <code>httpx.request()</code> that streams the response body instead of loading it into memory at once.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>See also: Streaming Responses</p> <code>build_request</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, timeout=, extensions=None) <p>Build and return a request instance.</p> <ul> <li>The <code>params</code>, <code>headers</code> and <code>cookies</code> arguments are merged with any values set on the client.</li> <li>The <code>url</code> argument is merged with any <code>base_url</code> set on the client.</li> </ul> <p>See also: Request instances</p> <code>send</code>(self, request, *, stream=False, auth=, follow_redirects=) <p>Send a request.</p> <p>The request is sent as-is, unmodified.</p> <p>Typically you'll want to build one with <code>Client.build_request()</code> so that any client-level configuration is merged into the request, but passing an explicit <code>httpx.Request()</code> is supported as well.</p> <p>See also: Request instances</p> <code>close</code>(self) <p>Close transport and proxies.</p>"},{"location":"api/#asyncclient","title":"<code>AsyncClient</code>","text":"class <code>httpx.AsyncClient</code>(*, auth=None, params=None, headers=None, cookies=None, verify=True, cert=None, http1=True, http2=False, proxy=None, mounts=None, timeout=Timeout(timeout=5.0), follow_redirects=False, limits=Limits(max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0), max_redirects=20, event_hooks=None, base_url='', transport=None, trust_env=True, default_encoding='utf-8') <p>An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.</p> <p>It can be shared between tasks.</p> <p>Usage:</p> <pre><code>>>> async with httpx.AsyncClient() as client:\n>>> response = await client.get('https://example.org')\n</code></pre> <p>Parameters:</p> <ul> <li>auth - (optional) An authentication class to use when sending requests.</li> <li>params - (optional) Query parameters to include in request URLs, as a string, dictionary, or sequence of two-tuples.</li> <li>headers - (optional) Dictionary of HTTP headers to include when sending requests.</li> <li>cookies - (optional) Dictionary of Cookie items to include when sending requests.</li> <li>verify - (optional) Either <code>True</code> to use an SSL context with the default CA bundle, <code>False</code> to disable verification, or an instance of <code>ssl.SSLContext</code> to use a custom context.</li> <li>http2 - (optional) A boolean indicating if HTTP/2 support should be enabled. Defaults to <code>False</code>.</li> <li>proxy - (optional) A proxy URL where all the traffic should be routed.</li> <li>timeout - (optional) The timeout configuration to use when sending requests.</li> <li>limits - (optional) The limits configuration to use.</li> <li>max_redirects - (optional) The maximum number of redirect responses that should be followed.</li> <li>base_url - (optional) A URL to use as the base when building request URLs.</li> <li>transport - (optional) A transport class to use for sending requests over the network.</li> <li>trust_env - (optional) Enables or disables usage of environment variables for configuration.</li> <li>default_encoding - (optional) The default encoding to use for decoding response text, if no charset information is included in a response Content-Type header. Set to a callable for automatic character set detection. Default: \"utf-8\".</li> </ul> <code>headers</code> <p>HTTP headers to include when sending requests.</p> <code>cookies</code> <p>Cookie values to include when sending requests.</p> <code>params</code> <p>Query parameters to include in the URL when sending requests.</p> <code>auth</code> <p>Authentication class used when none is passed at the request-level.</p> <p>See also Authentication.</p> async <code>request</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Build and send a request.</p> <p>Equivalent to:</p> <pre><code>request = client.build_request(...)\nresponse = await client.send(request, ...)\n</code></pre> <p>See <code>AsyncClient.build_request()</code>, <code>AsyncClient.send()</code> and Merging of configuration for how the various parameters are merged with client-level configuration.</p> async <code>get</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>GET</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>head</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>HEAD</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>options</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send an <code>OPTIONS</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>post</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>POST</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>put</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>PUT</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>patch</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>PATCH</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>delete</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>DELETE</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>stream</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Alternative to <code>httpx.request()</code> that streams the response body instead of loading it into memory at once.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>See also: Streaming Responses</p> <code>build_request</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, timeout=, extensions=None) <p>Build and return a request instance.</p> <ul> <li>The <code>params</code>, <code>headers</code> and <code>cookies</code> arguments are merged with any values set on the client.</li> <li>The <code>url</code> argument is merged with any <code>base_url</code> set on the client.</li> </ul> <p>See also: Request instances</p> async <code>send</code>(self, request, *, stream=False, auth=, follow_redirects=) <p>Send a request.</p> <p>The request is sent as-is, unmodified.</p> <p>Typically you'll want to build one with <code>AsyncClient.build_request()</code> so that any client-level configuration is merged into the request, but passing an explicit <code>httpx.Request()</code> is supported as well.</p> <p>See also: Request instances</p> async <code>aclose</code>(self) <p>Close transport and proxies.</p>"},{"location":"api/#response","title":"<code>Response</code>","text":"<p>An HTTP response.</p> <ul> <li><code>def __init__(...)</code></li> <li><code>.status_code</code> - int</li> <li><code>.reason_phrase</code> - str</li> <li><code>.http_version</code> - <code>\"HTTP/2\"</code> or <code>\"HTTP/1.1\"</code></li> <li><code>.url</code> - URL</li> <li><code>.headers</code> - Headers</li> <li><code>.content</code> - bytes</li> <li><code>.text</code> - str</li> <li><code>.encoding</code> - str</li> <li><code>.is_redirect</code> - bool</li> <li><code>.request</code> - Request</li> <li><code>.next_request</code> - Optional[Request]</li> <li><code>.cookies</code> - Cookies</li> <li><code>.history</code> - List[Response]</li> <li><code>.elapsed</code> - timedelta</li> <li>The amount of time elapsed between sending the request and calling <code>close()</code> on the corresponding response received for that request. total_seconds() to correctly get the total elapsed seconds.</li> <li><code>def .raise_for_status()</code> - Response</li> <li><code>def .json()</code> - Any</li> <li><code>def .read()</code> - bytes</li> <li><code>def .iter_raw([chunk_size])</code> - bytes iterator</li> <li><code>def .iter_bytes([chunk_size])</code> - bytes iterator</li> <li><code>def .iter_text([chunk_size])</code> - text iterator</li> <li><code>def .iter_lines()</code> - text iterator</li> <li><code>def .close()</code> - None</li> <li><code>def .next()</code> - Response</li> <li><code>def .aread()</code> - bytes</li> <li><code>def .aiter_raw([chunk_size])</code> - async bytes iterator</li> <li><code>def .aiter_bytes([chunk_size])</code> - async bytes iterator</li> <li><code>def .aiter_text([chunk_size])</code> - async text iterator</li> <li><code>def .aiter_lines()</code> - async text iterator</li> <li><code>def .aclose()</code> - None</li> <li><code>def .anext()</code> - Response</li> </ul>"},{"location":"api/#request","title":"<code>Request</code>","text":"<p>An HTTP request. Can be constructed explicitly for more control over exactly what gets sent over the wire.</p> <pre><code>>>> request = httpx.Request(\"GET\", \"https://example.org\", headers={'host': 'example.org'})\n>>> response = client.send(request)\n</code></pre> <ul> <li><code>def __init__(method, url, [params], [headers], [cookies], [content], [data], [files], [json], [stream])</code></li> <li><code>.method</code> - str</li> <li><code>.url</code> - URL</li> <li><code>.content</code> - byte, byte iterator, or byte async iterator</li> <li><code>.headers</code> - Headers</li> <li><code>.cookies</code> - Cookies</li> </ul>"},{"location":"api/#url","title":"<code>URL</code>","text":"<p>A normalized, IDNA supporting URL.</p> <pre><code>>>> url = URL(\"https://example.org/\")\n>>> url.host\n'example.org'\n</code></pre> <ul> <li><code>def __init__(url, **kwargs)</code></li> <li><code>.scheme</code> - str</li> <li><code>.authority</code> - str</li> <li><code>.host</code> - str</li> <li><code>.port</code> - int</li> <li><code>.path</code> - str</li> <li><code>.query</code> - str</li> <li><code>.raw_path</code> - str</li> <li><code>.fragment</code> - str</li> <li><code>.is_ssl</code> - bool</li> <li><code>.is_absolute_url</code> - bool</li> <li><code>.is_relative_url</code> - bool</li> <li><code>def .copy_with([scheme], [authority], [path], [query], [fragment])</code> - URL</li> </ul>"},{"location":"api/#headers","title":"<code>Headers</code>","text":"<p>A case-insensitive multi-dict.</p> <pre><code>>>> headers = Headers({'Content-Type': 'application/json'})\n>>> headers['content-type']\n'application/json'\n</code></pre> <ul> <li><code>def __init__(self, headers, encoding=None)</code></li> <li><code>def copy()</code> - Headers</li> </ul>"},{"location":"api/#cookies","title":"<code>Cookies</code>","text":"<p>A dict-like cookie store.</p> <pre><code>>>> cookies = Cookies()\n>>> cookies.set(\"name\", \"value\", domain=\"example.org\")\n</code></pre> <ul> <li><code>def __init__(cookies: [dict, Cookies, CookieJar])</code></li> <li><code>.jar</code> - CookieJar</li> <li><code>def extract_cookies(response)</code></li> <li><code>def set_cookie_header(request)</code></li> <li><code>def set(name, value, [domain], [path])</code></li> <li><code>def get(name, [domain], [path])</code></li> <li><code>def delete(name, [domain], [path])</code></li> <li><code>def clear([domain], [path])</code></li> <li>Standard mutable mapping interface</li> </ul>"},{"location":"async/","title":"Async Support","text":"<p>HTTPX offers a standard synchronous API by default, but also gives you the option of an async client if you need it.</p> <p>Async is a concurrency model that is far more efficient than multi-threading, and can provide significant performance benefits and enable the use of long-lived network connections such as WebSockets.</p> <p>If you're working with an async web framework then you'll also want to use an async client for sending outgoing HTTP requests.</p>"},{"location":"async/#making-async-requests","title":"Making Async requests","text":"<p>To make asynchronous requests, you'll need an <code>AsyncClient</code>.</p> <pre><code>>>> async with httpx.AsyncClient() as client:\n... r = await client.get('https://www.example.com/')\n...\n>>> r\n<Response [200 OK]>\n</code></pre> <p>Tip</p> <p>Use IPython or Python 3.8+ with <code>python -m asyncio</code> to try this code interactively, as they support executing <code>async</code>/<code>await</code> expressions in the console.</p>"},{"location":"async/#api-differences","title":"API Differences","text":"<p>If you're using an async client then there are a few bits of API that use async methods.</p>"},{"location":"async/#making-requests","title":"Making requests","text":"<p>The request methods are all async, so you should use <code>response = await client.get(...)</code> style for all of the following:</p> <ul> <li><code>AsyncClient.get(url, ...)</code></li> <li><code>AsyncClient.options(url, ...)</code></li> <li><code>AsyncClient.head(url, ...)</code></li> <li><code>AsyncClient.post(url, ...)</code></li> <li><code>AsyncClient.put(url, ...)</code></li> <li><code>AsyncClient.patch(url, ...)</code></li> <li><code>AsyncClient.delete(url, ...)</code></li> <li><code>AsyncClient.request(method, url, ...)</code></li> <li><code>AsyncClient.send(request, ...)</code></li> </ul>"},{"location":"async/#opening-and-closing-clients","title":"Opening and closing clients","text":"<p>Use <code>async with httpx.AsyncClient()</code> if you want a context-managed client...</p> <pre><code>async with httpx.AsyncClient() as client:\n ...\n</code></pre> <p>Warning</p> <p>In order to get the most benefit from connection pooling, make sure you're not instantiating multiple client instances - for example by using <code>async with</code> inside a \"hot loop\". This can be achieved either by having a single scoped client that's passed throughout wherever it's needed, or by having a single global client instance.</p> <p>Alternatively, use <code>await client.aclose()</code> if you want to close a client explicitly:</p> <pre><code>client = httpx.AsyncClient()\n...\nawait client.aclose()\n</code></pre>"},{"location":"async/#streaming-responses","title":"Streaming responses","text":"<p>The <code>AsyncClient.stream(method, url, ...)</code> method is an async context block.</p> <pre><code>>>> client = httpx.AsyncClient()\n>>> async with client.stream('GET', 'https://www.example.com/') as response:\n... async for chunk in response.aiter_bytes():\n... ...\n</code></pre> <p>The async response streaming methods are:</p> <ul> <li><code>Response.aread()</code> - For conditionally reading a response inside a stream block.</li> <li><code>Response.aiter_bytes()</code> - For streaming the response content as bytes.</li> <li><code>Response.aiter_text()</code> - For streaming the response content as text.</li> <li><code>Response.aiter_lines()</code> - For streaming the response content as lines of text.</li> <li><code>Response.aiter_raw()</code> - For streaming the raw response bytes, without applying content decoding.</li> <li><code>Response.aclose()</code> - For closing the response. You don't usually need this, since <code>.stream</code> block closes the response automatically on exit.</li> </ul> <p>For situations when context block usage is not practical, it is possible to enter \"manual mode\" by sending a <code>Request</code> instance using <code>client.send(..., stream=True)</code>.</p> <p>Example in the context of forwarding the response to a streaming web endpoint with Starlette:</p> <pre><code>import httpx\nfrom starlette.background import BackgroundTask\nfrom starlette.responses import StreamingResponse\n\nclient = httpx.AsyncClient()\n\nasync def home(request):\n req = client.build_request(\"GET\", \"https://www.example.com/\")\n r = await client.send(req, stream=True)\n return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))\n</code></pre> <p>Warning</p> <p>When using this \"manual streaming mode\", it is your duty as a developer to make sure that <code>Response.aclose()</code> is called eventually. Failing to do so would leave connections open, most likely resulting in resource leaks down the line.</p>"},{"location":"async/#streaming-requests","title":"Streaming requests","text":"<p>When sending a streaming request body with an <code>AsyncClient</code> instance, you should use an async bytes generator instead of a bytes generator:</p> <pre><code>async def upload_bytes():\n ... # yield byte content\n\nawait client.post(url, content=upload_bytes())\n</code></pre>"},{"location":"async/#explicit-transport-instances","title":"Explicit transport instances","text":"<p>When instantiating a transport instance directly, you need to use <code>httpx.AsyncHTTPTransport</code>.</p> <p>For instance:</p> <pre><code>>>> import httpx\n>>> transport = httpx.AsyncHTTPTransport(retries=1)\n>>> async with httpx.AsyncClient(transport=transport) as client:\n>>> ...\n</code></pre>"},{"location":"async/#supported-async-environments","title":"Supported async environments","text":"<p>HTTPX supports either <code>asyncio</code> or <code>trio</code> as an async environment.</p> <p>It will auto-detect which of those two to use as the backend for socket operations and concurrency primitives.</p>"},{"location":"async/#asyncio","title":"AsyncIO","text":"<p>AsyncIO is Python's built-in library for writing concurrent code with the async/await syntax.</p> <pre><code>import asyncio\nimport httpx\n\nasync def main():\n async with httpx.AsyncClient() as client:\n response = await client.get('https://www.example.com/')\n print(response)\n\nasyncio.run(main())\n</code></pre>"},{"location":"async/#trio","title":"Trio","text":"<p>Trio is an alternative async library, designed around the the principles of structured concurrency.</p> <pre><code>import httpx\nimport trio\n\nasync def main():\n async with httpx.AsyncClient() as client:\n response = await client.get('https://www.example.com/')\n print(response)\n\ntrio.run(main)\n</code></pre> <p>Important</p> <p>The <code>trio</code> package must be installed to use the Trio backend.</p>"},{"location":"async/#anyio","title":"AnyIO","text":"<p>AnyIO is an asynchronous networking and concurrency library that works on top of either <code>asyncio</code> or <code>trio</code>. It blends in with native libraries of your chosen backend (defaults to <code>asyncio</code>).</p> <pre><code>import httpx\nimport anyio\n\nasync def main():\n async with httpx.AsyncClient() as client:\n response = await client.get('https://www.example.com/')\n print(response)\n\nanyio.run(main, backend='trio')\n</code></pre>"},{"location":"async/#calling-into-python-web-apps","title":"Calling into Python Web Apps","text":"<p>For details on calling directly into ASGI applications, see the <code>ASGITransport</code> docs.</p>"},{"location":"code_of_conduct/","title":"Code of Conduct","text":"<p>We expect contributors to our projects and online spaces to follow the Python Software Foundation\u2019s Code of Conduct.</p> <p>The Python community is made up of members from around the globe with a diverse set of skills, personalities, and experiences. It is through these differences that our community experiences great successes and continued growth. When you're working with members of the community, this Code of Conduct will help steer your interactions and keep Python a positive, successful, and growing community.</p>"},{"location":"code_of_conduct/#our-community","title":"Our Community","text":"<p>Members of the Python community are open, considerate, and respectful. Behaviours that reinforce these values contribute to a positive environment, and include:</p> <ul> <li>Being open. Members of the community are open to collaboration, whether it's on PEPs, patches, problems, or otherwise.</li> <li>Focusing on what is best for the community. We're respectful of the processes set forth in the community, and we work within them.</li> <li>Acknowledging time and effort. We're respectful of the volunteer efforts that permeate the Python community. We're thoughtful when addressing the efforts of others, keeping in mind that often times the labor was completed simply for the good of the community.</li> <li>Being respectful of differing viewpoints and experiences. We're receptive to constructive comments and criticism, as the experiences and skill sets of other members contribute to the whole of our efforts.</li> <li>Showing empathy towards other community members. We're attentive in our communications, whether in person or online, and we're tactful when approaching differing views.</li> <li>Being considerate. Members of the community are considerate of their peers -- other Python users.</li> <li>Being respectful. We're respectful of others, their positions, their skills, their commitments, and their efforts.</li> <li>Gracefully accepting constructive criticism. When we disagree, we are courteous in raising our issues.</li> <li>Using welcoming and inclusive language. We're accepting of all who wish to take part in our activities, fostering an environment where anyone can participate and everyone can make a difference.</li> </ul>"},{"location":"code_of_conduct/#our-standards","title":"Our Standards","text":"<p>Every member of our community has the right to have their identity respected. The Python community is dedicated to providing a positive experience for everyone, regardless of age, gender identity and expression, sexual orientation, disability, physical appearance, body size, ethnicity, nationality, race, or religion (or lack thereof), education, or socio-economic status.</p>"},{"location":"code_of_conduct/#inappropriate-behavior","title":"Inappropriate Behavior","text":"<p>Examples of unacceptable behavior by participants include:</p> <ul> <li>Harassment of any participants in any form</li> <li>Deliberate intimidation, stalking, or following</li> <li>Logging or taking screenshots of online activity for harassment purposes</li> <li>Publishing others' private information, such as a physical or electronic address, without explicit permission</li> <li>Violent threats or language directed against another person</li> <li>Incitement of violence or harassment towards any individual, including encouraging a person to commit suicide or to engage in self-harm</li> <li>Creating additional online accounts in order to harass another person or circumvent a ban</li> <li>Sexual language and imagery in online communities or in any conference venue, including talks</li> <li>Insults, put downs, or jokes that are based upon stereotypes, that are exclusionary, or that hold others up for ridicule</li> <li>Excessive swearing</li> <li>Unwelcome sexual attention or advances</li> <li>Unwelcome physical contact, including simulated physical contact (eg, textual descriptions like \"hug\" or \"backrub\") without consent or after a request to stop</li> <li>Pattern of inappropriate social contact, such as requesting/assuming inappropriate levels of intimacy with others</li> <li>Sustained disruption of online community discussions, in-person presentations, or other in-person events</li> <li>Continued one-on-one communication after requests to cease</li> <li>Other conduct that is inappropriate for a professional audience including people of many different backgrounds</li> </ul> <p>Community members asked to stop any inappropriate behavior are expected to comply immediately.</p>"},{"location":"code_of_conduct/#enforcement","title":"Enforcement","text":"<p>We take Code of Conduct violations seriously, and will act to ensure our spaces are welcoming, inclusive, and professional environments to communicate in.</p> <p>If you need to raise a Code of Conduct report, you may do so privately by email to tom@tomchristie.com.</p> <p>Reports will be treated confidentially.</p> <p>Alternately you may make a report to the Python Software Foundation.</p>"},{"location":"compatibility/","title":"Requests Compatibility Guide","text":"<p>HTTPX aims to be broadly compatible with the <code>requests</code> API, although there are a few design differences in places.</p> <p>This documentation outlines places where the API differs...</p>"},{"location":"compatibility/#redirects","title":"Redirects","text":"<p>Unlike <code>requests</code>, HTTPX does not follow redirects by default.</p> <p>We differ in behaviour here because auto-redirects can easily mask unnecessary network calls being made.</p> <p>You can still enable behaviour to automatically follow redirects, but you need to do so explicitly...</p> <pre><code>response = client.get(url, follow_redirects=True)\n</code></pre> <p>Or else instantiate a client, with redirect following enabled by default...</p> <pre><code>client = httpx.Client(follow_redirects=True)\n</code></pre>"},{"location":"compatibility/#client-instances","title":"Client instances","text":"<p>The HTTPX equivalent of <code>requests.Session</code> is <code>httpx.Client</code>.</p> <pre><code>session = requests.Session(**kwargs)\n</code></pre> <p>is generally equivalent to</p> <pre><code>client = httpx.Client(**kwargs)\n</code></pre>"},{"location":"compatibility/#request-urls","title":"Request URLs","text":"<p>Accessing <code>response.url</code> will return a <code>URL</code> instance, rather than a string.</p> <p>Use <code>str(response.url)</code> if you need a string instance.</p>"},{"location":"compatibility/#determining-the-next-redirect-request","title":"Determining the next redirect request","text":"<p>The <code>requests</code> library exposes an attribute <code>response.next</code>, which can be used to obtain the next redirect request.</p> <pre><code>session = requests.Session()\nrequest = requests.Request(\"GET\", ...).prepare()\nwhile request is not None:\n response = session.send(request, allow_redirects=False)\n request = response.next\n</code></pre> <p>In HTTPX, this attribute is instead named <code>response.next_request</code>. For example:</p> <pre><code>client = httpx.Client()\nrequest = client.build_request(\"GET\", ...)\nwhile request is not None:\n response = client.send(request)\n request = response.next_request\n</code></pre>"},{"location":"compatibility/#request-content","title":"Request Content","text":"<p>For uploading raw text or binary content we prefer to use a <code>content</code> parameter, in order to better separate this usage from the case of uploading form data.</p> <p>For example, using <code>content=...</code> to upload raw content:</p> <pre><code># Uploading text, bytes, or a bytes iterator.\nhttpx.post(..., content=b\"Hello, world\")\n</code></pre> <p>And using <code>data=...</code> to send form data:</p> <pre><code># Uploading form data.\nhttpx.post(..., data={\"message\": \"Hello, world\"})\n</code></pre> <p>Using the <code>data=<text/byte content></code> will raise a deprecation warning, and is expected to be fully removed with the HTTPX 1.0 release.</p>"},{"location":"compatibility/#upload-files","title":"Upload files","text":"<p>HTTPX strictly enforces that upload files must be opened in binary mode, in order to avoid character encoding issues that can result from attempting to upload files opened in text mode.</p>"},{"location":"compatibility/#content-encoding","title":"Content encoding","text":"<p>HTTPX uses <code>utf-8</code> for encoding <code>str</code> request bodies. For example, when using <code>content=<str></code> the request body will be encoded to <code>utf-8</code> before being sent over the wire. This differs from Requests which uses <code>latin1</code>. If you need an explicit encoding, pass encoded bytes explicitly, e.g. <code>content=<str>.encode(\"latin1\")</code>. For response bodies, assuming the server didn't send an explicit encoding then HTTPX will do its best to figure out an appropriate encoding. HTTPX makes a guess at the encoding to use for decoding the response using <code>charset_normalizer</code>. Fallback to that or any content with less than 32 octets will be decoded using <code>utf-8</code> with the <code>error=\"replace\"</code> decoder strategy.</p>"},{"location":"compatibility/#cookies","title":"Cookies","text":"<p>If using a client instance, then cookies should always be set on the client rather than on a per-request basis.</p> <p>This usage is supported:</p> <pre><code>client = httpx.Client(cookies=...)\nclient.post(...)\n</code></pre> <p>This usage is not supported:</p> <pre><code>client = httpx.Client()\nclient.post(..., cookies=...)\n</code></pre> <p>We prefer enforcing a stricter API here because it provides clearer expectations around cookie persistence, particularly when redirects occur.</p>"},{"location":"compatibility/#status-codes","title":"Status Codes","text":"<p>In our documentation we prefer the uppercased versions, such as <code>codes.NOT_FOUND</code>, but also provide lower-cased versions for API compatibility with <code>requests</code>.</p> <p>Requests includes various synonyms for status codes that HTTPX does not support.</p>"},{"location":"compatibility/#streaming-responses","title":"Streaming responses","text":"<p>HTTPX provides a <code>.stream()</code> interface rather than using <code>stream=True</code>. This ensures that streaming responses are always properly closed outside of the stream block, and makes it visually clearer at which points streaming I/O APIs may be used with a response.</p> <p>For example:</p> <pre><code>with httpx.stream(\"GET\", \"https://www.example.com\") as response:\n ...\n</code></pre> <p>Within a <code>stream()</code> block request data is made available with:</p> <ul> <li><code>.iter_bytes()</code> - Instead of <code>response.iter_content()</code></li> <li><code>.iter_text()</code> - Instead of <code>response.iter_content(decode_unicode=True)</code></li> <li><code>.iter_lines()</code> - Corresponding to <code>response.iter_lines()</code></li> <li><code>.iter_raw()</code> - Use this instead of <code>response.raw</code></li> <li><code>.read()</code> - Read the entire response body, making <code>response.text</code> and <code>response.content</code> available.</li> </ul>"},{"location":"compatibility/#timeouts","title":"Timeouts","text":"<p>HTTPX defaults to including reasonable timeouts for all network operations, while Requests has no timeouts by default.</p> <p>To get the same behavior as Requests, set the <code>timeout</code> parameter to <code>None</code>:</p> <pre><code>httpx.get('https://www.example.com', timeout=None)\n</code></pre>"},{"location":"compatibility/#proxy-keys","title":"Proxy keys","text":"<p>HTTPX uses the mounts argument for HTTP proxying and transport routing. It can do much more than proxies and allows you to configure more than just the proxy route. For more detailed documentation, see Mounting Transports.</p> <p>When using <code>httpx.Client(mounts={...})</code> to map to a selection of different transports, we use full URL schemes, such as <code>mounts={\"http://\": ..., \"https://\": ...}</code>.</p> <p>This is different to the <code>requests</code> usage of <code>proxies={\"http\": ..., \"https\": ...}</code>.</p> <p>This change is for better consistency with more complex mappings, that might also include domain names, such as <code>mounts={\"all://\": ..., httpx.HTTPTransport(proxy=\"all://www.example.com\": None})</code> which maps all requests onto a proxy, except for requests to \"www.example.com\" which have an explicit exclusion.</p> <p>Also note that <code>requests.Session.request(...)</code> allows a <code>proxies=...</code> parameter, whereas <code>httpx.Client.request(...)</code> does not allow <code>mounts=...</code>.</p>"},{"location":"compatibility/#ssl-configuration","title":"SSL configuration","text":"<p>When using a <code>Client</code> instance, the ssl configurations should always be passed on client instantiation, rather than passed to the request method.</p> <p>If you need more than one different SSL configuration, you should use different client instances for each SSL configuration.</p>"},{"location":"compatibility/#request-body-on-http-methods","title":"Request body on HTTP methods","text":"<p>The HTTP <code>GET</code>, <code>DELETE</code>, <code>HEAD</code>, and <code>OPTIONS</code> methods are specified as not supporting a request body. To stay in line with this, the <code>.get</code>, <code>.delete</code>, <code>.head</code> and <code>.options</code> functions do not support <code>content</code>, <code>files</code>, <code>data</code>, or <code>json</code> arguments.</p> <p>If you really do need to send request data using these http methods you should use the generic <code>.request</code> function instead.</p> <pre><code>httpx.request(\n method=\"DELETE\",\n url=\"https://www.example.com/\",\n content=b'A request body on a DELETE request.'\n)\n</code></pre>"},{"location":"compatibility/#checking-for-success-and-failure-responses","title":"Checking for success and failure responses","text":"<p>We don't support <code>response.is_ok</code> since the naming is ambiguous there, and might incorrectly imply an equivalence to <code>response.status_code == codes.OK</code>. Instead we provide the <code>response.is_success</code> property, which can be used to check for a 2xx response.</p>"},{"location":"compatibility/#request-instantiation","title":"Request instantiation","text":"<p>There is no notion of prepared requests in HTTPX. If you need to customize request instantiation, see Request instances.</p> <p>Besides, <code>httpx.Request()</code> does not support the <code>auth</code>, <code>timeout</code>, <code>follow_redirects</code>, <code>mounts</code>, <code>verify</code> and <code>cert</code> parameters. However these are available in <code>httpx.request</code>, <code>httpx.get</code>, <code>httpx.post</code> etc., as well as on <code>Client</code> instances.</p>"},{"location":"compatibility/#mocking","title":"Mocking","text":"<p>If you need to mock HTTPX the same way that test utilities like <code>responses</code> and <code>requests-mock</code> does for <code>requests</code>, see RESPX.</p>"},{"location":"compatibility/#caching","title":"Caching","text":"<p>If you use <code>cachecontrol</code> or <code>requests-cache</code> to add HTTP Caching support to the <code>requests</code> library, you can use Hishel for HTTPX.</p>"},{"location":"compatibility/#networking-layer","title":"Networking layer","text":"<p><code>requests</code> defers most of its HTTP networking code to the excellent <code>urllib3</code> library.</p> <p>On the other hand, HTTPX uses HTTPCore as its core HTTP networking layer, which is a different project than <code>urllib3</code>.</p>"},{"location":"compatibility/#query-parameters","title":"Query Parameters","text":"<p><code>requests</code> omits <code>params</code> whose values are <code>None</code> (e.g. <code>requests.get(..., params={\"foo\": None})</code>). This is not supported by HTTPX.</p> <p>For both query params (<code>params=</code>) and form data (<code>data=</code>), <code>requests</code> supports sending a list of tuples (e.g. <code>requests.get(..., params=[('key1', 'value1'), ('key1', 'value2')])</code>). This is not supported by HTTPX. Instead, use a dictionary with lists as values. E.g.: <code>httpx.get(..., params={'key1': ['value1', 'value2']})</code> or with form data: <code>httpx.post(..., data={'key1': ['value1', 'value2']})</code>.</p>"},{"location":"compatibility/#event-hooks","title":"Event Hooks","text":"<p><code>requests</code> allows event hooks to mutate <code>Request</code> and <code>Response</code> objects. See examples given in the documentation for <code>requests</code>.</p> <p>In HTTPX, event hooks may access properties of requests and responses, but event hook callbacks cannot mutate the original request/response.</p> <p>If you are looking for more control, consider checking out Custom Transports.</p>"},{"location":"contributing/","title":"Contributing","text":"<p>Thank you for being interested in contributing to HTTPX. There are many ways you can contribute to the project:</p> <ul> <li>Try HTTPX and report bugs/issues you find</li> <li>Implement new features</li> <li>Review Pull Requests of others</li> <li>Write documentation</li> <li>Participate in discussions</li> </ul>"},{"location":"contributing/#reporting-bugs-or-other-issues","title":"Reporting Bugs or Other Issues","text":"<p>Found something that HTTPX should support? Stumbled upon some unexpected behaviour?</p> <p>Contributions should generally start out with a discussion. Possible bugs may be raised as a \"Potential Issue\" discussion, feature requests may be raised as an \"Ideas\" discussion. We can then determine if the discussion needs to be escalated into an \"Issue\" or not, or if we'd consider a pull request.</p> <p>Try to be more descriptive as you can and in case of a bug report, provide as much information as possible like:</p> <ul> <li>OS platform</li> <li>Python version</li> <li>Installed dependencies and versions (<code>python -m pip freeze</code>)</li> <li>Code snippet</li> <li>Error traceback</li> </ul> <p>You should always try to reduce any examples to the simplest possible case that demonstrates the issue.</p> <p>Some possibly useful tips for narrowing down potential issues...</p> <ul> <li>Does the issue exist on HTTP/1.1, or HTTP/2, or both?</li> <li>Does the issue exist with <code>Client</code>, <code>AsyncClient</code>, or both?</li> <li>When using <code>AsyncClient</code> does the issue exist when using <code>asyncio</code> or <code>trio</code>, or both?</li> </ul>"},{"location":"contributing/#development","title":"Development","text":"<p>To start developing HTTPX create a fork of the HTTPX repository on GitHub.</p> <p>Then clone your fork with the following command replacing <code>YOUR-USERNAME</code> with your GitHub username:</p> <pre><code>$ git clone https://github.com/YOUR-USERNAME/httpx\n</code></pre> <p>You can now install the project and its dependencies using:</p> <pre><code>$ cd httpx\n$ scripts/install\n</code></pre>"},{"location":"contributing/#testing-and-linting","title":"Testing and Linting","text":"<p>We use custom shell scripts to automate testing, linting, and documentation building workflow.</p> <p>To run the tests, use:</p> <pre><code>$ scripts/test\n</code></pre> <p>Warning</p> <p>The test suite spawns testing servers on ports 8000 and 8001. Make sure these are not in use, so the tests can run properly.</p> <p>Any additional arguments will be passed to <code>pytest</code>. See the pytest documentation for more information.</p> <p>For example, to run a single test script:</p> <pre><code>$ scripts/test tests/test_multipart.py\n</code></pre> <p>To run the code auto-formatting:</p> <pre><code>$ scripts/lint\n</code></pre> <p>Lastly, to run code checks separately (they are also run as part of <code>scripts/test</code>), run:</p> <pre><code>$ scripts/check\n</code></pre>"},{"location":"contributing/#documenting","title":"Documenting","text":"<p>Documentation pages are located under the <code>docs/</code> folder.</p> <p>To run the documentation site locally (useful for previewing changes), use:</p> <pre><code>$ scripts/docs\n</code></pre>"},{"location":"contributing/#resolving-build-ci-failures","title":"Resolving Build / CI Failures","text":"<p>Once you've submitted your pull request, the test suite will automatically run, and the results will show up in GitHub. If the test suite fails, you'll want to click through to the \"Details\" link, and try to identify why the test suite failed.</p> <p> </p> <p>Here are some common ways the test suite can fail:</p>"},{"location":"contributing/#check-job-failed","title":"Check Job Failed","text":"<p>This job failing means there is either a code formatting issue or type-annotation issue. You can look at the job output to figure out why it's failed or within a shell run:</p> <pre><code>$ scripts/check\n</code></pre> <p>It may be worth it to run <code>$ scripts/lint</code> to attempt auto-formatting the code and if that job succeeds commit the changes.</p>"},{"location":"contributing/#docs-job-failed","title":"Docs Job Failed","text":"<p>This job failing means the documentation failed to build. This can happen for a variety of reasons like invalid markdown or missing configuration within <code>mkdocs.yml</code>.</p>"},{"location":"contributing/#python-3x-job-failed","title":"Python 3.X Job Failed","text":"<p>This job failing means the unit tests failed or not all code paths are covered by unit tests.</p> <p>If tests are failing you will see this message under the coverage report:</p> <p><code>=== 1 failed, 435 passed, 1 skipped, 1 xfailed in 11.09s ===</code></p> <p>If tests succeed but coverage doesn't reach our current threshold, you will see this message under the coverage report:</p> <p><code>FAIL Required test coverage of 100% not reached. Total coverage: 99.00%</code></p>"},{"location":"contributing/#releasing","title":"Releasing","text":"<p>This section is targeted at HTTPX maintainers.</p> <p>Before releasing a new version, create a pull request that includes:</p> <ul> <li>An update to the changelog:<ul> <li>We follow the format from keepachangelog.</li> <li>Compare <code>master</code> with the tag of the latest release, and list all entries that are of interest to our users:<ul> <li>Things that must go in the changelog: added, changed, deprecated or removed features, and bug fixes.</li> <li>Things that should not go in the changelog: changes to documentation, tests or tooling.</li> <li>Try sorting entries in descending order of impact / importance.</li> <li>Keep it concise and to-the-point. \ud83c\udfaf</li> </ul> </li> </ul> </li> <li>A version bump: see <code>__version__.py</code>.</li> </ul> <p>For an example, see #1006.</p> <p>Once the release PR is merged, create a new release including:</p> <ul> <li>Tag version like <code>0.13.3</code>.</li> <li>Release title <code>Version 0.13.3</code></li> <li>Description copied from the changelog.</li> </ul> <p>Once created this release will be automatically uploaded to PyPI.</p> <p>If something goes wrong with the PyPI job the release can be published using the <code>scripts/publish</code> script.</p>"},{"location":"contributing/#development-proxy-setup","title":"Development proxy setup","text":"<p>To test and debug requests via a proxy it's best to run a proxy server locally. Any server should do but HTTPCore's test suite uses <code>mitmproxy</code> which is written in Python, it's fully featured and has excellent UI and tools for introspection of requests.</p> <p>You can install <code>mitmproxy</code> using <code>pip install mitmproxy</code> or several other ways.</p> <p><code>mitmproxy</code> does require setting up local TLS certificates for HTTPS requests, as its main purpose is to allow developers to inspect requests that pass through it. We can set them up follows:</p> <ol> <li><code>pip install trustme-cli</code>.</li> <li><code>trustme-cli -i example.org www.example.org</code>, assuming you want to test connecting to that domain, this will create three files: <code>server.pem</code>, <code>server.key</code> and <code>client.pem</code>.</li> <li><code>mitmproxy</code> requires a PEM file that includes the private key and the certificate so we need to concatenate them: <code>cat server.key server.pem > server.withkey.pem</code>.</li> <li>Start the proxy server <code>mitmproxy --certs server.withkey.pem</code>, or use the other mitmproxy commands with different UI options.</li> </ol> <p>At this point the server is ready to start serving requests, you'll need to configure HTTPX as described in the proxy section and the SSL certificates section, this is where our previously generated <code>client.pem</code> comes in:</p> <pre><code>ctx = ssl.create_default_context(cafile=\"/path/to/client.pem\")\nclient = httpx.Client(proxy=\"http://127.0.0.1:8080/\", verify=ctx)\n</code></pre> <p>Note, however, that HTTPS requests will only succeed to the host specified in the SSL/TLS certificate we generated, HTTPS requests to other hosts will raise an error like:</p> <pre><code>ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate\nverify failed: Hostname mismatch, certificate is not valid for\n'duckduckgo.com'. (_ssl.c:1108)\n</code></pre> <p>If you want to make requests to more hosts you'll need to regenerate the certificates and include all the hosts you intend to connect to in the seconds step, i.e.</p> <p><code>trustme-cli -i example.org www.example.org duckduckgo.com www.duckduckgo.com</code></p>"},{"location":"environment_variables/","title":"Environment Variables","text":"<p>The HTTPX library can be configured via environment variables. Environment variables are used by default. To ignore environment variables, <code>trust_env</code> has to be set <code>False</code>. There are two ways to set <code>trust_env</code> to disable environment variables:</p> <ul> <li>On the client via <code>httpx.Client(trust_env=False)</code>.</li> <li>Using the top-level API, such as <code>httpx.get(\"<url>\", trust_env=False)</code>.</li> </ul> <p>Here is a list of environment variables that HTTPX recognizes and what function they serve:</p>"},{"location":"environment_variables/#proxies","title":"Proxies","text":"<p>The environment variables documented below are used as a convention by various HTTP tooling, including:</p> <ul> <li>cURL</li> <li>requests</li> </ul> <p>For more information on using proxies in HTTPX, see HTTP Proxying.</p>"},{"location":"environment_variables/#http_proxy-https_proxy-all_proxy","title":"<code>HTTP_PROXY</code>, <code>HTTPS_PROXY</code>, <code>ALL_PROXY</code>","text":"<p>Valid values: A URL to a proxy</p> <p><code>HTTP_PROXY</code>, <code>HTTPS_PROXY</code>, <code>ALL_PROXY</code> set the proxy to be used for <code>http</code>, <code>https</code>, or all requests respectively.</p> <pre><code>export HTTP_PROXY=http://my-external-proxy.com:1234\n\n# This request will be sent through the proxy\npython -c \"import httpx; httpx.get('http://example.com')\"\n\n# This request will be sent directly, as we set `trust_env=False`\npython -c \"import httpx; httpx.get('http://example.com', trust_env=False)\"\n</code></pre>"},{"location":"environment_variables/#no_proxy","title":"<code>NO_PROXY</code>","text":"<p>Valid values: a comma-separated list of hostnames/urls</p> <p><code>NO_PROXY</code> disables the proxy for specific urls</p> <pre><code>export HTTP_PROXY=http://my-external-proxy.com:1234\nexport NO_PROXY=http://127.0.0.1,python-httpx.org\n\n# As in the previous example, this request will be sent through the proxy\npython -c \"import httpx; httpx.get('http://example.com')\"\n\n# These requests will be sent directly, bypassing the proxy\npython -c \"import httpx; httpx.get('http://127.0.0.1:5000/my-api')\"\npython -c \"import httpx; httpx.get('https://www.python-httpx.org')\"\n</code></pre>"},{"location":"exceptions/","title":"Exceptions","text":"<p>This page lists exceptions that may be raised when using HTTPX.</p> <p>For an overview of how to work with HTTPX exceptions, see Exceptions (Quickstart).</p>"},{"location":"exceptions/#the-exception-hierarchy","title":"The exception hierarchy","text":"<ul> <li>HTTPError<ul> <li>RequestError<ul> <li>TransportError<ul> <li>TimeoutException<ul> <li>ConnectTimeout</li> <li>ReadTimeout</li> <li>WriteTimeout</li> <li>PoolTimeout</li> </ul> </li> <li>NetworkError<ul> <li>ConnectError</li> <li>ReadError</li> <li>WriteError</li> <li>CloseError</li> </ul> </li> <li>ProtocolError<ul> <li>LocalProtocolError</li> <li>RemoteProtocolError</li> </ul> </li> <li>ProxyError</li> <li>UnsupportedProtocol</li> </ul> </li> <li>DecodingError</li> <li>TooManyRedirects</li> </ul> </li> <li>HTTPStatusError</li> </ul> </li> <li>InvalidURL</li> <li>CookieConflict</li> <li>StreamError<ul> <li>StreamConsumed</li> <li>ResponseNotRead</li> <li>RequestNotRead</li> <li>StreamClosed</li> </ul> </li> </ul>"},{"location":"exceptions/#exception-classes","title":"Exception classes","text":"class <code>httpx.HTTPError</code>(message) <p>Base class for <code>RequestError</code> and <code>HTTPStatusError</code>.</p> <p>Useful for <code>try...except</code> blocks when issuing a request, and then calling <code>.raise_for_status()</code>.</p> <p>For example:</p> <pre><code>try:\n response = httpx.get(\"https://www.example.com\")\n response.raise_for_status()\nexcept httpx.HTTPError as exc:\n print(f\"HTTP Exception for {exc.request.url} - {exc}\")\n</code></pre> class <code>httpx.RequestError</code>(message, *, request=None) <p>Base class for all exceptions that may occur when issuing a <code>.request()</code>.</p> class <code>httpx.TransportError</code>(message, *, request=None) <p>Base class for all exceptions that occur at the level of the Transport API.</p> class <code>httpx.TimeoutException</code>(message, *, request=None) <p>The base class for timeout errors.</p> <p>An operation has timed out.</p> class <code>httpx.ConnectTimeout</code>(message, *, request=None) <p>Timed out while connecting to the host.</p> class <code>httpx.ReadTimeout</code>(message, *, request=None) <p>Timed out while receiving data from the host.</p> class <code>httpx.WriteTimeout</code>(message, *, request=None) <p>Timed out while sending data to the host.</p> class <code>httpx.PoolTimeout</code>(message, *, request=None) <p>Timed out waiting to acquire a connection from the pool.</p> class <code>httpx.NetworkError</code>(message, *, request=None) <p>The base class for network-related errors.</p> <p>An error occurred while interacting with the network.</p> class <code>httpx.ConnectError</code>(message, *, request=None) <p>Failed to establish a connection.</p> class <code>httpx.ReadError</code>(message, *, request=None) <p>Failed to receive data from the network.</p> class <code>httpx.WriteError</code>(message, *, request=None) <p>Failed to send data through the network.</p> class <code>httpx.CloseError</code>(message, *, request=None) <p>Failed to close a connection.</p> class <code>httpx.ProtocolError</code>(message, *, request=None) <p>The protocol was violated.</p> class <code>httpx.LocalProtocolError</code>(message, *, request=None) <p>A protocol was violated by the client.</p> <p>For example if the user instantiated a <code>Request</code> instance explicitly, failed to include the mandatory <code>Host:</code> header, and then issued it directly using <code>client.send()</code>.</p> class <code>httpx.RemoteProtocolError</code>(message, *, request=None) <p>The protocol was violated by the server.</p> <p>For example, returning malformed HTTP.</p> class <code>httpx.ProxyError</code>(message, *, request=None) <p>An error occurred while establishing a proxy connection.</p> class <code>httpx.UnsupportedProtocol</code>(message, *, request=None) <p>Attempted to make a request to an unsupported protocol.</p> <p>For example issuing a request to <code>ftp://www.example.com</code>.</p> class <code>httpx.DecodingError</code>(message, *, request=None) <p>Decoding of the response failed, due to a malformed encoding.</p> class <code>httpx.TooManyRedirects</code>(message, *, request=None) <p>Too many redirects.</p> class <code>httpx.HTTPStatusError</code>(message, *, request, response) <p>The response had an error HTTP status of 4xx or 5xx.</p> <p>May be raised when calling <code>response.raise_for_status()</code></p> class <code>httpx.InvalidURL</code>(message) <p>URL is improperly formed or cannot be parsed.</p> class <code>httpx.CookieConflict</code>(message) <p>Attempted to lookup a cookie by name, but multiple cookies existed.</p> <p>Can occur when calling <code>response.cookies.get(...)</code>.</p> class <code>httpx.StreamError</code>(message) <p>The base class for stream exceptions.</p> <p>The developer made an error in accessing the request stream in an invalid way.</p> class <code>httpx.StreamConsumed</code>() <p>Attempted to read or stream content, but the content has already been streamed.</p> class <code>httpx.StreamClosed</code>() <p>Attempted to read or stream response content, but the request has been closed.</p> class <code>httpx.ResponseNotRead</code>() <p>Attempted to access streaming response content, without having called <code>read()</code>.</p> class <code>httpx.RequestNotRead</code>() <p>Attempted to access streaming request content, without having called <code>read()</code>.</p>"},{"location":"http2/","title":"HTTP/2","text":"<p>HTTP/2 is a major new iteration of the HTTP protocol, that provides a far more efficient transport, with potential performance benefits. HTTP/2 does not change the core semantics of the request or response, but alters the way that data is sent to and from the server.</p> <p>Rather than the text format that HTTP/1.1 uses, HTTP/2 is a binary format. The binary format provides full request and response multiplexing, and efficient compression of HTTP headers. The stream multiplexing means that where HTTP/1.1 requires one TCP stream for each concurrent request, HTTP/2 allows a single TCP stream to handle multiple concurrent requests.</p> <p>HTTP/2 also provides support for functionality such as response prioritization, and server push.</p> <p>For a comprehensive guide to HTTP/2 you may want to check out \"http2 explained\".</p>"},{"location":"http2/#enabling-http2","title":"Enabling HTTP/2","text":"<p>When using the <code>httpx</code> client, HTTP/2 support is not enabled by default, because HTTP/1.1 is a mature, battle-hardened transport layer, and our HTTP/1.1 implementation may be considered the more robust option at this point in time. It is possible that a future version of <code>httpx</code> may enable HTTP/2 support by default.</p> <p>If you're issuing highly concurrent requests you might want to consider trying out our HTTP/2 support. You can do so by first making sure to install the optional HTTP/2 dependencies...</p> <pre><code>$ pip install httpx[http2]\n</code></pre> <p>And then instantiating a client with HTTP/2 support enabled:</p> <pre><code>client = httpx.AsyncClient(http2=True)\n...\n</code></pre> <p>You can also instantiate a client as a context manager, to ensure that all HTTP connections are nicely scoped, and will be closed once the context block is exited.</p> <pre><code>async with httpx.AsyncClient(http2=True) as client:\n ...\n</code></pre> <p>HTTP/2 support is available on both <code>Client</code> and <code>AsyncClient</code>, although it's typically more useful in async contexts if you're issuing lots of concurrent requests.</p>"},{"location":"http2/#inspecting-the-http-version","title":"Inspecting the HTTP version","text":"<p>Enabling HTTP/2 support on the client does not necessarily mean that your requests and responses will be transported over HTTP/2, since both the client and the server need to support HTTP/2. If you connect to a server that only supports HTTP/1.1 the client will use a standard HTTP/1.1 connection instead.</p> <p>You can determine which version of the HTTP protocol was used by examining the <code>.http_version</code> property on the response.</p> <pre><code>client = httpx.AsyncClient(http2=True)\nresponse = await client.get(...)\nprint(response.http_version) # \"HTTP/1.0\", \"HTTP/1.1\", or \"HTTP/2\".\n</code></pre>"},{"location":"logging/","title":"Logging","text":"<p>If you need to inspect the internal behaviour of <code>httpx</code>, you can use Python's standard logging to output information about the underlying network behaviour.</p> <p>For example, the following configuration...</p> <pre><code>import logging\nimport httpx\n\nlogging.basicConfig(\n format=\"%(levelname)s [%(asctime)s] %(name)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n level=logging.DEBUG\n)\n\nhttpx.get(\"https://www.example.com\")\n</code></pre> <p>Will send debug level output to the console, or wherever <code>stdout</code> is directed too...</p> <pre><code>DEBUG [2024-09-28 17:27:40] httpx - load_ssl_context verify=True cert=None\nDEBUG [2024-09-28 17:27:40] httpx - load_verify_locations cafile='/Users/karenpetrosyan/oss/karhttpx/.venv/lib/python3.9/site-packages/certifi/cacert.pem'\nDEBUG [2024-09-28 17:27:40] httpcore.connection - connect_tcp.started host='www.example.com' port=443 local_address=None timeout=5.0 socket_options=None\nDEBUG [2024-09-28 17:27:41] httpcore.connection - connect_tcp.complete return_value=<httpcore._backends.sync.SyncStream object at 0x101f1e8e0>\nDEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.started ssl_context=SSLContext(verify=True) server_hostname='www.example.com' timeout=5.0\nDEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.complete return_value=<httpcore._backends.sync.SyncStream object at 0x1020f49a0>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.started request=<Request [b'GET']>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.complete\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.started request=<Request [b'GET']>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.complete\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_headers.started request=<Request [b'GET']>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Content-Encoding', b'gzip'), (b'Accept-Ranges', b'bytes'), (b'Age', b'407727'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Sat, 28 Sep 2024 13:27:42 GMT'), (b'Etag', b'\"3147526947+gzip\"'), (b'Expires', b'Sat, 05 Oct 2024 13:27:42 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECAcc (dcd/7D43)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'648')])\nINFO [2024-09-28 17:27:41] httpx - HTTP Request: GET https://www.example.com \"HTTP/1.1 200 OK\"\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.started request=<Request [b'GET']>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.complete\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.started\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.complete\nDEBUG [2024-09-28 17:27:41] httpcore.connection - close.started\nDEBUG [2024-09-28 17:27:41] httpcore.connection - close.complete\n</code></pre> <p>Logging output includes information from both the high-level <code>httpx</code> logger, and the network-level <code>httpcore</code> logger, which can be configured separately.</p> <p>For handling more complex logging configurations you might want to use the dictionary configuration style...</p> <pre><code>import logging.config\nimport httpx\n\nLOGGING_CONFIG = {\n \"version\": 1,\n \"handlers\": {\n \"default\": {\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"http\",\n \"stream\": \"ext://sys.stderr\"\n }\n },\n \"formatters\": {\n \"http\": {\n \"format\": \"%(levelname)s [%(asctime)s] %(name)s - %(message)s\",\n \"datefmt\": \"%Y-%m-%d %H:%M:%S\",\n }\n },\n 'loggers': {\n 'httpx': {\n 'handlers': ['default'],\n 'level': 'DEBUG',\n },\n 'httpcore': {\n 'handlers': ['default'],\n 'level': 'DEBUG',\n },\n }\n}\n\nlogging.config.dictConfig(LOGGING_CONFIG)\nhttpx.get('https://www.example.com')\n</code></pre> <p>The exact formatting of the debug logging may be subject to change across different versions of <code>httpx</code> and <code>httpcore</code>. If you need to rely on a particular format it is recommended that you pin installation of these packages to fixed versions.</p>"},{"location":"quickstart/","title":"QuickStart","text":"<p>First, start by importing HTTPX:</p> <pre><code>>>> import httpx\n</code></pre> <p>Now, let\u2019s try to get a webpage.</p> <pre><code>>>> r = httpx.get('https://httpbin.org/get')\n>>> r\n<Response [200 OK]>\n</code></pre> <p>Similarly, to make an HTTP POST request:</p> <pre><code>>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})\n</code></pre> <p>The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:</p> <pre><code>>>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})\n>>> r = httpx.delete('https://httpbin.org/delete')\n>>> r = httpx.head('https://httpbin.org/get')\n>>> r = httpx.options('https://httpbin.org/get')\n</code></pre>"},{"location":"quickstart/#passing-parameters-in-urls","title":"Passing Parameters in URLs","text":"<p>To include URL query parameters in the request, use the <code>params</code> keyword:</p> <pre><code>>>> params = {'key1': 'value1', 'key2': 'value2'}\n>>> r = httpx.get('https://httpbin.org/get', params=params)\n</code></pre> <p>To see how the values get encoding into the URL string, we can inspect the resulting URL that was used to make the request:</p> <pre><code>>>> r.url\nURL('https://httpbin.org/get?key2=value2&key1=value1')\n</code></pre> <p>You can also pass a list of items as a value:</p> <pre><code>>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}\n>>> r = httpx.get('https://httpbin.org/get', params=params)\n>>> r.url\nURL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')\n</code></pre>"},{"location":"quickstart/#response-content","title":"Response Content","text":"<p>HTTPX will automatically handle decoding the response content into Unicode text.</p> <pre><code>>>> r = httpx.get('https://www.example.org/')\n>>> r.text\n'<!doctype html>\\n<html>\\n<head>\\n<title>Example Domain</title>...'\n</code></pre> <p>You can inspect what encoding will be used to decode the response.</p> <pre><code>>>> r.encoding\n'UTF-8'\n</code></pre> <p>In some cases the response may not contain an explicit encoding, in which case HTTPX will attempt to automatically determine an encoding to use.</p> <pre><code>>>> r.encoding\nNone\n>>> r.text\n'<!doctype html>\\n<html>\\n<head>\\n<title>Example Domain</title>...'\n</code></pre> <p>If you need to override the standard behaviour and explicitly set the encoding to use, then you can do that too.</p> <pre><code>>>> r.encoding = 'ISO-8859-1'\n</code></pre>"},{"location":"quickstart/#binary-response-content","title":"Binary Response Content","text":"<p>The response content can also be accessed as bytes, for non-text responses:</p> <pre><code>>>> r.content\nb'<!doctype html>\\n<html>\\n<head>\\n<title>Example Domain</title>...'\n</code></pre> <p>Any <code>gzip</code> and <code>deflate</code> HTTP response encodings will automatically be decoded for you. If <code>brotlipy</code> is installed, then the <code>brotli</code> response encoding will be supported. If <code>zstandard</code> is installed, then <code>zstd</code> response encodings will also be supported.</p> <p>For example, to create an image from binary data returned by a request, you can use the following code:</p> <pre><code>>>> from PIL import Image\n>>> from io import BytesIO\n>>> i = Image.open(BytesIO(r.content))\n</code></pre>"},{"location":"quickstart/#json-response-content","title":"JSON Response Content","text":"<p>Often Web API responses will be encoded as JSON.</p> <pre><code>>>> r = httpx.get('https://api.github.com/events')\n>>> r.json()\n[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]\n</code></pre>"},{"location":"quickstart/#custom-headers","title":"Custom Headers","text":"<p>To include additional headers in the outgoing request, use the <code>headers</code> keyword argument:</p> <pre><code>>>> url = 'https://httpbin.org/headers'\n>>> headers = {'user-agent': 'my-app/0.0.1'}\n>>> r = httpx.get(url, headers=headers)\n</code></pre>"},{"location":"quickstart/#sending-form-encoded-data","title":"Sending Form Encoded Data","text":"<p>Some types of HTTP requests, such as <code>POST</code> and <code>PUT</code> requests, can include data in the request body. One common way of including that is as form-encoded data, which is used for HTML forms.</p> <pre><code>>>> data = {'key1': 'value1', 'key2': 'value2'}\n>>> r = httpx.post(\"https://httpbin.org/post\", data=data)\n>>> print(r.text)\n{\n ...\n \"form\": {\n \"key2\": \"value2\",\n \"key1\": \"value1\"\n },\n ...\n}\n</code></pre> <p>Form encoded data can also include multiple values from a given key.</p> <pre><code>>>> data = {'key1': ['value1', 'value2']}\n>>> r = httpx.post(\"https://httpbin.org/post\", data=data)\n>>> print(r.text)\n{\n ...\n \"form\": {\n \"key1\": [\n \"value1\",\n \"value2\"\n ]\n },\n ...\n}\n</code></pre>"},{"location":"quickstart/#sending-multipart-file-uploads","title":"Sending Multipart File Uploads","text":"<p>You can also upload files, using HTTP multipart encoding:</p> <pre><code>>>> files = {'upload-file': open('report.xls', 'rb')}\n>>> r = httpx.post(\"https://httpbin.org/post\", files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {\n \"upload-file\": \"<... binary content ...>\"\n },\n ...\n}\n</code></pre> <p>You can also explicitly set the filename and content type, by using a tuple of items for the file value:</p> <pre><code>>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}\n>>> r = httpx.post(\"https://httpbin.org/post\", files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {\n \"upload-file\": \"<... binary content ...>\"\n },\n ...\n}\n</code></pre> <p>If you need to include non-file data fields in the multipart form, use the <code>data=...</code> parameter:</p> <pre><code>>>> data = {'message': 'Hello, world!'}\n>>> files = {'file': open('report.xls', 'rb')}\n>>> r = httpx.post(\"https://httpbin.org/post\", data=data, files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {\n \"file\": \"<... binary content ...>\"\n },\n \"form\": {\n \"message\": \"Hello, world!\",\n },\n ...\n}\n</code></pre>"},{"location":"quickstart/#sending-json-encoded-data","title":"Sending JSON Encoded Data","text":"<p>Form encoded data is okay if all you need is a simple key-value data structure. For more complicated data structures you'll often want to use JSON encoding instead.</p> <pre><code>>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}\n>>> r = httpx.post(\"https://httpbin.org/post\", json=data)\n>>> print(r.text)\n{\n ...\n \"json\": {\n \"boolean\": true,\n \"integer\": 123,\n \"list\": [\n \"a\",\n \"b\",\n \"c\"\n ]\n },\n ...\n}\n</code></pre>"},{"location":"quickstart/#sending-binary-request-data","title":"Sending Binary Request Data","text":"<p>For other encodings, you should use the <code>content=...</code> parameter, passing either a <code>bytes</code> type or a generator that yields <code>bytes</code>.</p> <pre><code>>>> content = b'Hello, world'\n>>> r = httpx.post(\"https://httpbin.org/post\", content=content)\n</code></pre> <p>You may also want to set a custom <code>Content-Type</code> header when uploading binary data.</p>"},{"location":"quickstart/#response-status-codes","title":"Response Status Codes","text":"<p>We can inspect the HTTP status code of the response:</p> <pre><code>>>> r = httpx.get('https://httpbin.org/get')\n>>> r.status_code\n200\n</code></pre> <p>HTTPX also includes an easy shortcut for accessing status codes by their text phrase.</p> <pre><code>>>> r.status_code == httpx.codes.OK\nTrue\n</code></pre> <p>We can raise an exception for any responses which are not a 2xx success code:</p> <pre><code>>>> not_found = httpx.get('https://httpbin.org/status/404')\n>>> not_found.status_code\n404\n>>> not_found.raise_for_status()\nTraceback (most recent call last):\n File \"/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py\", line 837, in raise_for_status\n raise HTTPStatusError(message, response=self)\nhttpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404\nFor more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404\n</code></pre> <p>Any successful response codes will return the <code>Response</code> instance rather than raising an exception.</p> <pre><code>>>> r.raise_for_status()\n</code></pre> <p>The method returns the response instance, allowing you to use it inline. For example:</p> <pre><code>>>> r = httpx.get('...').raise_for_status()\n>>> data = httpx.get('...').raise_for_status().json()\n</code></pre>"},{"location":"quickstart/#response-headers","title":"Response Headers","text":"<p>The response headers are available as a dictionary-like interface.</p> <pre><code>>>> r.headers\nHeaders({\n 'content-encoding': 'gzip',\n 'transfer-encoding': 'chunked',\n 'connection': 'close',\n 'server': 'nginx/1.0.4',\n 'x-runtime': '148ms',\n 'etag': '\"e1ca502697e5c9317743dc078f67693f\"',\n 'content-type': 'application/json'\n})\n</code></pre> <p>The <code>Headers</code> data type is case-insensitive, so you can use any capitalization.</p> <pre><code>>>> r.headers['Content-Type']\n'application/json'\n\n>>> r.headers.get('content-type')\n'application/json'\n</code></pre> <p>Multiple values for a single response header are represented as a single comma-separated value, as per RFC 7230:</p> <p>A recipient MAY combine multiple header fields with the same field name into one \u201cfield-name: field-value\u201d pair, without changing the semantics of the message, by appending each subsequent field-value to the combined field value in order, separated by a comma.</p>"},{"location":"quickstart/#streaming-responses","title":"Streaming Responses","text":"<p>For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.</p> <p>You can stream the binary content of the response...</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... for data in r.iter_bytes():\n... print(data)\n</code></pre> <p>Or the text of the response...</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... for text in r.iter_text():\n... print(text)\n</code></pre> <p>Or stream the text, on a line-by-line basis...</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... for line in r.iter_lines():\n... print(line)\n</code></pre> <p>HTTPX will use universal line endings, normalising all cases to <code>\\n</code>.</p> <p>In some cases you might want to access the raw bytes on the response without applying any HTTP content decoding. In this case any content encoding that the web server has applied such as <code>gzip</code>, <code>deflate</code>, <code>brotli</code>, or <code>zstd</code> will not be automatically decoded.</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... for chunk in r.iter_raw():\n... print(chunk)\n</code></pre> <p>If you're using streaming responses in any of these ways then the <code>response.content</code> and <code>response.text</code> attributes will not be available, and will raise errors if accessed. However you can also use the response streaming functionality to conditionally load the response body:</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... if int(r.headers['Content-Length']) < TOO_LONG:\n... r.read()\n... print(r.text)\n</code></pre>"},{"location":"quickstart/#cookies","title":"Cookies","text":"<p>Any cookies that are set on the response can be easily accessed:</p> <pre><code>>>> r = httpx.get('https://httpbin.org/cookies/set?chocolate=chip')\n>>> r.cookies['chocolate']\n'chip'\n</code></pre> <p>To include cookies in an outgoing request, use the <code>cookies</code> parameter:</p> <pre><code>>>> cookies = {\"peanut\": \"butter\"}\n>>> r = httpx.get('https://httpbin.org/cookies', cookies=cookies)\n>>> r.json()\n{'cookies': {'peanut': 'butter'}}\n</code></pre> <p>Cookies are returned in a <code>Cookies</code> instance, which is a dict-like data structure with additional API for accessing cookies by their domain or path.</p> <pre><code>>>> cookies = httpx.Cookies()\n>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')\n>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')\n>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)\n>>> r.json()\n{'cookies': {'cookie_on_domain': 'hello, there!'}}\n</code></pre>"},{"location":"quickstart/#redirection-and-history","title":"Redirection and History","text":"<p>By default, HTTPX will not follow redirects for all HTTP methods, although this can be explicitly enabled.</p> <p>For example, GitHub redirects all HTTP requests to HTTPS.</p> <pre><code>>>> r = httpx.get('http://github.com/')\n>>> r.status_code\n301\n>>> r.history\n[]\n>>> r.next_request\n<Request('GET', 'https://github.com/')>\n</code></pre> <p>You can modify the default redirection handling with the <code>follow_redirects</code> parameter:</p> <pre><code>>>> r = httpx.get('http://github.com/', follow_redirects=True)\n>>> r.url\nURL('https://github.com/')\n>>> r.status_code\n200\n>>> r.history\n[<Response [301 Moved Permanently]>]\n</code></pre> <p>The <code>history</code> property of the response can be used to inspect any followed redirects. It contains a list of any redirect responses that were followed, in the order in which they were made.</p>"},{"location":"quickstart/#timeouts","title":"Timeouts","text":"<p>HTTPX defaults to including reasonable timeouts for all network operations, meaning that if a connection is not properly established then it should always raise an error rather than hanging indefinitely.</p> <p>The default timeout for network inactivity is five seconds. You can modify the value to be more or less strict:</p> <pre><code>>>> httpx.get('https://github.com/', timeout=0.001)\n</code></pre> <p>You can also disable the timeout behavior completely...</p> <pre><code>>>> httpx.get('https://github.com/', timeout=None)\n</code></pre> <p>For advanced timeout management, see Timeout fine-tuning.</p>"},{"location":"quickstart/#authentication","title":"Authentication","text":"<p>HTTPX supports Basic and Digest HTTP authentication.</p> <p>To provide Basic authentication credentials, pass a 2-tuple of plaintext <code>str</code> or <code>bytes</code> objects as the <code>auth</code> argument to the request functions:</p> <pre><code>>>> httpx.get(\"https://example.com\", auth=(\"my_user\", \"password123\"))\n</code></pre> <p>To provide credentials for Digest authentication you'll need to instantiate a <code>DigestAuth</code> object with the plaintext username and password as arguments. This object can be then passed as the <code>auth</code> argument to the request methods as above:</p> <pre><code>>>> auth = httpx.DigestAuth(\"my_user\", \"password123\")\n>>> httpx.get(\"https://example.com\", auth=auth)\n<Response [200 OK]>\n</code></pre>"},{"location":"quickstart/#exceptions","title":"Exceptions","text":"<p>HTTPX will raise exceptions if an error occurs.</p> <p>The most important exception classes in HTTPX are <code>RequestError</code> and <code>HTTPStatusError</code>.</p> <p>The <code>RequestError</code> class is a superclass that encompasses any exception that occurs while issuing an HTTP request. These exceptions include a <code>.request</code> attribute.</p> <pre><code>try:\n response = httpx.get(\"https://www.example.com/\")\nexcept httpx.RequestError as exc:\n print(f\"An error occurred while requesting {exc.request.url!r}.\")\n</code></pre> <p>The <code>HTTPStatusError</code> class is raised by <code>response.raise_for_status()</code> on responses which are not a 2xx success code. These exceptions include both a <code>.request</code> and a <code>.response</code> attribute.</p> <pre><code>response = httpx.get(\"https://www.example.com/\")\ntry:\n response.raise_for_status()\nexcept httpx.HTTPStatusError as exc:\n print(f\"Error response {exc.response.status_code} while requesting {exc.request.url!r}.\")\n</code></pre> <p>There is also a base class <code>HTTPError</code> that includes both of these categories, and can be used to catch either failed requests, or 4xx and 5xx responses.</p> <p>You can either use this base class to catch both categories...</p> <pre><code>try:\n response = httpx.get(\"https://www.example.com/\")\n response.raise_for_status()\nexcept httpx.HTTPError as exc:\n print(f\"Error while requesting {exc.request.url!r}.\")\n</code></pre> <p>Or handle each case explicitly...</p> <pre><code>try:\n response = httpx.get(\"https://www.example.com/\")\n response.raise_for_status()\nexcept httpx.RequestError as exc:\n print(f\"An error occurred while requesting {exc.request.url!r}.\")\nexcept httpx.HTTPStatusError as exc:\n print(f\"Error response {exc.response.status_code} while requesting {exc.request.url!r}.\")\n</code></pre> <p>For a full list of available exceptions, see Exceptions (API Reference).</p>"},{"location":"third_party_packages/","title":"Third Party Packages","text":"<p>As HTTPX usage grows, there is an expanding community of developers building tools and libraries that integrate with HTTPX, or depend on HTTPX. Here are some of them.</p>"},{"location":"third_party_packages/#plugins","title":"Plugins","text":""},{"location":"third_party_packages/#httpx-ws","title":"httpx-ws","text":"<p>GitHub - Documentation</p> <p>WebSocket support for HTTPX.</p>"},{"location":"third_party_packages/#httpx-socks","title":"httpx-socks","text":"<p>GitHub</p> <p>Proxy (HTTP, SOCKS) transports for httpx.</p>"},{"location":"third_party_packages/#hishel","title":"Hishel","text":"<p>GitHub - Documentation</p> <p>An elegant HTTP Cache implementation for HTTPX and HTTP Core.</p>"},{"location":"third_party_packages/#authlib","title":"Authlib","text":"<p>GitHub - Documentation</p> <p>The ultimate Python library in building OAuth and OpenID Connect clients and servers. Includes an OAuth HTTPX client.</p>"},{"location":"third_party_packages/#gidgethub","title":"Gidgethub","text":"<p>GitHub - Documentation</p> <p>An asynchronous GitHub API library. Includes HTTPX support.</p>"},{"location":"third_party_packages/#httpx-auth","title":"HTTPX-Auth","text":"<p>GitHub - Documentation</p> <p>Provides authentication classes to be used with HTTPX authentication parameter.</p>"},{"location":"third_party_packages/#pytest-httpx","title":"pytest-HTTPX","text":"<p>GitHub - Documentation</p> <p>Provides <code>httpx_mock</code> pytest fixture to mock HTTPX within test cases.</p>"},{"location":"third_party_packages/#respx","title":"RESPX","text":"<p>GitHub - Documentation</p> <p>A utility for mocking out the Python HTTPX library.</p>"},{"location":"third_party_packages/#rpcpy","title":"rpc.py","text":"<p>Github - Documentation</p> <p>An fast and powerful RPC framework based on ASGI/WSGI. Use HTTPX as the client of the RPC service.</p>"},{"location":"third_party_packages/#vcrpy","title":"VCR.py","text":"<p>GitHub - Documentation</p> <p>A utility for record and repeat an http request.</p>"},{"location":"third_party_packages/#httpx-caching","title":"httpx-caching","text":"<p>Github</p> <p>This package adds caching functionality to HTTPX</p>"},{"location":"third_party_packages/#httpx-sse","title":"httpx-sse","text":"<p>GitHub</p> <p>Allows consuming Server-Sent Events (SSE) with HTTPX.</p>"},{"location":"third_party_packages/#robox","title":"robox","text":"<p>Github</p> <p>A library for scraping the web built on top of HTTPX.</p>"},{"location":"third_party_packages/#gists","title":"Gists","text":""},{"location":"third_party_packages/#urllib3-transport","title":"urllib3-transport","text":"<p>GitHub</p> <p>This public gist provides an example implementation for a custom transport implementation on top of the battle-tested <code>urllib3</code> library.</p>"},{"location":"troubleshooting/","title":"Troubleshooting","text":"<p>This page lists some common problems or issues you could encounter while developing with HTTPX, as well as possible solutions.</p>"},{"location":"troubleshooting/#proxies","title":"Proxies","text":""},{"location":"troubleshooting/#the-handshake-operation-timed-out-on-https-requests-when-using-a-proxy","title":"\"<code>The handshake operation timed out</code>\" on HTTPS requests when using a proxy","text":"<p>Description: When using a proxy and making an HTTPS request, you see an exception looking like this:</p> <pre><code>httpx.ProxyError: _ssl.c:1091: The handshake operation timed out\n</code></pre> <p>Similar issues: encode/httpx#1412, encode/httpx#1433</p> <p>Resolution: it is likely that you've set up your proxies like this...</p> <pre><code>mounts = {\n \"http://\": httpx.HTTPTransport(proxy=\"http://myproxy.org\"),\n \"https://\": httpx.HTTPTransport(proxy=\"https://myproxy.org\"),\n}\n</code></pre> <p>Using this setup, you're telling HTTPX to connect to the proxy using HTTP for HTTP requests, and using HTTPS for HTTPS requests.</p> <p>But if you get the error above, it is likely that your proxy doesn't support connecting via HTTPS. Don't worry: that's a common gotcha.</p> <p>Change the scheme of your HTTPS proxy to <code>http://...</code> instead of <code>https://...</code>:</p> <pre><code>mounts = {\n \"http://\": httpx.HTTPTransport(proxy=\"http://myproxy.org\"),\n \"https://\": httpx.HTTPTransport(proxy=\"http://myproxy.org\"),\n}\n</code></pre> <p>This can be simplified to:</p> <pre><code>proxy = \"http://myproxy.org\"\nwith httpx.Client(proxy=proxy) as client:\n ...\n</code></pre> <p>For more information, see Proxies: FORWARD vs TUNNEL.</p>"},{"location":"troubleshooting/#error-when-making-requests-to-an-https-proxy","title":"Error when making requests to an HTTPS proxy","text":"<p>Description: your proxy does support connecting via HTTPS, but you are seeing errors along the lines of...</p> <pre><code>httpx.ProxyError: [SSL: PRE_MAC_LENGTH_TOO_LONG] invalid alert (_ssl.c:1091)\n</code></pre> <p>Similar issues: encode/httpx#1424.</p> <p>Resolution: HTTPX does not properly support HTTPS proxies at this time. If that's something you're interested in having, please see encode/httpx#1434 and consider lending a hand there.</p>"},{"location":"advanced/authentication/","title":"Authentication","text":"<p>Authentication can either be included on a per-request basis...</p> <pre><code>>>> auth = httpx.BasicAuth(username=\"username\", password=\"secret\")\n>>> client = httpx.Client()\n>>> response = client.get(\"https://www.example.com/\", auth=auth)\n</code></pre> <p>Or configured on the client instance, ensuring that all outgoing requests will include authentication credentials...</p> <pre><code>>>> auth = httpx.BasicAuth(username=\"username\", password=\"secret\")\n>>> client = httpx.Client(auth=auth)\n>>> response = client.get(\"https://www.example.com/\")\n</code></pre>"},{"location":"advanced/authentication/#basic-authentication","title":"Basic authentication","text":"<p>HTTP basic authentication is an unencrypted authentication scheme that uses a simple encoding of the username and password in the request <code>Authorization</code> header. Since it is unencrypted it should typically only be used over <code>https</code>, although this is not strictly enforced.</p> <pre><code>>>> auth = httpx.BasicAuth(username=\"finley\", password=\"secret\")\n>>> client = httpx.Client(auth=auth)\n>>> response = client.get(\"https://httpbin.org/basic-auth/finley/secret\")\n>>> response\n<Response [200 OK]>\n</code></pre>"},{"location":"advanced/authentication/#digest-authentication","title":"Digest authentication","text":"<p>HTTP digest authentication is a challenge-response authentication scheme. Unlike basic authentication it provides encryption, and can be used over unencrypted <code>http</code> connections. It requires an additional round-trip in order to negotiate the authentication. </p> <pre><code>>>> auth = httpx.DigestAuth(username=\"olivia\", password=\"secret\")\n>>> client = httpx.Client(auth=auth)\n>>> response = client.get(\"https://httpbin.org/digest-auth/auth/olivia/secret\")\n>>> response\n<Response [200 OK]>\n>>> response.history\n[<Response [401 UNAUTHORIZED]>]\n</code></pre>"},{"location":"advanced/authentication/#netrc-authentication","title":"NetRC authentication","text":"<p>HTTPX can be configured to use a <code>.netrc</code> config file for authentication.</p> <p>The <code>.netrc</code> config file allows authentication credentials to be associated with specified hosts. When a request is made to a host that is found in the netrc file, the username and password will be included using HTTP basic authentication.</p> <p>Example <code>.netrc</code> file:</p> <pre><code>machine example.org\nlogin example-username\npassword example-password\n\nmachine python-httpx.org\nlogin other-username\npassword other-password\n</code></pre> <p>Some examples of configuring <code>.netrc</code> authentication with <code>httpx</code>.</p> <p>Use the default <code>.netrc</code> file in the users home directory:</p> <pre><code>>>> auth = httpx.NetRCAuth()\n>>> client = httpx.Client(auth=auth)\n</code></pre> <p>Use an explicit path to a <code>.netrc</code> file:</p> <pre><code>>>> auth = httpx.NetRCAuth(file=\"/path/to/.netrc\")\n>>> client = httpx.Client(auth=auth)\n</code></pre> <p>Use the <code>NETRC</code> environment variable to configure a path to the <code>.netrc</code> file, or fallback to the default.</p> <pre><code>>>> auth = httpx.NetRCAuth(file=os.environ.get(\"NETRC\"))\n>>> client = httpx.Client(auth=auth)\n</code></pre> <p>The <code>NetRCAuth()</code> class uses the <code>netrc.netrc()</code> function from the Python standard library. See the documentation there for more details on exceptions that may be raised if the <code>.netrc</code> file is not found, or cannot be parsed.</p>"},{"location":"advanced/authentication/#custom-authentication-schemes","title":"Custom authentication schemes","text":"<p>When issuing requests or instantiating a client, the <code>auth</code> argument can be used to pass an authentication scheme to use. The <code>auth</code> argument may be one of the following...</p> <ul> <li>A two-tuple of <code>username</code>/<code>password</code>, to be used with basic authentication.</li> <li>An instance of <code>httpx.BasicAuth()</code>, <code>httpx.DigestAuth()</code>, or <code>httpx.NetRCAuth()</code>.</li> <li>A callable, accepting a request and returning an authenticated request instance.</li> <li>An instance of subclasses of <code>httpx.Auth</code>.</li> </ul> <p>The most involved of these is the last, which allows you to create authentication flows involving one or more requests. A subclass of <code>httpx.Auth</code> should implement <code>def auth_flow(request)</code>, and yield any requests that need to be made...</p> <pre><code>class MyCustomAuth(httpx.Auth):\n def __init__(self, token):\n self.token = token\n\n def auth_flow(self, request):\n # Send the request, with a custom `X-Authentication` header.\n request.headers['X-Authentication'] = self.token\n yield request\n</code></pre> <p>If the auth flow requires more than one request, you can issue multiple yields, and obtain the response in each case...</p> <pre><code>class MyCustomAuth(httpx.Auth):\n def __init__(self, token):\n self.token = token\n\n def auth_flow(self, request):\n response = yield request\n if response.status_code == 401:\n # If the server issues a 401 response then resend the request,\n # with a custom `X-Authentication` header.\n request.headers['X-Authentication'] = self.token\n yield request\n</code></pre> <p>Custom authentication classes are designed to not perform any I/O, so that they may be used with both sync and async client instances. If you are implementing an authentication scheme that requires the request body, then you need to indicate this on the class using a <code>requires_request_body</code> property.</p> <p>You will then be able to access <code>request.content</code> inside the <code>.auth_flow()</code> method.</p> <pre><code>class MyCustomAuth(httpx.Auth):\n requires_request_body = True\n\n def __init__(self, token):\n self.token = token\n\n def auth_flow(self, request):\n response = yield request\n if response.status_code == 401:\n # If the server issues a 401 response then resend the request,\n # with a custom `X-Authentication` header.\n request.headers['X-Authentication'] = self.sign_request(...)\n yield request\n\n def sign_request(self, request):\n # Create a request signature, based on `request.method`, `request.url`,\n # `request.headers`, and `request.content`.\n ...\n</code></pre> <p>Similarly, if you are implementing a scheme that requires access to the response body, then use the <code>requires_response_body</code> property. You will then be able to access response body properties and methods such as <code>response.content</code>, <code>response.text</code>, <code>response.json()</code>, etc.</p> <pre><code>class MyCustomAuth(httpx.Auth):\n requires_response_body = True\n\n def __init__(self, access_token, refresh_token, refresh_url):\n self.access_token = access_token\n self.refresh_token = refresh_token\n self.refresh_url = refresh_url\n\n def auth_flow(self, request):\n request.headers[\"X-Authentication\"] = self.access_token\n response = yield request\n\n if response.status_code == 401:\n # If the server issues a 401 response, then issue a request to\n # refresh tokens, and resend the request.\n refresh_response = yield self.build_refresh_request()\n self.update_tokens(refresh_response)\n\n request.headers[\"X-Authentication\"] = self.access_token\n yield request\n\n def build_refresh_request(self):\n # Return an `httpx.Request` for refreshing tokens.\n ...\n\n def update_tokens(self, response):\n # Update the `.access_token` and `.refresh_token` tokens\n # based on a refresh response.\n data = response.json()\n ...\n</code></pre> <p>If you do need to perform I/O other than HTTP requests, such as accessing a disk-based cache, or you need to use concurrency primitives, such as locks, then you should override <code>.sync_auth_flow()</code> and <code>.async_auth_flow()</code> (instead of <code>.auth_flow()</code>). The former will be used by <code>httpx.Client</code>, while the latter will be used by <code>httpx.AsyncClient</code>.</p> <pre><code>import asyncio\nimport threading\nimport httpx\n\n\nclass MyCustomAuth(httpx.Auth):\n def __init__(self):\n self._sync_lock = threading.RLock()\n self._async_lock = asyncio.Lock()\n\n def sync_get_token(self):\n with self._sync_lock:\n ...\n\n def sync_auth_flow(self, request):\n token = self.sync_get_token()\n request.headers[\"Authorization\"] = f\"Token {token}\"\n yield request\n\n async def async_get_token(self):\n async with self._async_lock:\n ...\n\n async def async_auth_flow(self, request):\n token = await self.async_get_token()\n request.headers[\"Authorization\"] = f\"Token {token}\"\n yield request\n</code></pre> <p>If you only want to support one of the two methods, then you should still override it, but raise an explicit <code>RuntimeError</code>.</p> <pre><code>import httpx\nimport sync_only_library\n\n\nclass MyCustomAuth(httpx.Auth):\n def sync_auth_flow(self, request):\n token = sync_only_library.get_token(...)\n request.headers[\"Authorization\"] = f\"Token {token}\"\n yield request\n\n async def async_auth_flow(self, request):\n raise RuntimeError(\"Cannot use a sync authentication class with httpx.AsyncClient\")\n</code></pre>"},{"location":"advanced/clients/","title":"Clients","text":"<p>Hint</p> <p>If you are coming from Requests, <code>httpx.Client()</code> is what you can use instead of <code>requests.Session()</code>.</p>"},{"location":"advanced/clients/#why-use-a-client","title":"Why use a Client?","text":"<p>TL;DR</p> <p>If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a <code>Client</code> instance.</p> <p>More efficient usage of network resources</p> <p>When you make requests using the top-level API as documented in the Quickstart guide, HTTPX has to establish a new connection for every single request (connections are not reused). As the number of requests to a host increases, this quickly becomes inefficient.</p> <p>On the other hand, a <code>Client</code> instance uses HTTP connection pooling. This means that when you make several requests to the same host, the <code>Client</code> will reuse the underlying TCP connection, instead of recreating one for every single request.</p> <p>This can bring significant performance improvements compared to using the top-level API, including:</p> <ul> <li>Reduced latency across requests (no handshaking).</li> <li>Reduced CPU usage and round-trips.</li> <li>Reduced network congestion.</li> </ul> <p>Extra features</p> <p><code>Client</code> instances also support features that aren't available at the top-level API, such as:</p> <ul> <li>Cookie persistence across requests.</li> <li>Applying configuration across all outgoing requests.</li> <li>Sending requests through HTTP proxies.</li> <li>Using HTTP/2.</li> </ul> <p>The other sections on this page go into further detail about what you can do with a <code>Client</code> instance.</p>"},{"location":"advanced/clients/#usage","title":"Usage","text":"<p>The recommended way to use a <code>Client</code> is as a context manager. This will ensure that connections are properly cleaned up when leaving the <code>with</code> block:</p> <pre><code>with httpx.Client() as client:\n ...\n</code></pre> <p>Alternatively, you can explicitly close the connection pool without block-usage using <code>.close()</code>:</p> <pre><code>client = httpx.Client()\ntry:\n ...\nfinally:\n client.close()\n</code></pre>"},{"location":"advanced/clients/#making-requests","title":"Making requests","text":"<p>Once you have a <code>Client</code>, you can send requests using <code>.get()</code>, <code>.post()</code>, etc. For example:</p> <pre><code>>>> with httpx.Client() as client:\n... r = client.get('https://example.com')\n...\n>>> r\n<Response [200 OK]>\n</code></pre> <p>These methods accept the same arguments as <code>httpx.get()</code>, <code>httpx.post()</code>, etc. This means that all features documented in the Quickstart guide are also available at the client level.</p> <p>For example, to send a request with custom headers:</p> <pre><code>>>> with httpx.Client() as client:\n... headers = {'X-Custom': 'value'}\n... r = client.get('https://example.com', headers=headers)\n...\n>>> r.request.headers['X-Custom']\n'value'\n</code></pre>"},{"location":"advanced/clients/#sharing-configuration-across-requests","title":"Sharing configuration across requests","text":"<p>Clients allow you to apply configuration to all outgoing requests by passing parameters to the <code>Client</code> constructor.</p> <p>For example, to apply a set of custom headers on every request:</p> <pre><code>>>> url = 'http://httpbin.org/headers'\n>>> headers = {'user-agent': 'my-app/0.0.1'}\n>>> with httpx.Client(headers=headers) as client:\n... r = client.get(url)\n...\n>>> r.json()['headers']['User-Agent']\n'my-app/0.0.1'\n</code></pre>"},{"location":"advanced/clients/#merging-of-configuration","title":"Merging of configuration","text":"<p>When a configuration option is provided at both the client-level and request-level, one of two things can happen:</p> <ul> <li>For headers, query parameters and cookies, the values are combined together. For example:</li> </ul> <pre><code>>>> headers = {'X-Auth': 'from-client'}\n>>> params = {'client_id': 'client1'}\n>>> with httpx.Client(headers=headers, params=params) as client:\n... headers = {'X-Custom': 'from-request'}\n... params = {'request_id': 'request1'}\n... r = client.get('https://example.com', headers=headers, params=params)\n...\n>>> r.request.url\nURL('https://example.com?client_id=client1&request_id=request1')\n>>> r.request.headers['X-Auth']\n'from-client'\n>>> r.request.headers['X-Custom']\n'from-request'\n</code></pre> <ul> <li>For all other parameters, the request-level value takes priority. For example:</li> </ul> <pre><code>>>> with httpx.Client(auth=('tom', 'mot123')) as client:\n... r = client.get('https://example.com', auth=('alice', 'ecila123'))\n...\n>>> _, _, auth = r.request.headers['Authorization'].partition(' ')\n>>> import base64\n>>> base64.b64decode(auth)\nb'alice:ecila123'\n</code></pre> <p>If you need finer-grained control on the merging of client-level and request-level parameters, see Request instances.</p>"},{"location":"advanced/clients/#other-client-only-configuration-options","title":"Other Client-only configuration options","text":"<p>Additionally, <code>Client</code> accepts some configuration options that aren't available at the request level.</p> <p>For example, <code>base_url</code> allows you to prepend an URL to all outgoing requests:</p> <pre><code>>>> with httpx.Client(base_url='http://httpbin.org') as client:\n... r = client.get('/headers')\n...\n>>> r.request.url\nURL('http://httpbin.org/headers')\n</code></pre> <p>For a list of all available client parameters, see the <code>Client</code> API reference.</p>"},{"location":"advanced/clients/#request-instances","title":"Request instances","text":"<p>For maximum control on what gets sent over the wire, HTTPX supports building explicit <code>Request</code> instances:</p> <pre><code>request = httpx.Request(\"GET\", \"https://example.com\")\n</code></pre> <p>To dispatch a <code>Request</code> instance across to the network, create a <code>Client</code> instance and use <code>.send()</code>:</p> <pre><code>with httpx.Client() as client:\n response = client.send(request)\n ...\n</code></pre> <p>If you need to mix client-level and request-level options in a way that is not supported by the default Merging of parameters, you can use <code>.build_request()</code> and then make arbitrary modifications to the <code>Request</code> instance. For example:</p> <pre><code>headers = {\"X-Api-Key\": \"...\", \"X-Client-ID\": \"ABC123\"}\n\nwith httpx.Client(headers=headers) as client:\n request = client.build_request(\"GET\", \"https://api.example.com\")\n\n print(request.headers[\"X-Client-ID\"]) # \"ABC123\"\n\n # Don't send the API key for this particular request.\n del request.headers[\"X-Api-Key\"]\n\n response = client.send(request)\n ...\n</code></pre>"},{"location":"advanced/clients/#monitoring-download-progress","title":"Monitoring download progress","text":"<p>If you need to monitor download progress of large responses, you can use response streaming and inspect the <code>response.num_bytes_downloaded</code> property.</p> <p>This interface is required for properly determining download progress, because the total number of bytes returned by <code>response.content</code> or <code>response.iter_content()</code> will not always correspond with the raw content length of the response if HTTP response compression is being used.</p> <p>For example, showing a progress bar using the <code>tqdm</code> library while a response is being downloaded could be done like this\u2026</p> <pre><code>import tempfile\n\nimport httpx\nfrom tqdm import tqdm\n\nwith tempfile.NamedTemporaryFile() as download_file:\n url = \"https://speed.hetzner.de/100MB.bin\"\n with httpx.stream(\"GET\", url) as response:\n total = int(response.headers[\"Content-Length\"])\n\n with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit=\"B\") as progress:\n num_bytes_downloaded = response.num_bytes_downloaded\n for chunk in response.iter_bytes():\n download_file.write(chunk)\n progress.update(response.num_bytes_downloaded - num_bytes_downloaded)\n num_bytes_downloaded = response.num_bytes_downloaded\n</code></pre> <p></p> <p>Or an alternate example, this time using the <code>rich</code> library\u2026</p> <pre><code>import tempfile\nimport httpx\nimport rich.progress\n\nwith tempfile.NamedTemporaryFile() as download_file:\n url = \"https://speed.hetzner.de/100MB.bin\"\n with httpx.stream(\"GET\", url) as response:\n total = int(response.headers[\"Content-Length\"])\n\n with rich.progress.Progress(\n \"[progress.percentage]{task.percentage:>3.0f}%\",\n rich.progress.BarColumn(bar_width=None),\n rich.progress.DownloadColumn(),\n rich.progress.TransferSpeedColumn(),\n ) as progress:\n download_task = progress.add_task(\"Download\", total=total)\n for chunk in response.iter_bytes():\n download_file.write(chunk)\n progress.update(download_task, completed=response.num_bytes_downloaded)\n</code></pre> <p></p>"},{"location":"advanced/clients/#monitoring-upload-progress","title":"Monitoring upload progress","text":"<p>If you need to monitor upload progress of large responses, you can use request content generator streaming.</p> <p>For example, showing a progress bar using the <code>tqdm</code> library.</p> <pre><code>import io\nimport random\n\nimport httpx\nfrom tqdm import tqdm\n\n\ndef gen():\n \"\"\"\n this is a complete example with generated random bytes.\n you can replace `io.BytesIO` with real file object.\n \"\"\"\n total = 32 * 1024 * 1024 # 32m\n with tqdm(ascii=True, unit_scale=True, unit='B', unit_divisor=1024, total=total) as bar:\n with io.BytesIO(random.randbytes(total)) as f:\n while data := f.read(1024):\n yield data\n bar.update(len(data))\n\n\nhttpx.post(\"https://httpbin.org/post\", content=gen())\n</code></pre> <p></p>"},{"location":"advanced/clients/#multipart-file-encoding","title":"Multipart file encoding","text":"<p>As mentioned in the quickstart multipart file encoding is available by passing a dictionary with the name of the payloads as keys and either tuple of elements or a file-like object or a string as values.</p> <pre><code>>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}\n>>> r = httpx.post(\"https://httpbin.org/post\", files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {\n \"upload-file\": \"<... binary content ...>\"\n },\n ...\n}\n</code></pre> <p>More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:</p> <ul> <li>The first element is an optional file name which can be set to <code>None</code>.</li> <li>The second element may be a file-like object or a string which will be automatically encoded in UTF-8.</li> <li>An optional third element can be used to specify the MIME type of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based on the file name, with unknown file extensions defaulting to \"application/octet-stream\". If the file name is explicitly set to <code>None</code> then HTTPX will not include a content-type MIME header field.</li> </ul> <pre><code>>>> files = {'upload-file': (None, 'text content', 'text/plain')}\n>>> r = httpx.post(\"https://httpbin.org/post\", files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {},\n \"form\": {\n \"upload-file\": \"text-content\"\n },\n ...\n}\n</code></pre> <p>Tip</p> <p>It is safe to upload large files this way. File uploads are streaming by default, meaning that only one chunk will be loaded into memory at a time.</p> <p>Non-file data fields can be included in the multipart form using by passing them to <code>data=...</code>.</p> <p>You can also send multiple files in one go with a multiple file field form. To do that, pass a list of <code>(field, <file>)</code> items instead of a dictionary, allowing you to pass multiple items with the same <code>field</code>. For instance this request sends 2 files, <code>foo.png</code> and <code>bar.png</code> in one request on the <code>images</code> form field:</p> <pre><code>>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),\n ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]\n>>> r = httpx.post(\"https://httpbin.org/post\", files=files)\n</code></pre>"},{"location":"advanced/event-hooks/","title":"Event Hooks","text":"<p>HTTPX allows you to register \"event hooks\" with the client, that are called every time a particular type of event takes place.</p> <p>There are currently two event hooks:</p> <ul> <li><code>request</code> - Called after a request is fully prepared, but before it is sent to the network. Passed the <code>request</code> instance.</li> <li><code>response</code> - Called after the response has been fetched from the network, but before it is returned to the caller. Passed the <code>response</code> instance.</li> </ul> <p>These allow you to install client-wide functionality such as logging, monitoring or tracing.</p> <pre><code>def log_request(request):\n print(f\"Request event hook: {request.method} {request.url} - Waiting for response\")\n\ndef log_response(response):\n request = response.request\n print(f\"Response event hook: {request.method} {request.url} - Status {response.status_code}\")\n\nclient = httpx.Client(event_hooks={'request': [log_request], 'response': [log_response]})\n</code></pre> <p>You can also use these hooks to install response processing code, such as this example, which creates a client instance that always raises <code>httpx.HTTPStatusError</code> on 4xx and 5xx responses.</p> <pre><code>def raise_on_4xx_5xx(response):\n response.raise_for_status()\n\nclient = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})\n</code></pre> <p>Note</p> <p>Response event hooks are called before determining if the response body should be read or not.</p> <p>If you need access to the response body inside an event hook, you'll need to call <code>response.read()</code>, or for AsyncClients, <code>response.aread()</code>.</p> <p>The hooks are also allowed to modify <code>request</code> and <code>response</code> objects.</p> <pre><code>def add_timestamp(request):\n request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat()\n\nclient = httpx.Client(event_hooks={'request': [add_timestamp]})\n</code></pre> <p>Event hooks must always be set as a list of callables, and you may register multiple event hooks for each type of event.</p> <p>As well as being able to set event hooks on instantiating the client, there is also an <code>.event_hooks</code> property, that allows you to inspect and modify the installed hooks.</p> <pre><code>client = httpx.Client()\nclient.event_hooks['request'] = [log_request]\nclient.event_hooks['response'] = [log_response, raise_on_4xx_5xx]\n</code></pre> <p>Note</p> <p>If you are using HTTPX's async support, then you need to be aware that hooks registered with <code>httpx.AsyncClient</code> MUST be async functions, rather than plain functions.</p>"},{"location":"advanced/extensions/","title":"Extensions","text":"<p>Request and response extensions provide a untyped space where additional information may be added.</p> <p>Extensions should be used for features that may not be available on all transports, and that do not fit neatly into the simplified request/response model that the underlying <code>httpcore</code> package uses as its API.</p> <p>Several extensions are supported on the request:</p> <pre><code># Request timeouts actually implemented as an extension on\n# the request, ensuring that they are passed throughout the\n# entire call stack.\nclient = httpx.Client()\nresponse = client.get(\n \"https://www.example.com\",\n extensions={\"timeout\": {\"connect\": 5.0}}\n)\nresponse.request.extensions[\"timeout\"]\n{\"connect\": 5.0}\n</code></pre> <p>And on the response:</p> <pre><code>client = httpx.Client()\nresponse = client.get(\"https://www.example.com\")\nprint(response.extensions[\"http_version\"]) # b\"HTTP/1.1\"\n# Other server responses could have been\n# b\"HTTP/0.9\", b\"HTTP/1.0\", or b\"HTTP/1.1\"\n</code></pre>"},{"location":"advanced/extensions/#request-extensions","title":"Request Extensions","text":""},{"location":"advanced/extensions/#trace","title":"<code>\"trace\"</code>","text":"<p>The trace extension allows a callback handler to be installed to monitor the internal flow of events within the underlying <code>httpcore</code> transport.</p> <p>The simplest way to explain this is with an example:</p> <pre><code>import httpx\n\ndef log(event_name, info):\n print(event_name, info)\n\nclient = httpx.Client()\nresponse = client.get(\"https://www.example.com/\", extensions={\"trace\": log})\n# connection.connect_tcp.started {'host': 'www.example.com', 'port': 443, 'local_address': None, 'timeout': None}\n# connection.connect_tcp.complete {'return_value': <httpcore.backends.sync.SyncStream object at 0x1093f94d0>}\n# connection.start_tls.started {'ssl_context': <ssl.SSLContext object at 0x1093ee750>, 'server_hostname': b'www.example.com', 'timeout': None}\n# connection.start_tls.complete {'return_value': <httpcore.backends.sync.SyncStream object at 0x1093f9450>}\n# http11.send_request_headers.started {'request': <Request [b'GET']>}\n# http11.send_request_headers.complete {'return_value': None}\n# http11.send_request_body.started {'request': <Request [b'GET']>}\n# http11.send_request_body.complete {'return_value': None}\n# http11.receive_response_headers.started {'request': <Request [b'GET']>}\n# http11.receive_response_headers.complete {'return_value': (b'HTTP/1.1', 200, b'OK', [(b'Age', b'553715'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Thu, 21 Oct 2021 17:08:42 GMT'), (b'Etag', b'\"3147526947+ident\"'), (b'Expires', b'Thu, 28 Oct 2021 17:08:42 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECS (nyb/1DCD)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'1256')])}\n# http11.receive_response_body.started {'request': <Request [b'GET']>}\n# http11.receive_response_body.complete {'return_value': None}\n# http11.response_closed.started {}\n# http11.response_closed.complete {'return_value': None}\n</code></pre> <p>The <code>event_name</code> and <code>info</code> arguments here will be one of the following:</p> <ul> <li><code>{event_type}.{event_name}.started</code>, <code><dictionary of keyword arguments></code></li> <li><code>{event_type}.{event_name}.complete</code>, <code>{\"return_value\": <...>}</code></li> <li><code>{event_type}.{event_name}.failed</code>, <code>{\"exception\": <...>}</code></li> </ul> <p>Note that when using async code the handler function passed to <code>\"trace\"</code> must be an <code>async def ...</code> function.</p> <p>The following event types are currently exposed...</p> <p>Establishing the connection</p> <ul> <li><code>\"connection.connect_tcp\"</code></li> <li><code>\"connection.connect_unix_socket\"</code></li> <li><code>\"connection.start_tls\"</code></li> </ul> <p>HTTP/1.1 events</p> <ul> <li><code>\"http11.send_request_headers\"</code></li> <li><code>\"http11.send_request_body\"</code></li> <li><code>\"http11.receive_response\"</code></li> <li><code>\"http11.receive_response_body\"</code></li> <li><code>\"http11.response_closed\"</code></li> </ul> <p>HTTP/2 events</p> <ul> <li><code>\"http2.send_connection_init\"</code></li> <li><code>\"http2.send_request_headers\"</code></li> <li><code>\"http2.send_request_body\"</code></li> <li><code>\"http2.receive_response_headers\"</code></li> <li><code>\"http2.receive_response_body\"</code></li> <li><code>\"http2.response_closed\"</code></li> </ul> <p>The exact set of trace events may be subject to change across different versions of <code>httpcore</code>. If you need to rely on a particular set of events it is recommended that you pin installation of the package to a fixed version.</p>"},{"location":"advanced/extensions/#sni_hostname","title":"<code>\"sni_hostname\"</code>","text":"<p>The server's hostname, which is used to confirm the hostname supplied by the SSL certificate.</p> <p>If you want to connect to an explicit IP address rather than using the standard DNS hostname lookup, then you'll need to use this request extension.</p> <p>For example:</p> <pre><code># Connect to '185.199.108.153' but use 'www.encode.io' in the Host header,\n#\u00a0and use 'www.encode.io' when SSL verifying the server hostname.\nclient = httpx.Client()\nheaders = {\"Host\": \"www.encode.io\"}\nextensions = {\"sni_hostname\": \"www.encode.io\"}\nresponse = client.get(\n \"https://185.199.108.153/path\",\n headers=headers,\n extensions=extensions\n)\n</code></pre>"},{"location":"advanced/extensions/#timeout","title":"<code>\"timeout\"</code>","text":"<p>A dictionary of <code>str: Optional[float]</code> timeout values.</p> <p>May include values for <code>'connect'</code>, <code>'read'</code>, <code>'write'</code>, or <code>'pool'</code>.</p> <p>For example:</p> <pre><code># Timeout if a connection takes more than 5 seconds to established, or if\n# we are blocked waiting on the connection pool for more than 10 seconds.\nclient = httpx.Client()\nresponse = client.get(\n \"https://www.example.com\",\n extensions={\"timeout\": {\"connect\": 5.0, \"pool\": 10.0}}\n)\n</code></pre> <p>This extension is how the <code>httpx</code> timeouts are implemented, ensuring that the timeout values are associated with the request instance and passed throughout the stack. You shouldn't typically be working with this extension directly, but use the higher level <code>timeout</code> API instead.</p>"},{"location":"advanced/extensions/#target","title":"<code>\"target\"</code>","text":"<p>The target that is used as the HTTP target instead of the URL path.</p> <p>This enables support constructing requests that would otherwise be unsupported.</p> <ul> <li>URL paths with non-standard escaping applied.</li> <li>Forward proxy requests using an absolute URI.</li> <li>Tunneling proxy requests using <code>CONNECT</code> with hostname as the target.</li> <li>Server-wide <code>OPTIONS *</code> requests.</li> </ul> <p>Some examples:</p> <p>Using the 'target' extension to send requests without the standard path escaping rules...</p> <pre><code># Typically a request to \"https://www.example.com/test^path\" would\n# connect to \"www.example.com\" and send an HTTP/1.1 request like...\n#\n# GET /test%5Epath HTTP/1.1\n#\n# Using the target extension we can include the literal '^'...\n#\n# GET /test^path HTTP/1.1\n#\n# Note that requests must still be valid HTTP requests.\n# For example including whitespace in the target will raise a `LocalProtocolError`.\nextensions = {\"target\": b\"/test^path\"}\nresponse = httpx.get(\"https://www.example.com\", extensions=extensions)\n</code></pre> <p>The <code>target</code> extension also allows server-wide <code>OPTIONS *</code> requests to be constructed...</p> <pre><code># This will send the following request...\n#\n# CONNECT * HTTP/1.1\nextensions = {\"target\": b\"*\"}\nresponse = httpx.request(\"CONNECT\", \"https://www.example.com\", extensions=extensions)\n</code></pre>"},{"location":"advanced/extensions/#response-extensions","title":"Response Extensions","text":""},{"location":"advanced/extensions/#http_version","title":"<code>\"http_version\"</code>","text":"<p>The HTTP version, as bytes. Eg. <code>b\"HTTP/1.1\"</code>.</p> <p>When using HTTP/1.1 the response line includes an explicit version, and the value of this key could feasibly be one of <code>b\"HTTP/0.9\"</code>, <code>b\"HTTP/1.0\"</code>, or <code>b\"HTTP/1.1\"</code>.</p> <p>When using HTTP/2 there is no further response versioning included in the protocol, and the value of this key will always be <code>b\"HTTP/2\"</code>.</p>"},{"location":"advanced/extensions/#reason_phrase","title":"<code>\"reason_phrase\"</code>","text":"<p>The reason-phrase of the HTTP response, as bytes. For example <code>b\"OK\"</code>. Some servers may include a custom reason phrase, although this is not recommended.</p> <p>HTTP/2 onwards does not include a reason phrase on the wire.</p> <p>When no key is included, a default based on the status code may be used.</p>"},{"location":"advanced/extensions/#stream_id","title":"<code>\"stream_id\"</code>","text":"<p>When HTTP/2 is being used the <code>\"stream_id\"</code> response extension can be accessed to determine the ID of the data stream that the response was sent on.</p>"},{"location":"advanced/extensions/#network_stream","title":"<code>\"network_stream\"</code>","text":"<p>The <code>\"network_stream\"</code> extension allows developers to handle HTTP <code>CONNECT</code> and <code>Upgrade</code> requests, by providing an API that steps outside the standard request/response model, and can directly read or write to the network.</p> <p>The interface provided by the network stream:</p> <ul> <li><code>read(max_bytes, timeout = None) -> bytes</code></li> <li><code>write(buffer, timeout = None)</code></li> <li><code>close()</code></li> <li><code>start_tls(ssl_context, server_hostname = None, timeout = None) -> NetworkStream</code></li> <li><code>get_extra_info(info) -> Any</code></li> </ul> <p>This API can be used as the foundation for working with HTTP proxies, WebSocket upgrades, and other advanced use-cases.</p> <p>See the network backends documentation for more information on working directly with network streams.</p> <p>Extra network information</p> <p>The network stream abstraction also allows access to various low-level information that may be exposed by the underlying socket:</p> <pre><code>response = httpx.get(\"https://www.example.com\")\nnetwork_stream = response.extensions[\"network_stream\"]\n\nclient_addr = network_stream.get_extra_info(\"client_addr\")\nserver_addr = network_stream.get_extra_info(\"server_addr\")\nprint(\"Client address\", client_addr)\nprint(\"Server address\", server_addr)\n</code></pre> <p>The socket SSL information is also available through this interface, although you need to ensure that the underlying connection is still open, in order to access it...</p> <pre><code>with httpx.stream(\"GET\", \"https://www.example.com\") as response:\n network_stream = response.extensions[\"network_stream\"]\n\n ssl_object = network_stream.get_extra_info(\"ssl_object\")\n print(\"TLS version\", ssl_object.version())\n</code></pre>"},{"location":"advanced/proxies/","title":"Proxies","text":"<p>HTTPX supports setting up HTTP proxies via the <code>proxy</code> parameter to be passed on client initialization or top-level API functions like <code>httpx.get(..., proxy=...)</code>.</p> Diagram of how a proxy works (source: Wikipedia). The left hand side \"Internet\" blob may be your HTTPX client requesting <code>example.com</code> through a proxy."},{"location":"advanced/proxies/#http-proxies","title":"HTTP Proxies","text":"<p>To route all traffic (HTTP and HTTPS) to a proxy located at <code>http://localhost:8030</code>, pass the proxy URL to the client...</p> <pre><code>with httpx.Client(proxy=\"http://localhost:8030\") as client:\n ...\n</code></pre> <p>For more advanced use cases, pass a mounts <code>dict</code>. For example, to route HTTP and HTTPS requests to 2 different proxies, respectively located at <code>http://localhost:8030</code>, and <code>http://localhost:8031</code>, pass a <code>dict</code> of proxy URLs:</p> <pre><code>proxy_mounts = {\n \"http://\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n \"https://\": httpx.HTTPTransport(proxy=\"http://localhost:8031\"),\n}\n\nwith httpx.Client(mounts=proxy_mounts) as client:\n ...\n</code></pre> <p>For detailed information about proxy routing, see the Routing section.</p> <p>Gotcha</p> <p>In most cases, the proxy URL for the <code>https://</code> key should use the <code>http://</code> scheme (that's not a typo!).</p> <p>This is because HTTP proxying requires initiating a connection with the proxy server. While it's possible that your proxy supports doing it via HTTPS, most proxies only support doing it via HTTP.</p> <p>For more information, see FORWARD vs TUNNEL.</p>"},{"location":"advanced/proxies/#authentication","title":"Authentication","text":"<p>Proxy credentials can be passed as the <code>userinfo</code> section of the proxy URL. For example:</p> <pre><code>with httpx.Client(proxy=\"http://username:password@localhost:8030\") as client:\n ...\n</code></pre>"},{"location":"advanced/proxies/#proxy-mechanisms","title":"Proxy mechanisms","text":"<p>Note</p> <p>This section describes advanced proxy concepts and functionality.</p>"},{"location":"advanced/proxies/#forward-vs-tunnel","title":"FORWARD vs TUNNEL","text":"<p>In general, the flow for making an HTTP request through a proxy is as follows:</p> <ol> <li>The client connects to the proxy (initial connection request).</li> <li>The proxy transfers data to the server on your behalf.</li> </ol> <p>How exactly step 2/ is performed depends on which of two proxying mechanisms is used:</p> <ul> <li>Forwarding: the proxy makes the request for you, and sends back the response it obtained from the server.</li> <li>Tunnelling: the proxy establishes a TCP connection to the server on your behalf, and the client reuses this connection to send the request and receive the response. This is known as an HTTP Tunnel. This mechanism is how you can access websites that use HTTPS from an HTTP proxy (the client \"upgrades\" the connection to HTTPS by performing the TLS handshake with the server over the TCP connection provided by the proxy).</li> </ul>"},{"location":"advanced/proxies/#troubleshooting-proxies","title":"Troubleshooting proxies","text":"<p>If you encounter issues when setting up proxies, please refer to our Troubleshooting guide.</p>"},{"location":"advanced/proxies/#socks","title":"SOCKS","text":"<p>In addition to HTTP proxies, <code>httpcore</code> also supports proxies using the SOCKS protocol. This is an optional feature that requires an additional third-party library be installed before use.</p> <p>You can install SOCKS support using <code>pip</code>:</p> <pre><code>$ pip install httpx[socks]\n</code></pre> <p>You can now configure a client to make requests via a proxy using the SOCKS protocol:</p> <pre><code>httpx.Client(proxy='socks5://user:pass@host:port')\n</code></pre>"},{"location":"advanced/resource-limits/","title":"Resource Limits","text":"<p>You can control the connection pool size using the <code>limits</code> keyword argument on the client. It takes instances of <code>httpx.Limits</code> which define:</p> <ul> <li><code>max_keepalive_connections</code>, number of allowable keep-alive connections, or <code>None</code> to always allow. (Defaults 20)</li> <li><code>max_connections</code>, maximum number of allowable connections, or <code>None</code> for no limits. (Default 100)</li> <li><code>keepalive_expiry</code>, time limit on idle keep-alive connections in seconds, or <code>None</code> for no limits. (Default 5)</li> </ul> <pre><code>limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)\nclient = httpx.Client(limits=limits)\n</code></pre>"},{"location":"advanced/ssl/","title":"SSL","text":"<p>When making a request over HTTPS, HTTPX needs to verify the identity of the requested host. To do this, it uses a bundle of SSL certificates (a.k.a. CA bundle) delivered by a trusted certificate authority (CA).</p>"},{"location":"advanced/ssl/#enabling-and-disabling-verification","title":"Enabling and disabling verification","text":"<p>By default httpx will verify HTTPS connections, and raise an error for invalid SSL cases...</p> <pre><code>>>> httpx.get(\"https://expired.badssl.com/\")\nhttpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)\n</code></pre> <p>You can disable SSL verification completely and allow insecure requests...</p> <pre><code>>>> httpx.get(\"https://expired.badssl.com/\", verify=False)\n<Response [200 OK]>\n</code></pre>"},{"location":"advanced/ssl/#configuring-client-instances","title":"Configuring client instances","text":"<p>If you're using a <code>Client()</code> instance you should pass any <code>verify=<...></code> configuration when instantiating the client.</p> <p>By default the certifi CA bundle is used for SSL verification.</p> <p>For more complex configurations you can pass an SSL Context instance...</p> <pre><code>import certifi\nimport httpx\nimport ssl\n\n# This SSL context is equivelent to the default `verify=True`.\nctx = ssl.create_default_context(cafile=certifi.where())\nclient = httpx.Client(verify=ctx)\n</code></pre> <p>Using the <code>truststore</code> package to support system certificate stores...</p> <pre><code>import ssl\nimport truststore\nimport httpx\n\n# Use system certificate stores.\nctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\nclient = httpx.Client(verify=ctx)\n</code></pre> <p>Loding an alternative certificate verification store using the standard SSL context API...</p> <pre><code>import httpx\nimport ssl\n\n# Use an explicitly configured certificate store.\nctx = ssl.create_default_context(cafile=\"path/to/certs.pem\") # Either cafile or capath.\nclient = httpx.Client(verify=ctx)\n</code></pre>"},{"location":"advanced/ssl/#client-side-certificates","title":"Client side certificates","text":"<p>Client side certificates allow a remote server to verify the client. They tend to be used within private organizations to authenticate requests to remote servers.</p> <p>You can specify client-side certificates, using the <code>.load_cert_chain()</code> API...</p> <pre><code>ctx = ssl.create_default_context()\nctx.load_cert_chain(certfile=\"path/to/client.pem\") # Optionally also keyfile or password.\nclient = httpx.Client(verify=ctx)\n</code></pre>"},{"location":"advanced/ssl/#working-with-ssl_cert_file-and-ssl_cert_dir","title":"Working with <code>SSL_CERT_FILE</code> and <code>SSL_CERT_DIR</code>","text":"<p>Unlike <code>requests</code>, the <code>httpx</code> package does not automatically pull in the environment variables <code>SSL_CERT_FILE</code> or <code>SSL_CERT_DIR</code>. If you want to use these they need to be enabled explicitly.</p> <p>For example...</p> <pre><code># Use `SSL_CERT_FILE` or `SSL_CERT_DIR` if configured.\n# Otherwise default to certifi.\nctx = ssl.create_default_context(\n cafile=os.environ.get(\"SSL_CERT_FILE\", certifi.where()),\n capath=os.environ.get(\"SSL_CERT_DIR\"),\n)\nclient = httpx.Client(verify=ctx)\n</code></pre>"},{"location":"advanced/ssl/#making-https-requests-to-a-local-server","title":"Making HTTPS requests to a local server","text":"<p>When making requests to local servers, such as a development server running on <code>localhost</code>, you will typically be using unencrypted HTTP connections.</p> <p>If you do need to make HTTPS connections to a local server, for example to test an HTTPS-only service, you will need to create and use your own certificates. Here's one way to do it...</p> <ol> <li>Use trustme to generate a pair of server key/cert files, and a client cert file.</li> <li>Pass the server key/cert files when starting your local server. (This depends on the particular web server you're using. For example, Uvicorn provides the <code>--ssl-keyfile</code> and <code>--ssl-certfile</code> options.)</li> <li>Configure <code>httpx</code> to use the certificates stored in <code>client.pem</code>.</li> </ol> <pre><code>ctx = ssl.create_default_context(cafile=\"client.pem\")\nclient = httpx.Client(verify=ctx)\n</code></pre>"},{"location":"advanced/text-encodings/","title":"Text Encodings","text":"<p>When accessing <code>response.text</code>, we need to decode the response bytes into a unicode text representation.</p> <p>By default <code>httpx</code> will use <code>\"charset\"</code> information included in the response <code>Content-Type</code> header to determine how the response bytes should be decoded into text.</p> <p>In cases where no charset information is included on the response, the default behaviour is to assume \"utf-8\" encoding, which is by far the most widely used text encoding on the internet.</p>"},{"location":"advanced/text-encodings/#using-the-default-encoding","title":"Using the default encoding","text":"<p>To understand this better let's start by looking at the default behaviour for text decoding...</p> <pre><code>import httpx\n# Instantiate a client with the default configuration.\nclient = httpx.Client()\n# Using the client...\nresponse = client.get(...)\nprint(response.encoding) # This will either print the charset given in\n # the Content-Type charset, or else \"utf-8\".\nprint(response.text) # The text will either be decoded with the Content-Type\n # charset, or using \"utf-8\".\n</code></pre> <p>This is normally absolutely fine. Most servers will respond with a properly formatted Content-Type header, including a charset encoding. And in most cases where no charset encoding is included, UTF-8 is very likely to be used, since it is so widely adopted.</p>"},{"location":"advanced/text-encodings/#using-an-explicit-encoding","title":"Using an explicit encoding","text":"<p>In some cases we might be making requests to a site where no character set information is being set explicitly by the server, but we know what the encoding is. In this case it's best to set the default encoding explicitly on the client.</p> <pre><code>import httpx\n# Instantiate a client with a Japanese character set as the default encoding.\nclient = httpx.Client(default_encoding=\"shift-jis\")\n# Using the client...\nresponse = client.get(...)\nprint(response.encoding) # This will either print the charset given in\n # the Content-Type charset, or else \"shift-jis\".\nprint(response.text) # The text will either be decoded with the Content-Type\n # charset, or using \"shift-jis\".\n</code></pre>"},{"location":"advanced/text-encodings/#using-auto-detection","title":"Using auto-detection","text":"<p>In cases where the server is not reliably including character set information, and where we don't know what encoding is being used, we can enable auto-detection to make a best-guess attempt when decoding from bytes to text.</p> <p>To use auto-detection you need to set the <code>default_encoding</code> argument to a callable instead of a string. This callable should be a function which takes the input bytes as an argument and returns the character set to use for decoding those bytes to text.</p> <p>There are two widely used Python packages which both handle this functionality:</p> <ul> <li><code>chardet</code> - This is a well established package, and is a port of the auto-detection code in Mozilla.</li> <li><code>charset-normalizer</code> - A newer package, motivated by <code>chardet</code>, with a different approach.</li> </ul> <p>Let's take a look at installing autodetection using one of these packages...</p> <pre><code>$ pip install httpx\n$ pip install chardet\n</code></pre> <p>Once <code>chardet</code> is installed, we can configure a client to use character-set autodetection.</p> <pre><code>import httpx\nimport chardet\n\ndef autodetect(content):\n return chardet.detect(content).get(\"encoding\")\n\n# Using a client with character-set autodetection enabled.\nclient = httpx.Client(default_encoding=autodetect)\nresponse = client.get(...)\nprint(response.encoding) # This will either print the charset given in\n # the Content-Type charset, or else the auto-detected\n # character set.\nprint(response.text)\n</code></pre>"},{"location":"advanced/timeouts/","title":"Timeouts","text":"<p>HTTPX is careful to enforce timeouts everywhere by default.</p> <p>The default behavior is to raise a <code>TimeoutException</code> after 5 seconds of network inactivity.</p>"},{"location":"advanced/timeouts/#setting-and-disabling-timeouts","title":"Setting and disabling timeouts","text":"<p>You can set timeouts for an individual request:</p> <pre><code># Using the top-level API:\nhttpx.get('http://example.com/api/v1/example', timeout=10.0)\n\n# Using a client instance:\nwith httpx.Client() as client:\n client.get(\"http://example.com/api/v1/example\", timeout=10.0)\n</code></pre> <p>Or disable timeouts for an individual request:</p> <pre><code># Using the top-level API:\nhttpx.get('http://example.com/api/v1/example', timeout=None)\n\n# Using a client instance:\nwith httpx.Client() as client:\n client.get(\"http://example.com/api/v1/example\", timeout=None)\n</code></pre>"},{"location":"advanced/timeouts/#setting-a-default-timeout-on-a-client","title":"Setting a default timeout on a client","text":"<p>You can set a timeout on a client instance, which results in the given <code>timeout</code> being used as the default for requests made with this client:</p> <pre><code>client = httpx.Client() # Use a default 5s timeout everywhere.\nclient = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.\nclient = httpx.Client(timeout=None) # Disable all timeouts by default.\n</code></pre>"},{"location":"advanced/timeouts/#fine-tuning-the-configuration","title":"Fine tuning the configuration","text":"<p>HTTPX also allows you to specify the timeout behavior in more fine grained detail.</p> <p>There are four different types of timeouts that may occur. These are connect, read, write, and pool timeouts.</p> <ul> <li>The connect timeout specifies the maximum amount of time to wait until a socket connection to the requested host is established. If HTTPX is unable to connect within this time frame, a <code>ConnectTimeout</code> exception is raised.</li> <li>The read timeout specifies the maximum duration to wait for a chunk of data to be received (for example, a chunk of the response body). If HTTPX is unable to receive data within this time frame, a <code>ReadTimeout</code> exception is raised.</li> <li>The write timeout specifies the maximum duration to wait for a chunk of data to be sent (for example, a chunk of the request body). If HTTPX is unable to send data within this time frame, a <code>WriteTimeout</code> exception is raised.</li> <li>The pool timeout specifies the maximum duration to wait for acquiring a connection from the connection pool. If HTTPX is unable to acquire a connection within this time frame, a <code>PoolTimeout</code> exception is raised. A related configuration here is the maximum number of allowable connections in the connection pool, which is configured by the <code>limits</code> argument.</li> </ul> <p>You can configure the timeout behavior for any of these values...</p> <pre><code># A client with a 60s timeout for connecting, and a 10s timeout elsewhere.\ntimeout = httpx.Timeout(10.0, connect=60.0)\nclient = httpx.Client(timeout=timeout)\n\nresponse = client.get('http://example.com/')\n</code></pre>"},{"location":"advanced/transports/","title":"Transports","text":"<p>HTTPX's <code>Client</code> also accepts a <code>transport</code> argument. This argument allows you to provide a custom Transport object that will be used to perform the actual sending of the requests.</p>"},{"location":"advanced/transports/#http-transport","title":"HTTP Transport","text":"<p>For some advanced configuration you might need to instantiate a transport class directly, and pass it to the client instance. One example is the <code>local_address</code> configuration which is only available via this low-level API.</p> <pre><code>>>> import httpx\n>>> transport = httpx.HTTPTransport(local_address=\"0.0.0.0\")\n>>> client = httpx.Client(transport=transport)\n</code></pre> <p>Connection retries are also available via this interface. Requests will be retried the given number of times in case an <code>httpx.ConnectError</code> or an <code>httpx.ConnectTimeout</code> occurs, allowing smoother operation under flaky networks. If you need other forms of retry behaviors, such as handling read/write errors or reacting to <code>503 Service Unavailable</code>, consider general-purpose tools such as tenacity.</p> <pre><code>>>> import httpx\n>>> transport = httpx.HTTPTransport(retries=1)\n>>> client = httpx.Client(transport=transport)\n</code></pre> <p>Similarly, instantiating a transport directly provides a <code>uds</code> option for connecting via a Unix Domain Socket that is only available via this low-level API:</p> <pre><code>>>> import httpx\n>>> # Connect to the Docker API via a Unix Socket.\n>>> transport = httpx.HTTPTransport(uds=\"/var/run/docker.sock\")\n>>> client = httpx.Client(transport=transport)\n>>> response = client.get(\"http://docker/info\")\n>>> response.json()\n{\"ID\": \"...\", \"Containers\": 4, \"Images\": 74, ...}\n</code></pre>"},{"location":"advanced/transports/#wsgi-transport","title":"WSGI Transport","text":"<p>You can configure an <code>httpx</code> client to call directly into a Python web application using the WSGI protocol.</p> <p>This is particularly useful for two main use-cases:</p> <ul> <li>Using <code>httpx</code> as a client inside test cases.</li> <li>Mocking out external services during tests or in dev or staging environments.</li> </ul>"},{"location":"advanced/transports/#example","title":"Example","text":"<p>Here's an example of integrating against a Flask application:</p> <pre><code>from flask import Flask\nimport httpx\n\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello World!\"\n\ntransport = httpx.WSGITransport(app=app)\nwith httpx.Client(transport=transport, base_url=\"http://testserver\") as client:\n r = client.get(\"/\")\n assert r.status_code == 200\n assert r.text == \"Hello World!\"\n</code></pre>"},{"location":"advanced/transports/#configuration","title":"Configuration","text":"<p>For some more complex cases you might need to customize the WSGI transport. This allows you to:</p> <ul> <li>Inspect 500 error responses rather than raise exceptions by setting <code>raise_app_exceptions=False</code>.</li> <li>Mount the WSGI application at a subpath by setting <code>script_name</code> (WSGI).</li> <li>Use a given client address for requests by setting <code>remote_addr</code> (WSGI).</li> </ul> <p>For example:</p> <pre><code># Instantiate a client that makes WSGI requests with a client IP of \"1.2.3.4\".\ntransport = httpx.WSGITransport(app=app, remote_addr=\"1.2.3.4\")\nwith httpx.Client(transport=transport, base_url=\"http://testserver\") as client:\n ...\n</code></pre>"},{"location":"advanced/transports/#asgi-transport","title":"ASGI Transport","text":"<p>You can configure an <code>httpx</code> client to call directly into an async Python web application using the ASGI protocol.</p> <p>This is particularly useful for two main use-cases:</p> <ul> <li>Using <code>httpx</code> as a client inside test cases.</li> <li>Mocking out external services during tests or in dev or staging environments.</li> </ul>"},{"location":"advanced/transports/#example_1","title":"Example","text":"<p>Let's take this Starlette application as an example:</p> <pre><code>from starlette.applications import Starlette\nfrom starlette.responses import HTMLResponse\nfrom starlette.routing import Route\n\n\nasync def hello(request):\n return HTMLResponse(\"Hello World!\")\n\n\napp = Starlette(routes=[Route(\"/\", hello)])\n</code></pre> <p>We can make requests directly against the application, like so:</p> <pre><code>transport = httpx.ASGITransport(app=app)\n\nasync with httpx.AsyncClient(transport=transport, base_url=\"http://testserver\") as client:\n r = await client.get(\"/\")\n assert r.status_code == 200\n assert r.text == \"Hello World!\"\n</code></pre>"},{"location":"advanced/transports/#configuration_1","title":"Configuration","text":"<p>For some more complex cases you might need to customise the ASGI transport. This allows you to:</p> <ul> <li>Inspect 500 error responses rather than raise exceptions by setting <code>raise_app_exceptions=False</code>.</li> <li>Mount the ASGI application at a subpath by setting <code>root_path</code>.</li> <li>Use a given client address for requests by setting <code>client</code>.</li> </ul> <p>For example:</p> <pre><code># Instantiate a client that makes ASGI requests with a client IP of \"1.2.3.4\",\n# on port 123.\ntransport = httpx.ASGITransport(app=app, client=(\"1.2.3.4\", 123))\nasync with httpx.AsyncClient(transport=transport, base_url=\"http://testserver\") as client:\n ...\n</code></pre> <p>See the ASGI documentation for more details on the <code>client</code> and <code>root_path</code> keys.</p>"},{"location":"advanced/transports/#asgi-startup-and-shutdown","title":"ASGI startup and shutdown","text":"<p>It is not in the scope of HTTPX to trigger ASGI lifespan events of your app.</p> <p>However it is suggested to use <code>LifespanManager</code> from asgi-lifespan in pair with <code>AsyncClient</code>.</p>"},{"location":"advanced/transports/#custom-transports","title":"Custom transports","text":"<p>A transport instance must implement the low-level Transport API which deals with sending a single request, and returning a response. You should either subclass <code>httpx.BaseTransport</code> to implement a transport to use with <code>Client</code>, or subclass <code>httpx.AsyncBaseTransport</code> to implement a transport to use with <code>AsyncClient</code>.</p> <p>At the layer of the transport API we're using the familiar <code>Request</code> and <code>Response</code> models.</p> <p>See the <code>handle_request</code> and <code>handle_async_request</code> docstrings for more details on the specifics of the Transport API.</p> <p>A complete example of a custom transport implementation would be:</p> <pre><code>import json\nimport httpx\n\nclass HelloWorldTransport(httpx.BaseTransport):\n \"\"\"\n A mock transport that always returns a JSON \"Hello, world!\" response.\n \"\"\"\n\n def handle_request(self, request):\n return httpx.Response(200, json={\"text\": \"Hello, world!\"})\n</code></pre> <p>Or this example, which uses a custom transport and <code>httpx.Mounts</code> to always redirect <code>http://</code> requests.</p> <pre><code>class HTTPSRedirect(httpx.BaseTransport):\n \"\"\"\n A transport that always redirects to HTTPS.\n \"\"\"\n def handle_request(self, request):\n url = request.url.copy_with(scheme=\"https\")\n return httpx.Response(303, headers={\"Location\": str(url)})\n\n# A client where any `http` requests are always redirected to `https`\ntransport = httpx.Mounts({\n 'http://': HTTPSRedirect()\n 'https://': httpx.HTTPTransport()\n})\nclient = httpx.Client(transport=transport)\n</code></pre> <p>A useful pattern here is custom transport classes that wrap the default HTTP implementation. For example...</p> <pre><code>class DebuggingTransport(httpx.BaseTransport):\n def __init__(self, **kwargs):\n self._wrapper = httpx.HTTPTransport(**kwargs)\n\n def handle_request(self, request):\n print(f\">>> {request}\")\n response = self._wrapper.handle_request(request)\n print(f\"<<< {response}\")\n return response\n\n def close(self):\n self._wrapper.close()\n\ntransport = DebuggingTransport()\nclient = httpx.Client(transport=transport)\n</code></pre> <p>Here's another case, where we're using a round-robin across a number of different proxies...</p> <pre><code>class ProxyRoundRobin(httpx.BaseTransport):\n def __init__(self, proxies, **kwargs):\n self._transports = [\n httpx.HTTPTransport(proxy=proxy, **kwargs)\n for proxy in proxies\n ]\n self._idx = 0\n\n def handle_request(self, request):\n transport = self._transports[self._idx]\n self._idx = (self._idx + 1) % len(self._transports)\n return transport.handle_request(request)\n\n def close(self):\n for transport in self._transports:\n transport.close()\n\nproxies = [\n httpx.Proxy(\"http://127.0.0.1:8081\"),\n httpx.Proxy(\"http://127.0.0.1:8082\"),\n httpx.Proxy(\"http://127.0.0.1:8083\"),\n]\ntransport = ProxyRoundRobin(proxies=proxies)\nclient = httpx.Client(transport=transport)\n</code></pre>"},{"location":"advanced/transports/#mock-transports","title":"Mock transports","text":"<p>During testing it can often be useful to be able to mock out a transport, and return pre-determined responses, rather than making actual network requests.</p> <p>The <code>httpx.MockTransport</code> class accepts a handler function, which can be used to map requests onto pre-determined responses:</p> <pre><code>def handler(request):\n return httpx.Response(200, json={\"text\": \"Hello, world!\"})\n\n\n# Switch to a mock transport, if the TESTING environment variable is set.\nif os.environ.get('TESTING', '').upper() == \"TRUE\":\n transport = httpx.MockTransport(handler)\nelse:\n transport = httpx.HTTPTransport()\n\nclient = httpx.Client(transport=transport)\n</code></pre> <p>For more advanced use-cases you might want to take a look at either the third-party mocking library, RESPX, or the pytest-httpx library.</p>"},{"location":"advanced/transports/#mounting-transports","title":"Mounting transports","text":"<p>You can also mount transports against given schemes or domains, to control which transport an outgoing request should be routed via, with the same style used for specifying proxy routing.</p> <pre><code>import httpx\n\nclass HTTPSRedirectTransport(httpx.BaseTransport):\n \"\"\"\n A transport that always redirects to HTTPS.\n \"\"\"\n\n def handle_request(self, method, url, headers, stream, extensions):\n scheme, host, port, path = url\n if port is None:\n location = b\"https://%s%s\" % (host, path)\n else:\n location = b\"https://%s:%d%s\" % (host, port, path)\n stream = httpx.ByteStream(b\"\")\n headers = [(b\"location\", location)]\n extensions = {}\n return 303, headers, stream, extensions\n\n\n# A client where any `http` requests are always redirected to `https`\nmounts = {'http://': HTTPSRedirectTransport()}\nclient = httpx.Client(mounts=mounts)\n</code></pre> <p>A couple of other sketches of how you might take advantage of mounted transports...</p> <p>Disabling HTTP/2 on a single given domain...</p> <pre><code>mounts = {\n \"all://\": httpx.HTTPTransport(http2=True),\n \"all://*example.org\": httpx.HTTPTransport()\n}\nclient = httpx.Client(mounts=mounts)\n</code></pre> <p>Mocking requests to a given domain:</p> <pre><code># All requests to \"example.org\" should be mocked out.\n# Other requests occur as usual.\ndef handler(request):\n return httpx.Response(200, json={\"text\": \"Hello, World!\"})\n\nmounts = {\"all://example.org\": httpx.MockTransport(handler)}\nclient = httpx.Client(mounts=mounts)\n</code></pre> <p>Adding support for custom schemes:</p> <pre><code># Support URLs like \"file:///Users/sylvia_green/websites/new_client/index.html\"\nmounts = {\"file://\": FileSystemTransport()}\nclient = httpx.Client(mounts=mounts)\n</code></pre>"},{"location":"advanced/transports/#routing","title":"Routing","text":"<p>HTTPX provides a powerful mechanism for routing requests, allowing you to write complex rules that specify which transport should be used for each request.</p> <p>The <code>mounts</code> dictionary maps URL patterns to HTTP transports. HTTPX matches requested URLs against URL patterns to decide which transport should be used, if any. Matching is done from most specific URL patterns (e.g. <code>https://<domain>:<port></code>) to least specific ones (e.g. <code>https://</code>).</p> <p>HTTPX supports routing requests based on scheme, domain, port, or a combination of these.</p>"},{"location":"advanced/transports/#wildcard-routing","title":"Wildcard routing","text":"<p>Route everything through a transport...</p> <pre><code>mounts = {\n \"all://\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre>"},{"location":"advanced/transports/#scheme-routing","title":"Scheme routing","text":"<p>Route HTTP requests through one transport, and HTTPS requests through another...</p> <pre><code>mounts = {\n \"http://\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n \"https://\": httpx.HTTPTransport(proxy=\"http://localhost:8031\"),\n}\n</code></pre>"},{"location":"advanced/transports/#domain-routing","title":"Domain routing","text":"<p>Proxy all requests on domain \"example.com\", let other requests pass through...</p> <pre><code>mounts = {\n \"all://example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre> <p>Proxy HTTP requests on domain \"example.com\", let HTTPS and other requests pass through...</p> <pre><code>mounts = {\n \"http://example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre> <p>Proxy all requests to \"example.com\" and its subdomains, let other requests pass through...</p> <pre><code>mounts = {\n \"all://*example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre> <p>Proxy all requests to strict subdomains of \"example.com\", let \"example.com\" and other requests pass through...</p> <pre><code>mounts = {\n \"all://*.example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre>"},{"location":"advanced/transports/#port-routing","title":"Port routing","text":"<p>Proxy HTTPS requests on port 1234 to \"example.com\"...</p> <pre><code>mounts = {\n \"https://example.com:1234\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre> <p>Proxy all requests on port 1234...</p> <pre><code>mounts = {\n \"all://*:1234\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre>"},{"location":"advanced/transports/#no-proxy-support","title":"No-proxy support","text":"<p>It is also possible to define requests that shouldn't be routed through the transport.</p> <p>To do so, pass <code>None</code> as the proxy URL. For example...</p> <pre><code>mounts = {\n # Route requests through a proxy by default...\n \"all://\": httpx.HTTPTransport(proxy=\"http://localhost:8031\"),\n # Except those for \"example.com\".\n \"all://example.com\": None,\n}\n</code></pre>"},{"location":"advanced/transports/#complex-configuration-example","title":"Complex configuration example","text":"<p>You can combine the routing features outlined above to build complex proxy routing configurations. For example...</p> <pre><code>mounts = {\n # Route all traffic through a proxy by default...\n \"all://\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n # But don't use proxies for HTTPS requests to \"domain.io\"...\n \"https://domain.io\": None,\n # And use another proxy for requests to \"example.com\" and its subdomains...\n \"all://*example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8031\"),\n # And yet another proxy if HTTP is used,\n # and the \"internal\" subdomain on port 5550 is requested...\n \"http://internal.example.com:5550\": httpx.HTTPTransport(proxy=\"http://localhost:8032\"),\n}\n</code></pre>"},{"location":"advanced/transports/#environment-variables","title":"Environment variables","text":"<p>There are also environment variables that can be used to control the dictionary of the client mounts. They can be used to configure HTTP proxying for clients.</p> <p>See documentation on <code>HTTP_PROXY</code>, <code>HTTPS_PROXY</code>, <code>ALL_PROXY</code> and <code>NO_PROXY</code> for more information.</p>"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Introduction","text":"HTTPX A next-generation HTTP client for Python. <p>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.</p> <p>Install HTTPX using pip:</p> <pre><code>$ pip install httpx\n</code></pre> <p>Now, let's get started:</p> <pre><code>>>> import httpx\n>>> r = httpx.get('https://www.example.org/')\n>>> r\n<Response [200 OK]>\n>>> r.status_code\n200\n>>> r.headers['content-type']\n'text/html; charset=UTF-8'\n>>> r.text\n'<!doctype html>\\n<html>\\n<head>\\n<title>Example Domain</title>...'\n</code></pre> <p>Or, using the command-line client.</p> <pre><code># The command line client is an optional dependency.\n$ pip install 'httpx[cli]'\n</code></pre> <p>Which now allows us to use HTTPX directly from the command-line...</p> <p></p> <p>Sending a request...</p> <p></p>"},{"location":"#features","title":"Features","text":"<p>HTTPX builds on the well-established usability of <code>requests</code>, and gives you:</p> <ul> <li>A broadly requests-compatible API.</li> <li>Standard synchronous interface, but with async support if you need it.</li> <li>HTTP/1.1 and HTTP/2 support.</li> <li>Ability to make requests directly to WSGI applications or ASGI applications.</li> <li>Strict timeouts everywhere.</li> <li>Fully type annotated.</li> <li>100% test coverage.</li> </ul> <p>Plus all the standard features of <code>requests</code>...</p> <ul> <li>International Domains and URLs</li> <li>Keep-Alive & Connection Pooling</li> <li>Sessions with Cookie Persistence</li> <li>Browser-style SSL Verification</li> <li>Basic/Digest Authentication</li> <li>Elegant Key/Value Cookies</li> <li>Automatic Decompression</li> <li>Automatic Content Decoding</li> <li>Unicode Response Bodies</li> <li>Multipart File Uploads</li> <li>HTTP(S) Proxy Support</li> <li>Connection Timeouts</li> <li>Streaming Downloads</li> <li>.netrc Support</li> <li>Chunked Requests</li> </ul>"},{"location":"#documentation","title":"Documentation","text":"<p>For a run-through of all the basics, head over to the QuickStart.</p> <p>For more advanced topics, see the Advanced section, the async support section, or the HTTP/2 section.</p> <p>The Developer Interface provides a comprehensive API reference.</p> <p>To find out about tools that integrate with HTTPX, see Third Party Packages.</p>"},{"location":"#dependencies","title":"Dependencies","text":"<p>The HTTPX project relies on these excellent libraries:</p> <ul> <li><code>httpcore</code> - The underlying transport implementation for <code>httpx</code>.</li> <li><code>h11</code> - HTTP/1.1 support.</li> <li><code>certifi</code> - SSL certificates.</li> <li><code>idna</code> - Internationalized domain name support.</li> <li><code>sniffio</code> - Async library autodetection.</li> </ul> <p>As well as these optional installs:</p> <ul> <li><code>h2</code> - HTTP/2 support. (Optional, with <code>httpx[http2]</code>)</li> <li><code>socksio</code> - SOCKS proxy support. (Optional, with <code>httpx[socks]</code>)</li> <li><code>rich</code> - Rich terminal support. (Optional, with <code>httpx[cli]</code>)</li> <li><code>click</code> - Command line client support. (Optional, with <code>httpx[cli]</code>)</li> <li><code>brotli</code> or <code>brotlicffi</code> - Decoding for \"brotli\" compressed responses. (Optional, with <code>httpx[brotli]</code>)</li> <li><code>zstandard</code> - Decoding for \"zstd\" compressed responses. (Optional, with <code>httpx[zstd]</code>)</li> </ul> <p>A huge amount of credit is due to <code>requests</code> for the API layout that much of this work follows, as well as to <code>urllib3</code> for plenty of design inspiration around the lower-level networking details.</p>"},{"location":"#installation","title":"Installation","text":"<p>Install with pip:</p> <pre><code>$ pip install httpx\n</code></pre> <p>Or, to include the optional HTTP/2 support, use:</p> <pre><code>$ pip install httpx[http2]\n</code></pre> <p>To include the optional brotli and zstandard decoders support, use:</p> <pre><code>$ pip install httpx[brotli,zstd]\n</code></pre> <p>HTTPX requires Python 3.9+</p>"},{"location":"api/","title":"Developer Interface","text":""},{"location":"api/#helper-functions","title":"Helper Functions","text":"<p>Note</p> <p>Only use these functions if you're testing HTTPX in a console or making a small number of requests. Using a <code>Client</code> will enable HTTP/2 and connection pooling for more efficient and long-lived connections.</p> <code>httpx.request</code>(method, url, *, params=None, content=None, data=None, files=None, json=None, headers=None, cookies=None, auth=None, proxy=None, timeout=Timeout(timeout=5.0), follow_redirects=False, verify=True, trust_env=True) <p>Sends an HTTP request.</p> <p>Parameters:</p> <ul> <li>method - HTTP method for the new <code>Request</code> object: <code>GET</code>, <code>OPTIONS</code>, <code>HEAD</code>, <code>POST</code>, <code>PUT</code>, <code>PATCH</code>, or <code>DELETE</code>.</li> <li>url - URL for the new <code>Request</code> object.</li> <li>params - (optional) Query parameters to include in the URL, as a string, dictionary, or sequence of two-tuples.</li> <li>content - (optional) Binary content to include in the body of the request, as bytes or a byte iterator.</li> <li>data - (optional) Form data to include in the body of the request, as a dictionary.</li> <li>files - (optional) A dictionary of upload files to include in the body of the request.</li> <li>json - (optional) A JSON serializable object to include in the body of the request.</li> <li>headers - (optional) Dictionary of HTTP headers to include in the request.</li> <li>cookies - (optional) Dictionary of Cookie items to include in the request.</li> <li>auth - (optional) An authentication class to use when sending the request.</li> <li>proxy - (optional) A proxy URL where all the traffic should be routed.</li> <li>timeout - (optional) The timeout configuration to use when sending the request.</li> <li>follow_redirects - (optional) Enables or disables HTTP redirects.</li> <li>verify - (optional) Either <code>True</code> to use an SSL context with the default CA bundle, <code>False</code> to disable verification, or an instance of <code>ssl.SSLContext</code> to use a custom context.</li> <li>trust_env - (optional) Enables or disables usage of environment variables for configuration.</li> </ul> <p>Returns: <code>Response</code></p> <p>Usage:</p> <pre><code>>>> import httpx\n>>> response = httpx.request('GET', 'https://httpbin.org/get')\n>>> response\n<Response [200 OK]>\n</code></pre> <code>httpx.get</code>(url, *, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>GET</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>Note that the <code>data</code>, <code>files</code>, <code>json</code> and <code>content</code> parameters are not available on this function, as <code>GET</code> requests should not include a request body.</p> <code>httpx.options</code>(url, *, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends an <code>OPTIONS</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>Note that the <code>data</code>, <code>files</code>, <code>json</code> and <code>content</code> parameters are not available on this function, as <code>OPTIONS</code> requests should not include a request body.</p> <code>httpx.head</code>(url, *, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>HEAD</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>Note that the <code>data</code>, <code>files</code>, <code>json</code> and <code>content</code> parameters are not available on this function, as <code>HEAD</code> requests should not include a request body.</p> <code>httpx.post</code>(url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>POST</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>httpx.put</code>(url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>PUT</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>httpx.patch</code>(url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, verify=True, timeout=Timeout(timeout=5.0), trust_env=True) <p>Sends a <code>PATCH</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>httpx.delete</code>(url, *, params=None, headers=None, cookies=None, auth=None, proxy=None, follow_redirects=False, timeout=Timeout(timeout=5.0), verify=True, trust_env=True) <p>Sends a <code>DELETE</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>Note that the <code>data</code>, <code>files</code>, <code>json</code> and <code>content</code> parameters are not available on this function, as <code>DELETE</code> requests should not include a request body.</p> <code>httpx.stream</code>(method, url, *, params=None, content=None, data=None, files=None, json=None, headers=None, cookies=None, auth=None, proxy=None, timeout=Timeout(timeout=5.0), follow_redirects=False, verify=True, trust_env=True) <p>Alternative to <code>httpx.request()</code> that streams the response body instead of loading it into memory at once.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>See also: Streaming Responses</p>"},{"location":"api/#client","title":"<code>Client</code>","text":"class <code>httpx.Client</code>(*, auth=None, params=None, headers=None, cookies=None, verify=True, cert=None, trust_env=True, http1=True, http2=False, proxy=None, mounts=None, timeout=Timeout(timeout=5.0), follow_redirects=False, limits=Limits(max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0), max_redirects=20, event_hooks=None, base_url='', transport=None, default_encoding='utf-8') <p>An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.</p> <p>It can be shared between threads.</p> <p>Usage:</p> <pre><code>>>> client = httpx.Client()\n>>> response = client.get('https://example.org')\n</code></pre> <p>Parameters:</p> <ul> <li>auth - (optional) An authentication class to use when sending requests.</li> <li>params - (optional) Query parameters to include in request URLs, as a string, dictionary, or sequence of two-tuples.</li> <li>headers - (optional) Dictionary of HTTP headers to include when sending requests.</li> <li>cookies - (optional) Dictionary of Cookie items to include when sending requests.</li> <li>verify - (optional) Either <code>True</code> to use an SSL context with the default CA bundle, <code>False</code> to disable verification, or an instance of <code>ssl.SSLContext</code> to use a custom context.</li> <li>http2 - (optional) A boolean indicating if HTTP/2 support should be enabled. Defaults to <code>False</code>.</li> <li>proxy - (optional) A proxy URL where all the traffic should be routed.</li> <li>timeout - (optional) The timeout configuration to use when sending requests.</li> <li>limits - (optional) The limits configuration to use.</li> <li>max_redirects - (optional) The maximum number of redirect responses that should be followed.</li> <li>base_url - (optional) A URL to use as the base when building request URLs.</li> <li>transport - (optional) A transport class to use for sending requests over the network.</li> <li>trust_env - (optional) Enables or disables usage of environment variables for configuration.</li> <li>default_encoding - (optional) The default encoding to use for decoding response text, if no charset information is included in a response Content-Type header. Set to a callable for automatic character set detection. Default: \"utf-8\".</li> </ul> <code>headers</code> <p>HTTP headers to include when sending requests.</p> <code>cookies</code> <p>Cookie values to include when sending requests.</p> <code>params</code> <p>Query parameters to include in the URL when sending requests.</p> <code>auth</code> <p>Authentication class used when none is passed at the request-level.</p> <p>See also Authentication.</p> <code>request</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Build and send a request.</p> <p>Equivalent to:</p> <pre><code>request = client.build_request(...)\nresponse = client.send(request, ...)\n</code></pre> <p>See <code>Client.build_request()</code>, <code>Client.send()</code> and Merging of configuration for how the various parameters are merged with client-level configuration.</p> <code>get</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>GET</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>head</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>HEAD</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>options</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send an <code>OPTIONS</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>post</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>POST</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>put</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>PUT</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>patch</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>PATCH</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>delete</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>DELETE</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>stream</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Alternative to <code>httpx.request()</code> that streams the response body instead of loading it into memory at once.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>See also: Streaming Responses</p> <code>build_request</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, timeout=, extensions=None) <p>Build and return a request instance.</p> <ul> <li>The <code>params</code>, <code>headers</code> and <code>cookies</code> arguments are merged with any values set on the client.</li> <li>The <code>url</code> argument is merged with any <code>base_url</code> set on the client.</li> </ul> <p>See also: Request instances</p> <code>send</code>(self, request, *, stream=False, auth=, follow_redirects=) <p>Send a request.</p> <p>The request is sent as-is, unmodified.</p> <p>Typically you'll want to build one with <code>Client.build_request()</code> so that any client-level configuration is merged into the request, but passing an explicit <code>httpx.Request()</code> is supported as well.</p> <p>See also: Request instances</p> <code>close</code>(self) <p>Close transport and proxies.</p>"},{"location":"api/#asyncclient","title":"<code>AsyncClient</code>","text":"class <code>httpx.AsyncClient</code>(*, auth=None, params=None, headers=None, cookies=None, verify=True, cert=None, http1=True, http2=False, proxy=None, mounts=None, timeout=Timeout(timeout=5.0), follow_redirects=False, limits=Limits(max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0), max_redirects=20, event_hooks=None, base_url='', transport=None, trust_env=True, default_encoding='utf-8') <p>An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.</p> <p>It can be shared between tasks.</p> <p>Usage:</p> <pre><code>>>> async with httpx.AsyncClient() as client:\n>>> response = await client.get('https://example.org')\n</code></pre> <p>Parameters:</p> <ul> <li>auth - (optional) An authentication class to use when sending requests.</li> <li>params - (optional) Query parameters to include in request URLs, as a string, dictionary, or sequence of two-tuples.</li> <li>headers - (optional) Dictionary of HTTP headers to include when sending requests.</li> <li>cookies - (optional) Dictionary of Cookie items to include when sending requests.</li> <li>verify - (optional) Either <code>True</code> to use an SSL context with the default CA bundle, <code>False</code> to disable verification, or an instance of <code>ssl.SSLContext</code> to use a custom context.</li> <li>http2 - (optional) A boolean indicating if HTTP/2 support should be enabled. Defaults to <code>False</code>.</li> <li>proxy - (optional) A proxy URL where all the traffic should be routed.</li> <li>timeout - (optional) The timeout configuration to use when sending requests.</li> <li>limits - (optional) The limits configuration to use.</li> <li>max_redirects - (optional) The maximum number of redirect responses that should be followed.</li> <li>base_url - (optional) A URL to use as the base when building request URLs.</li> <li>transport - (optional) A transport class to use for sending requests over the network.</li> <li>trust_env - (optional) Enables or disables usage of environment variables for configuration.</li> <li>default_encoding - (optional) The default encoding to use for decoding response text, if no charset information is included in a response Content-Type header. Set to a callable for automatic character set detection. Default: \"utf-8\".</li> </ul> <code>headers</code> <p>HTTP headers to include when sending requests.</p> <code>cookies</code> <p>Cookie values to include when sending requests.</p> <code>params</code> <p>Query parameters to include in the URL when sending requests.</p> <code>auth</code> <p>Authentication class used when none is passed at the request-level.</p> <p>See also Authentication.</p> async <code>request</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Build and send a request.</p> <p>Equivalent to:</p> <pre><code>request = client.build_request(...)\nresponse = await client.send(request, ...)\n</code></pre> <p>See <code>AsyncClient.build_request()</code>, <code>AsyncClient.send()</code> and Merging of configuration for how the various parameters are merged with client-level configuration.</p> async <code>get</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>GET</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>head</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>HEAD</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>options</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send an <code>OPTIONS</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>post</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>POST</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>put</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>PUT</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>patch</code>(self, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>PATCH</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> async <code>delete</code>(self, url, *, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Send a <code>DELETE</code> request.</p> <p>Parameters: See <code>httpx.request</code>.</p> <code>stream</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=, follow_redirects=, timeout=, extensions=None) <p>Alternative to <code>httpx.request()</code> that streams the response body instead of loading it into memory at once.</p> <p>Parameters: See <code>httpx.request</code>.</p> <p>See also: Streaming Responses</p> <code>build_request</code>(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, timeout=, extensions=None) <p>Build and return a request instance.</p> <ul> <li>The <code>params</code>, <code>headers</code> and <code>cookies</code> arguments are merged with any values set on the client.</li> <li>The <code>url</code> argument is merged with any <code>base_url</code> set on the client.</li> </ul> <p>See also: Request instances</p> async <code>send</code>(self, request, *, stream=False, auth=, follow_redirects=) <p>Send a request.</p> <p>The request is sent as-is, unmodified.</p> <p>Typically you'll want to build one with <code>AsyncClient.build_request()</code> so that any client-level configuration is merged into the request, but passing an explicit <code>httpx.Request()</code> is supported as well.</p> <p>See also: Request instances</p> async <code>aclose</code>(self) <p>Close transport and proxies.</p>"},{"location":"api/#response","title":"<code>Response</code>","text":"<p>An HTTP response.</p> <ul> <li><code>def __init__(...)</code></li> <li><code>.status_code</code> - int</li> <li><code>.reason_phrase</code> - str</li> <li><code>.http_version</code> - <code>\"HTTP/2\"</code> or <code>\"HTTP/1.1\"</code></li> <li><code>.url</code> - URL</li> <li><code>.headers</code> - Headers</li> <li><code>.content</code> - bytes</li> <li><code>.text</code> - str</li> <li><code>.encoding</code> - str</li> <li><code>.is_redirect</code> - bool</li> <li><code>.request</code> - Request</li> <li><code>.next_request</code> - Optional[Request]</li> <li><code>.cookies</code> - Cookies</li> <li><code>.history</code> - List[Response]</li> <li><code>.elapsed</code> - timedelta</li> <li>The amount of time elapsed between sending the request and calling <code>close()</code> on the corresponding response received for that request. total_seconds() to correctly get the total elapsed seconds.</li> <li><code>def .raise_for_status()</code> - Response</li> <li><code>def .json()</code> - Any</li> <li><code>def .read()</code> - bytes</li> <li><code>def .iter_raw([chunk_size])</code> - bytes iterator</li> <li><code>def .iter_bytes([chunk_size])</code> - bytes iterator</li> <li><code>def .iter_text([chunk_size])</code> - text iterator</li> <li><code>def .iter_lines()</code> - text iterator</li> <li><code>def .close()</code> - None</li> <li><code>def .next()</code> - Response</li> <li><code>def .aread()</code> - bytes</li> <li><code>def .aiter_raw([chunk_size])</code> - async bytes iterator</li> <li><code>def .aiter_bytes([chunk_size])</code> - async bytes iterator</li> <li><code>def .aiter_text([chunk_size])</code> - async text iterator</li> <li><code>def .aiter_lines()</code> - async text iterator</li> <li><code>def .aclose()</code> - None</li> <li><code>def .anext()</code> - Response</li> </ul>"},{"location":"api/#request","title":"<code>Request</code>","text":"<p>An HTTP request. Can be constructed explicitly for more control over exactly what gets sent over the wire.</p> <pre><code>>>> request = httpx.Request(\"GET\", \"https://example.org\", headers={'host': 'example.org'})\n>>> response = client.send(request)\n</code></pre> <ul> <li><code>def __init__(method, url, [params], [headers], [cookies], [content], [data], [files], [json], [stream])</code></li> <li><code>.method</code> - str</li> <li><code>.url</code> - URL</li> <li><code>.content</code> - byte, byte iterator, or byte async iterator</li> <li><code>.headers</code> - Headers</li> <li><code>.cookies</code> - Cookies</li> </ul>"},{"location":"api/#url","title":"<code>URL</code>","text":"<p>A normalized, IDNA supporting URL.</p> <pre><code>>>> url = URL(\"https://example.org/\")\n>>> url.host\n'example.org'\n</code></pre> <ul> <li><code>def __init__(url, **kwargs)</code></li> <li><code>.scheme</code> - str</li> <li><code>.authority</code> - str</li> <li><code>.host</code> - str</li> <li><code>.port</code> - int</li> <li><code>.path</code> - str</li> <li><code>.query</code> - str</li> <li><code>.raw_path</code> - str</li> <li><code>.fragment</code> - str</li> <li><code>.is_ssl</code> - bool</li> <li><code>.is_absolute_url</code> - bool</li> <li><code>.is_relative_url</code> - bool</li> <li><code>def .copy_with([scheme], [authority], [path], [query], [fragment])</code> - URL</li> </ul>"},{"location":"api/#headers","title":"<code>Headers</code>","text":"<p>A case-insensitive multi-dict.</p> <pre><code>>>> headers = Headers({'Content-Type': 'application/json'})\n>>> headers['content-type']\n'application/json'\n</code></pre> <ul> <li><code>def __init__(self, headers, encoding=None)</code></li> <li><code>def copy()</code> - Headers</li> </ul>"},{"location":"api/#cookies","title":"<code>Cookies</code>","text":"<p>A dict-like cookie store.</p> <pre><code>>>> cookies = Cookies()\n>>> cookies.set(\"name\", \"value\", domain=\"example.org\")\n</code></pre> <ul> <li><code>def __init__(cookies: [dict, Cookies, CookieJar])</code></li> <li><code>.jar</code> - CookieJar</li> <li><code>def extract_cookies(response)</code></li> <li><code>def set_cookie_header(request)</code></li> <li><code>def set(name, value, [domain], [path])</code></li> <li><code>def get(name, [domain], [path])</code></li> <li><code>def delete(name, [domain], [path])</code></li> <li><code>def clear([domain], [path])</code></li> <li>Standard mutable mapping interface</li> </ul>"},{"location":"api/#proxy","title":"<code>Proxy</code>","text":"<p>A configuration of the proxy server.</p> <pre><code>>>> proxy = Proxy(\"http://proxy.example.com:8030\")\n>>> client = Client(proxy=proxy)\n</code></pre> <ul> <li><code>def __init__(url, [ssl_context], [auth], [headers])</code></li> <li><code>.url</code> - URL</li> <li><code>.auth</code> - tuple[str, str]</li> <li><code>.headers</code> - Headers</li> <li><code>.ssl_context</code> - SSLContext</li> </ul>"},{"location":"async/","title":"Async Support","text":"<p>HTTPX offers a standard synchronous API by default, but also gives you the option of an async client if you need it.</p> <p>Async is a concurrency model that is far more efficient than multi-threading, and can provide significant performance benefits and enable the use of long-lived network connections such as WebSockets.</p> <p>If you're working with an async web framework then you'll also want to use an async client for sending outgoing HTTP requests.</p>"},{"location":"async/#making-async-requests","title":"Making Async requests","text":"<p>To make asynchronous requests, you'll need an <code>AsyncClient</code>.</p> <pre><code>>>> async with httpx.AsyncClient() as client:\n... r = await client.get('https://www.example.com/')\n...\n>>> r\n<Response [200 OK]>\n</code></pre> <p>Tip</p> <p>Use IPython or Python 3.9+ with <code>python -m asyncio</code> to try this code interactively, as they support executing <code>async</code>/<code>await</code> expressions in the console.</p>"},{"location":"async/#api-differences","title":"API Differences","text":"<p>If you're using an async client then there are a few bits of API that use async methods.</p>"},{"location":"async/#making-requests","title":"Making requests","text":"<p>The request methods are all async, so you should use <code>response = await client.get(...)</code> style for all of the following:</p> <ul> <li><code>AsyncClient.get(url, ...)</code></li> <li><code>AsyncClient.options(url, ...)</code></li> <li><code>AsyncClient.head(url, ...)</code></li> <li><code>AsyncClient.post(url, ...)</code></li> <li><code>AsyncClient.put(url, ...)</code></li> <li><code>AsyncClient.patch(url, ...)</code></li> <li><code>AsyncClient.delete(url, ...)</code></li> <li><code>AsyncClient.request(method, url, ...)</code></li> <li><code>AsyncClient.send(request, ...)</code></li> </ul>"},{"location":"async/#opening-and-closing-clients","title":"Opening and closing clients","text":"<p>Use <code>async with httpx.AsyncClient()</code> if you want a context-managed client...</p> <pre><code>async with httpx.AsyncClient() as client:\n ...\n</code></pre> <p>Warning</p> <p>In order to get the most benefit from connection pooling, make sure you're not instantiating multiple client instances - for example by using <code>async with</code> inside a \"hot loop\". This can be achieved either by having a single scoped client that's passed throughout wherever it's needed, or by having a single global client instance.</p> <p>Alternatively, use <code>await client.aclose()</code> if you want to close a client explicitly:</p> <pre><code>client = httpx.AsyncClient()\n...\nawait client.aclose()\n</code></pre>"},{"location":"async/#streaming-responses","title":"Streaming responses","text":"<p>The <code>AsyncClient.stream(method, url, ...)</code> method is an async context block.</p> <pre><code>>>> client = httpx.AsyncClient()\n>>> async with client.stream('GET', 'https://www.example.com/') as response:\n... async for chunk in response.aiter_bytes():\n... ...\n</code></pre> <p>The async response streaming methods are:</p> <ul> <li><code>Response.aread()</code> - For conditionally reading a response inside a stream block.</li> <li><code>Response.aiter_bytes()</code> - For streaming the response content as bytes.</li> <li><code>Response.aiter_text()</code> - For streaming the response content as text.</li> <li><code>Response.aiter_lines()</code> - For streaming the response content as lines of text.</li> <li><code>Response.aiter_raw()</code> - For streaming the raw response bytes, without applying content decoding.</li> <li><code>Response.aclose()</code> - For closing the response. You don't usually need this, since <code>.stream</code> block closes the response automatically on exit.</li> </ul> <p>For situations when context block usage is not practical, it is possible to enter \"manual mode\" by sending a <code>Request</code> instance using <code>client.send(..., stream=True)</code>.</p> <p>Example in the context of forwarding the response to a streaming web endpoint with Starlette:</p> <pre><code>import httpx\nfrom starlette.background import BackgroundTask\nfrom starlette.responses import StreamingResponse\n\nclient = httpx.AsyncClient()\n\nasync def home(request):\n req = client.build_request(\"GET\", \"https://www.example.com/\")\n r = await client.send(req, stream=True)\n return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))\n</code></pre> <p>Warning</p> <p>When using this \"manual streaming mode\", it is your duty as a developer to make sure that <code>Response.aclose()</code> is called eventually. Failing to do so would leave connections open, most likely resulting in resource leaks down the line.</p>"},{"location":"async/#streaming-requests","title":"Streaming requests","text":"<p>When sending a streaming request body with an <code>AsyncClient</code> instance, you should use an async bytes generator instead of a bytes generator:</p> <pre><code>async def upload_bytes():\n ... # yield byte content\n\nawait client.post(url, content=upload_bytes())\n</code></pre>"},{"location":"async/#explicit-transport-instances","title":"Explicit transport instances","text":"<p>When instantiating a transport instance directly, you need to use <code>httpx.AsyncHTTPTransport</code>.</p> <p>For instance:</p> <pre><code>>>> import httpx\n>>> transport = httpx.AsyncHTTPTransport(retries=1)\n>>> async with httpx.AsyncClient(transport=transport) as client:\n>>> ...\n</code></pre>"},{"location":"async/#supported-async-environments","title":"Supported async environments","text":"<p>HTTPX supports either <code>asyncio</code> or <code>trio</code> as an async environment.</p> <p>It will auto-detect which of those two to use as the backend for socket operations and concurrency primitives.</p>"},{"location":"async/#asyncio","title":"AsyncIO","text":"<p>AsyncIO is Python's built-in library for writing concurrent code with the async/await syntax.</p> <pre><code>import asyncio\nimport httpx\n\nasync def main():\n async with httpx.AsyncClient() as client:\n response = await client.get('https://www.example.com/')\n print(response)\n\nasyncio.run(main())\n</code></pre>"},{"location":"async/#trio","title":"Trio","text":"<p>Trio is an alternative async library, designed around the the principles of structured concurrency.</p> <pre><code>import httpx\nimport trio\n\nasync def main():\n async with httpx.AsyncClient() as client:\n response = await client.get('https://www.example.com/')\n print(response)\n\ntrio.run(main)\n</code></pre> <p>Important</p> <p>The <code>trio</code> package must be installed to use the Trio backend.</p>"},{"location":"async/#anyio","title":"AnyIO","text":"<p>AnyIO is an asynchronous networking and concurrency library that works on top of either <code>asyncio</code> or <code>trio</code>. It blends in with native libraries of your chosen backend (defaults to <code>asyncio</code>).</p> <pre><code>import httpx\nimport anyio\n\nasync def main():\n async with httpx.AsyncClient() as client:\n response = await client.get('https://www.example.com/')\n print(response)\n\nanyio.run(main, backend='trio')\n</code></pre>"},{"location":"async/#calling-into-python-web-apps","title":"Calling into Python Web Apps","text":"<p>For details on calling directly into ASGI applications, see the <code>ASGITransport</code> docs.</p>"},{"location":"code_of_conduct/","title":"Code of Conduct","text":"<p>We expect contributors to our projects and online spaces to follow the Python Software Foundation\u2019s Code of Conduct.</p> <p>The Python community is made up of members from around the globe with a diverse set of skills, personalities, and experiences. It is through these differences that our community experiences great successes and continued growth. When you're working with members of the community, this Code of Conduct will help steer your interactions and keep Python a positive, successful, and growing community.</p>"},{"location":"code_of_conduct/#our-community","title":"Our Community","text":"<p>Members of the Python community are open, considerate, and respectful. Behaviours that reinforce these values contribute to a positive environment, and include:</p> <ul> <li>Being open. Members of the community are open to collaboration, whether it's on PEPs, patches, problems, or otherwise.</li> <li>Focusing on what is best for the community. We're respectful of the processes set forth in the community, and we work within them.</li> <li>Acknowledging time and effort. We're respectful of the volunteer efforts that permeate the Python community. We're thoughtful when addressing the efforts of others, keeping in mind that often times the labor was completed simply for the good of the community.</li> <li>Being respectful of differing viewpoints and experiences. We're receptive to constructive comments and criticism, as the experiences and skill sets of other members contribute to the whole of our efforts.</li> <li>Showing empathy towards other community members. We're attentive in our communications, whether in person or online, and we're tactful when approaching differing views.</li> <li>Being considerate. Members of the community are considerate of their peers -- other Python users.</li> <li>Being respectful. We're respectful of others, their positions, their skills, their commitments, and their efforts.</li> <li>Gracefully accepting constructive criticism. When we disagree, we are courteous in raising our issues.</li> <li>Using welcoming and inclusive language. We're accepting of all who wish to take part in our activities, fostering an environment where anyone can participate and everyone can make a difference.</li> </ul>"},{"location":"code_of_conduct/#our-standards","title":"Our Standards","text":"<p>Every member of our community has the right to have their identity respected. The Python community is dedicated to providing a positive experience for everyone, regardless of age, gender identity and expression, sexual orientation, disability, physical appearance, body size, ethnicity, nationality, race, or religion (or lack thereof), education, or socio-economic status.</p>"},{"location":"code_of_conduct/#inappropriate-behavior","title":"Inappropriate Behavior","text":"<p>Examples of unacceptable behavior by participants include:</p> <ul> <li>Harassment of any participants in any form</li> <li>Deliberate intimidation, stalking, or following</li> <li>Logging or taking screenshots of online activity for harassment purposes</li> <li>Publishing others' private information, such as a physical or electronic address, without explicit permission</li> <li>Violent threats or language directed against another person</li> <li>Incitement of violence or harassment towards any individual, including encouraging a person to commit suicide or to engage in self-harm</li> <li>Creating additional online accounts in order to harass another person or circumvent a ban</li> <li>Sexual language and imagery in online communities or in any conference venue, including talks</li> <li>Insults, put downs, or jokes that are based upon stereotypes, that are exclusionary, or that hold others up for ridicule</li> <li>Excessive swearing</li> <li>Unwelcome sexual attention or advances</li> <li>Unwelcome physical contact, including simulated physical contact (eg, textual descriptions like \"hug\" or \"backrub\") without consent or after a request to stop</li> <li>Pattern of inappropriate social contact, such as requesting/assuming inappropriate levels of intimacy with others</li> <li>Sustained disruption of online community discussions, in-person presentations, or other in-person events</li> <li>Continued one-on-one communication after requests to cease</li> <li>Other conduct that is inappropriate for a professional audience including people of many different backgrounds</li> </ul> <p>Community members asked to stop any inappropriate behavior are expected to comply immediately.</p>"},{"location":"code_of_conduct/#enforcement","title":"Enforcement","text":"<p>We take Code of Conduct violations seriously, and will act to ensure our spaces are welcoming, inclusive, and professional environments to communicate in.</p> <p>If you need to raise a Code of Conduct report, you may do so privately by email to tom@tomchristie.com.</p> <p>Reports will be treated confidentially.</p> <p>Alternately you may make a report to the Python Software Foundation.</p>"},{"location":"compatibility/","title":"Requests Compatibility Guide","text":"<p>HTTPX aims to be broadly compatible with the <code>requests</code> API, although there are a few design differences in places.</p> <p>This documentation outlines places where the API differs...</p>"},{"location":"compatibility/#redirects","title":"Redirects","text":"<p>Unlike <code>requests</code>, HTTPX does not follow redirects by default.</p> <p>We differ in behaviour here because auto-redirects can easily mask unnecessary network calls being made.</p> <p>You can still enable behaviour to automatically follow redirects, but you need to do so explicitly...</p> <pre><code>response = client.get(url, follow_redirects=True)\n</code></pre> <p>Or else instantiate a client, with redirect following enabled by default...</p> <pre><code>client = httpx.Client(follow_redirects=True)\n</code></pre>"},{"location":"compatibility/#client-instances","title":"Client instances","text":"<p>The HTTPX equivalent of <code>requests.Session</code> is <code>httpx.Client</code>.</p> <pre><code>session = requests.Session(**kwargs)\n</code></pre> <p>is generally equivalent to</p> <pre><code>client = httpx.Client(**kwargs)\n</code></pre>"},{"location":"compatibility/#request-urls","title":"Request URLs","text":"<p>Accessing <code>response.url</code> will return a <code>URL</code> instance, rather than a string.</p> <p>Use <code>str(response.url)</code> if you need a string instance.</p>"},{"location":"compatibility/#determining-the-next-redirect-request","title":"Determining the next redirect request","text":"<p>The <code>requests</code> library exposes an attribute <code>response.next</code>, which can be used to obtain the next redirect request.</p> <pre><code>session = requests.Session()\nrequest = requests.Request(\"GET\", ...).prepare()\nwhile request is not None:\n response = session.send(request, allow_redirects=False)\n request = response.next\n</code></pre> <p>In HTTPX, this attribute is instead named <code>response.next_request</code>. For example:</p> <pre><code>client = httpx.Client()\nrequest = client.build_request(\"GET\", ...)\nwhile request is not None:\n response = client.send(request)\n request = response.next_request\n</code></pre>"},{"location":"compatibility/#request-content","title":"Request Content","text":"<p>For uploading raw text or binary content we prefer to use a <code>content</code> parameter, in order to better separate this usage from the case of uploading form data.</p> <p>For example, using <code>content=...</code> to upload raw content:</p> <pre><code># Uploading text, bytes, or a bytes iterator.\nhttpx.post(..., content=b\"Hello, world\")\n</code></pre> <p>And using <code>data=...</code> to send form data:</p> <pre><code># Uploading form data.\nhttpx.post(..., data={\"message\": \"Hello, world\"})\n</code></pre> <p>Using the <code>data=<text/byte content></code> will raise a deprecation warning, and is expected to be fully removed with the HTTPX 1.0 release.</p>"},{"location":"compatibility/#upload-files","title":"Upload files","text":"<p>HTTPX strictly enforces that upload files must be opened in binary mode, in order to avoid character encoding issues that can result from attempting to upload files opened in text mode.</p>"},{"location":"compatibility/#content-encoding","title":"Content encoding","text":"<p>HTTPX uses <code>utf-8</code> for encoding <code>str</code> request bodies. For example, when using <code>content=<str></code> the request body will be encoded to <code>utf-8</code> before being sent over the wire. This differs from Requests which uses <code>latin1</code>. If you need an explicit encoding, pass encoded bytes explicitly, e.g. <code>content=<str>.encode(\"latin1\")</code>. For response bodies, assuming the server didn't send an explicit encoding then HTTPX will do its best to figure out an appropriate encoding. HTTPX makes a guess at the encoding to use for decoding the response using <code>charset_normalizer</code>. Fallback to that or any content with less than 32 octets will be decoded using <code>utf-8</code> with the <code>error=\"replace\"</code> decoder strategy.</p>"},{"location":"compatibility/#cookies","title":"Cookies","text":"<p>If using a client instance, then cookies should always be set on the client rather than on a per-request basis.</p> <p>This usage is supported:</p> <pre><code>client = httpx.Client(cookies=...)\nclient.post(...)\n</code></pre> <p>This usage is not supported:</p> <pre><code>client = httpx.Client()\nclient.post(..., cookies=...)\n</code></pre> <p>We prefer enforcing a stricter API here because it provides clearer expectations around cookie persistence, particularly when redirects occur.</p>"},{"location":"compatibility/#status-codes","title":"Status Codes","text":"<p>In our documentation we prefer the uppercased versions, such as <code>codes.NOT_FOUND</code>, but also provide lower-cased versions for API compatibility with <code>requests</code>.</p> <p>Requests includes various synonyms for status codes that HTTPX does not support.</p>"},{"location":"compatibility/#streaming-responses","title":"Streaming responses","text":"<p>HTTPX provides a <code>.stream()</code> interface rather than using <code>stream=True</code>. This ensures that streaming responses are always properly closed outside of the stream block, and makes it visually clearer at which points streaming I/O APIs may be used with a response.</p> <p>For example:</p> <pre><code>with httpx.stream(\"GET\", \"https://www.example.com\") as response:\n ...\n</code></pre> <p>Within a <code>stream()</code> block request data is made available with:</p> <ul> <li><code>.iter_bytes()</code> - Instead of <code>response.iter_content()</code></li> <li><code>.iter_text()</code> - Instead of <code>response.iter_content(decode_unicode=True)</code></li> <li><code>.iter_lines()</code> - Corresponding to <code>response.iter_lines()</code></li> <li><code>.iter_raw()</code> - Use this instead of <code>response.raw</code></li> <li><code>.read()</code> - Read the entire response body, making <code>response.text</code> and <code>response.content</code> available.</li> </ul>"},{"location":"compatibility/#timeouts","title":"Timeouts","text":"<p>HTTPX defaults to including reasonable timeouts for all network operations, while Requests has no timeouts by default.</p> <p>To get the same behavior as Requests, set the <code>timeout</code> parameter to <code>None</code>:</p> <pre><code>httpx.get('https://www.example.com', timeout=None)\n</code></pre>"},{"location":"compatibility/#proxy-keys","title":"Proxy keys","text":"<p>HTTPX uses the mounts argument for HTTP proxying and transport routing. It can do much more than proxies and allows you to configure more than just the proxy route. For more detailed documentation, see Mounting Transports.</p> <p>When using <code>httpx.Client(mounts={...})</code> to map to a selection of different transports, we use full URL schemes, such as <code>mounts={\"http://\": ..., \"https://\": ...}</code>.</p> <p>This is different to the <code>requests</code> usage of <code>proxies={\"http\": ..., \"https\": ...}</code>.</p> <p>This change is for better consistency with more complex mappings, that might also include domain names, such as <code>mounts={\"all://\": ..., httpx.HTTPTransport(proxy=\"all://www.example.com\": None})</code> which maps all requests onto a proxy, except for requests to \"www.example.com\" which have an explicit exclusion.</p> <p>Also note that <code>requests.Session.request(...)</code> allows a <code>proxies=...</code> parameter, whereas <code>httpx.Client.request(...)</code> does not allow <code>mounts=...</code>.</p>"},{"location":"compatibility/#ssl-configuration","title":"SSL configuration","text":"<p>When using a <code>Client</code> instance, the ssl configurations should always be passed on client instantiation, rather than passed to the request method.</p> <p>If you need more than one different SSL configuration, you should use different client instances for each SSL configuration.</p>"},{"location":"compatibility/#request-body-on-http-methods","title":"Request body on HTTP methods","text":"<p>The HTTP <code>GET</code>, <code>DELETE</code>, <code>HEAD</code>, and <code>OPTIONS</code> methods are specified as not supporting a request body. To stay in line with this, the <code>.get</code>, <code>.delete</code>, <code>.head</code> and <code>.options</code> functions do not support <code>content</code>, <code>files</code>, <code>data</code>, or <code>json</code> arguments.</p> <p>If you really do need to send request data using these http methods you should use the generic <code>.request</code> function instead.</p> <pre><code>httpx.request(\n method=\"DELETE\",\n url=\"https://www.example.com/\",\n content=b'A request body on a DELETE request.'\n)\n</code></pre>"},{"location":"compatibility/#checking-for-success-and-failure-responses","title":"Checking for success and failure responses","text":"<p>We don't support <code>response.is_ok</code> since the naming is ambiguous there, and might incorrectly imply an equivalence to <code>response.status_code == codes.OK</code>. Instead we provide the <code>response.is_success</code> property, which can be used to check for a 2xx response.</p>"},{"location":"compatibility/#request-instantiation","title":"Request instantiation","text":"<p>There is no notion of prepared requests in HTTPX. If you need to customize request instantiation, see Request instances.</p> <p>Besides, <code>httpx.Request()</code> does not support the <code>auth</code>, <code>timeout</code>, <code>follow_redirects</code>, <code>mounts</code>, <code>verify</code> and <code>cert</code> parameters. However these are available in <code>httpx.request</code>, <code>httpx.get</code>, <code>httpx.post</code> etc., as well as on <code>Client</code> instances.</p>"},{"location":"compatibility/#mocking","title":"Mocking","text":"<p>If you need to mock HTTPX the same way that test utilities like <code>responses</code> and <code>requests-mock</code> does for <code>requests</code>, see RESPX.</p>"},{"location":"compatibility/#caching","title":"Caching","text":"<p>If you use <code>cachecontrol</code> or <code>requests-cache</code> to add HTTP Caching support to the <code>requests</code> library, you can use Hishel for HTTPX.</p>"},{"location":"compatibility/#networking-layer","title":"Networking layer","text":"<p><code>requests</code> defers most of its HTTP networking code to the excellent <code>urllib3</code> library.</p> <p>On the other hand, HTTPX uses HTTPCore as its core HTTP networking layer, which is a different project than <code>urllib3</code>.</p>"},{"location":"compatibility/#query-parameters","title":"Query Parameters","text":"<p><code>requests</code> omits <code>params</code> whose values are <code>None</code> (e.g. <code>requests.get(..., params={\"foo\": None})</code>). This is not supported by HTTPX.</p> <p>For both query params (<code>params=</code>) and form data (<code>data=</code>), <code>requests</code> supports sending a list of tuples (e.g. <code>requests.get(..., params=[('key1', 'value1'), ('key1', 'value2')])</code>). This is not supported by HTTPX. Instead, use a dictionary with lists as values. E.g.: <code>httpx.get(..., params={'key1': ['value1', 'value2']})</code> or with form data: <code>httpx.post(..., data={'key1': ['value1', 'value2']})</code>.</p>"},{"location":"compatibility/#event-hooks","title":"Event Hooks","text":"<p><code>requests</code> allows event hooks to mutate <code>Request</code> and <code>Response</code> objects. See examples given in the documentation for <code>requests</code>.</p> <p>In HTTPX, event hooks may access properties of requests and responses, but event hook callbacks cannot mutate the original request/response.</p> <p>If you are looking for more control, consider checking out Custom Transports.</p>"},{"location":"compatibility/#exceptions-and-errors","title":"Exceptions and Errors","text":"<p><code>requests</code> exception hierarchy is slightly different to the <code>httpx</code> exception hierarchy. <code>requests</code> exposes a top level <code>RequestException</code>, where as <code>httpx</code> exposes a top level <code>HTTPError</code>. see the exceptions exposes in requests here. See the <code>httpx</code> error hierarchy here.</p>"},{"location":"contributing/","title":"Contributing","text":"<p>Thank you for being interested in contributing to HTTPX. There are many ways you can contribute to the project:</p> <ul> <li>Try HTTPX and report bugs/issues you find</li> <li>Implement new features</li> <li>Review Pull Requests of others</li> <li>Write documentation</li> <li>Participate in discussions</li> </ul>"},{"location":"contributing/#reporting-bugs-or-other-issues","title":"Reporting Bugs or Other Issues","text":"<p>Found something that HTTPX should support? Stumbled upon some unexpected behaviour?</p> <p>Contributions should generally start out with a discussion. Possible bugs may be raised as a \"Potential Issue\" discussion, feature requests may be raised as an \"Ideas\" discussion. We can then determine if the discussion needs to be escalated into an \"Issue\" or not, or if we'd consider a pull request.</p> <p>Try to be more descriptive as you can and in case of a bug report, provide as much information as possible like:</p> <ul> <li>OS platform</li> <li>Python version</li> <li>Installed dependencies and versions (<code>python -m pip freeze</code>)</li> <li>Code snippet</li> <li>Error traceback</li> </ul> <p>You should always try to reduce any examples to the simplest possible case that demonstrates the issue.</p> <p>Some possibly useful tips for narrowing down potential issues...</p> <ul> <li>Does the issue exist on HTTP/1.1, or HTTP/2, or both?</li> <li>Does the issue exist with <code>Client</code>, <code>AsyncClient</code>, or both?</li> <li>When using <code>AsyncClient</code> does the issue exist when using <code>asyncio</code> or <code>trio</code>, or both?</li> </ul>"},{"location":"contributing/#development","title":"Development","text":"<p>To start developing HTTPX create a fork of the HTTPX repository on GitHub.</p> <p>Then clone your fork with the following command replacing <code>YOUR-USERNAME</code> with your GitHub username:</p> <pre><code>$ git clone https://github.com/YOUR-USERNAME/httpx\n</code></pre> <p>You can now install the project and its dependencies using:</p> <pre><code>$ cd httpx\n$ scripts/install\n</code></pre>"},{"location":"contributing/#testing-and-linting","title":"Testing and Linting","text":"<p>We use custom shell scripts to automate testing, linting, and documentation building workflow.</p> <p>To run the tests, use:</p> <pre><code>$ scripts/test\n</code></pre> <p>Warning</p> <p>The test suite spawns testing servers on ports 8000 and 8001. Make sure these are not in use, so the tests can run properly.</p> <p>Any additional arguments will be passed to <code>pytest</code>. See the pytest documentation for more information.</p> <p>For example, to run a single test script:</p> <pre><code>$ scripts/test tests/test_multipart.py\n</code></pre> <p>To run the code auto-formatting:</p> <pre><code>$ scripts/lint\n</code></pre> <p>Lastly, to run code checks separately (they are also run as part of <code>scripts/test</code>), run:</p> <pre><code>$ scripts/check\n</code></pre>"},{"location":"contributing/#documenting","title":"Documenting","text":"<p>Documentation pages are located under the <code>docs/</code> folder.</p> <p>To run the documentation site locally (useful for previewing changes), use:</p> <pre><code>$ scripts/docs\n</code></pre>"},{"location":"contributing/#resolving-build-ci-failures","title":"Resolving Build / CI Failures","text":"<p>Once you've submitted your pull request, the test suite will automatically run, and the results will show up in GitHub. If the test suite fails, you'll want to click through to the \"Details\" link, and try to identify why the test suite failed.</p> <p> </p> <p>Here are some common ways the test suite can fail:</p>"},{"location":"contributing/#check-job-failed","title":"Check Job Failed","text":"<p>This job failing means there is either a code formatting issue or type-annotation issue. You can look at the job output to figure out why it's failed or within a shell run:</p> <pre><code>$ scripts/check\n</code></pre> <p>It may be worth it to run <code>$ scripts/lint</code> to attempt auto-formatting the code and if that job succeeds commit the changes.</p>"},{"location":"contributing/#docs-job-failed","title":"Docs Job Failed","text":"<p>This job failing means the documentation failed to build. This can happen for a variety of reasons like invalid markdown or missing configuration within <code>mkdocs.yml</code>.</p>"},{"location":"contributing/#python-3x-job-failed","title":"Python 3.X Job Failed","text":"<p>This job failing means the unit tests failed or not all code paths are covered by unit tests.</p> <p>If tests are failing you will see this message under the coverage report:</p> <p><code>=== 1 failed, 435 passed, 1 skipped, 1 xfailed in 11.09s ===</code></p> <p>If tests succeed but coverage doesn't reach our current threshold, you will see this message under the coverage report:</p> <p><code>FAIL Required test coverage of 100% not reached. Total coverage: 99.00%</code></p>"},{"location":"contributing/#releasing","title":"Releasing","text":"<p>This section is targeted at HTTPX maintainers.</p> <p>Before releasing a new version, create a pull request that includes:</p> <ul> <li>An update to the changelog:<ul> <li>We follow the format from keepachangelog.</li> <li>Compare <code>master</code> with the tag of the latest release, and list all entries that are of interest to our users:<ul> <li>Things that must go in the changelog: added, changed, deprecated or removed features, and bug fixes.</li> <li>Things that should not go in the changelog: changes to documentation, tests or tooling.</li> <li>Try sorting entries in descending order of impact / importance.</li> <li>Keep it concise and to-the-point. \ud83c\udfaf</li> </ul> </li> </ul> </li> <li>A version bump: see <code>__version__.py</code>.</li> </ul> <p>For an example, see #1006.</p> <p>Once the release PR is merged, create a new release including:</p> <ul> <li>Tag version like <code>0.13.3</code>.</li> <li>Release title <code>Version 0.13.3</code></li> <li>Description copied from the changelog.</li> </ul> <p>Once created this release will be automatically uploaded to PyPI.</p> <p>If something goes wrong with the PyPI job the release can be published using the <code>scripts/publish</code> script.</p>"},{"location":"contributing/#development-proxy-setup","title":"Development proxy setup","text":"<p>To test and debug requests via a proxy it's best to run a proxy server locally. Any server should do but HTTPCore's test suite uses <code>mitmproxy</code> which is written in Python, it's fully featured and has excellent UI and tools for introspection of requests.</p> <p>You can install <code>mitmproxy</code> using <code>pip install mitmproxy</code> or several other ways.</p> <p><code>mitmproxy</code> does require setting up local TLS certificates for HTTPS requests, as its main purpose is to allow developers to inspect requests that pass through it. We can set them up follows:</p> <ol> <li><code>pip install trustme-cli</code>.</li> <li><code>trustme-cli -i example.org www.example.org</code>, assuming you want to test connecting to that domain, this will create three files: <code>server.pem</code>, <code>server.key</code> and <code>client.pem</code>.</li> <li><code>mitmproxy</code> requires a PEM file that includes the private key and the certificate so we need to concatenate them: <code>cat server.key server.pem > server.withkey.pem</code>.</li> <li>Start the proxy server <code>mitmproxy --certs server.withkey.pem</code>, or use the other mitmproxy commands with different UI options.</li> </ol> <p>At this point the server is ready to start serving requests, you'll need to configure HTTPX as described in the proxy section and the SSL certificates section, this is where our previously generated <code>client.pem</code> comes in:</p> <pre><code>ctx = ssl.create_default_context(cafile=\"/path/to/client.pem\")\nclient = httpx.Client(proxy=\"http://127.0.0.1:8080/\", verify=ctx)\n</code></pre> <p>Note, however, that HTTPS requests will only succeed to the host specified in the SSL/TLS certificate we generated, HTTPS requests to other hosts will raise an error like:</p> <pre><code>ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate\nverify failed: Hostname mismatch, certificate is not valid for\n'duckduckgo.com'. (_ssl.c:1108)\n</code></pre> <p>If you want to make requests to more hosts you'll need to regenerate the certificates and include all the hosts you intend to connect to in the seconds step, i.e.</p> <p><code>trustme-cli -i example.org www.example.org duckduckgo.com www.duckduckgo.com</code></p>"},{"location":"environment_variables/","title":"Environment Variables","text":"<p>The HTTPX library can be configured via environment variables. Environment variables are used by default. To ignore environment variables, <code>trust_env</code> has to be set <code>False</code>. There are two ways to set <code>trust_env</code> to disable environment variables:</p> <ul> <li>On the client via <code>httpx.Client(trust_env=False)</code>.</li> <li>Using the top-level API, such as <code>httpx.get(\"<url>\", trust_env=False)</code>.</li> </ul> <p>Here is a list of environment variables that HTTPX recognizes and what function they serve:</p>"},{"location":"environment_variables/#proxies","title":"Proxies","text":"<p>The environment variables documented below are used as a convention by various HTTP tooling, including:</p> <ul> <li>cURL</li> <li>requests</li> </ul> <p>For more information on using proxies in HTTPX, see HTTP Proxying.</p>"},{"location":"environment_variables/#http_proxy-https_proxy-all_proxy","title":"<code>HTTP_PROXY</code>, <code>HTTPS_PROXY</code>, <code>ALL_PROXY</code>","text":"<p>Valid values: A URL to a proxy</p> <p><code>HTTP_PROXY</code>, <code>HTTPS_PROXY</code>, <code>ALL_PROXY</code> set the proxy to be used for <code>http</code>, <code>https</code>, or all requests respectively.</p> <pre><code>export HTTP_PROXY=http://my-external-proxy.com:1234\n\n# This request will be sent through the proxy\npython -c \"import httpx; httpx.get('http://example.com')\"\n\n# This request will be sent directly, as we set `trust_env=False`\npython -c \"import httpx; httpx.get('http://example.com', trust_env=False)\"\n</code></pre>"},{"location":"environment_variables/#no_proxy","title":"<code>NO_PROXY</code>","text":"<p>Valid values: a comma-separated list of hostnames/urls</p> <p><code>NO_PROXY</code> disables the proxy for specific urls</p> <pre><code>export HTTP_PROXY=http://my-external-proxy.com:1234\nexport NO_PROXY=http://127.0.0.1,python-httpx.org\n\n# As in the previous example, this request will be sent through the proxy\npython -c \"import httpx; httpx.get('http://example.com')\"\n\n# These requests will be sent directly, bypassing the proxy\npython -c \"import httpx; httpx.get('http://127.0.0.1:5000/my-api')\"\npython -c \"import httpx; httpx.get('https://www.python-httpx.org')\"\n</code></pre>"},{"location":"environment_variables/#ssl_cert_file","title":"<code>SSL_CERT_FILE</code>","text":"<p>Valid values: a filename</p> <p>If this environment variable is set then HTTPX will load CA certificate from the specified file instead of the default location.</p> <p>Example:</p> <pre><code>SSL_CERT_FILE=/path/to/ca-certs/ca-bundle.crt python -c \"import httpx; httpx.get('https://example.com')\"\n</code></pre>"},{"location":"environment_variables/#ssl_cert_dir","title":"<code>SSL_CERT_DIR</code>","text":"<p>Valid values: a directory following an OpenSSL specific layout.</p> <p>If this environment variable is set and the directory follows an OpenSSL specific layout (ie. you ran <code>c_rehash</code>) then HTTPX will load CA certificates from this directory instead of the default location.</p> <p>Example:</p> <pre><code>SSL_CERT_DIR=/path/to/ca-certs/ python -c \"import httpx; httpx.get('https://example.com')\"\n</code></pre>"},{"location":"exceptions/","title":"Exceptions","text":"<p>This page lists exceptions that may be raised when using HTTPX.</p> <p>For an overview of how to work with HTTPX exceptions, see Exceptions (Quickstart).</p>"},{"location":"exceptions/#the-exception-hierarchy","title":"The exception hierarchy","text":"<ul> <li>HTTPError<ul> <li>RequestError<ul> <li>TransportError<ul> <li>TimeoutException<ul> <li>ConnectTimeout</li> <li>ReadTimeout</li> <li>WriteTimeout</li> <li>PoolTimeout</li> </ul> </li> <li>NetworkError<ul> <li>ConnectError</li> <li>ReadError</li> <li>WriteError</li> <li>CloseError</li> </ul> </li> <li>ProtocolError<ul> <li>LocalProtocolError</li> <li>RemoteProtocolError</li> </ul> </li> <li>ProxyError</li> <li>UnsupportedProtocol</li> </ul> </li> <li>DecodingError</li> <li>TooManyRedirects</li> </ul> </li> <li>HTTPStatusError</li> </ul> </li> <li>InvalidURL</li> <li>CookieConflict</li> <li>StreamError<ul> <li>StreamConsumed</li> <li>ResponseNotRead</li> <li>RequestNotRead</li> <li>StreamClosed</li> </ul> </li> </ul>"},{"location":"exceptions/#exception-classes","title":"Exception classes","text":"class <code>httpx.HTTPError</code>(message) <p>Base class for <code>RequestError</code> and <code>HTTPStatusError</code>.</p> <p>Useful for <code>try...except</code> blocks when issuing a request, and then calling <code>.raise_for_status()</code>.</p> <p>For example:</p> <pre><code>try:\n response = httpx.get(\"https://www.example.com\")\n response.raise_for_status()\nexcept httpx.HTTPError as exc:\n print(f\"HTTP Exception for {exc.request.url} - {exc}\")\n</code></pre> class <code>httpx.RequestError</code>(message, *, request=None) <p>Base class for all exceptions that may occur when issuing a <code>.request()</code>.</p> class <code>httpx.TransportError</code>(message, *, request=None) <p>Base class for all exceptions that occur at the level of the Transport API.</p> class <code>httpx.TimeoutException</code>(message, *, request=None) <p>The base class for timeout errors.</p> <p>An operation has timed out.</p> class <code>httpx.ConnectTimeout</code>(message, *, request=None) <p>Timed out while connecting to the host.</p> class <code>httpx.ReadTimeout</code>(message, *, request=None) <p>Timed out while receiving data from the host.</p> class <code>httpx.WriteTimeout</code>(message, *, request=None) <p>Timed out while sending data to the host.</p> class <code>httpx.PoolTimeout</code>(message, *, request=None) <p>Timed out waiting to acquire a connection from the pool.</p> class <code>httpx.NetworkError</code>(message, *, request=None) <p>The base class for network-related errors.</p> <p>An error occurred while interacting with the network.</p> class <code>httpx.ConnectError</code>(message, *, request=None) <p>Failed to establish a connection.</p> class <code>httpx.ReadError</code>(message, *, request=None) <p>Failed to receive data from the network.</p> class <code>httpx.WriteError</code>(message, *, request=None) <p>Failed to send data through the network.</p> class <code>httpx.CloseError</code>(message, *, request=None) <p>Failed to close a connection.</p> class <code>httpx.ProtocolError</code>(message, *, request=None) <p>The protocol was violated.</p> class <code>httpx.LocalProtocolError</code>(message, *, request=None) <p>A protocol was violated by the client.</p> <p>For example if the user instantiated a <code>Request</code> instance explicitly, failed to include the mandatory <code>Host:</code> header, and then issued it directly using <code>client.send()</code>.</p> class <code>httpx.RemoteProtocolError</code>(message, *, request=None) <p>The protocol was violated by the server.</p> <p>For example, returning malformed HTTP.</p> class <code>httpx.ProxyError</code>(message, *, request=None) <p>An error occurred while establishing a proxy connection.</p> class <code>httpx.UnsupportedProtocol</code>(message, *, request=None) <p>Attempted to make a request to an unsupported protocol.</p> <p>For example issuing a request to <code>ftp://www.example.com</code>.</p> class <code>httpx.DecodingError</code>(message, *, request=None) <p>Decoding of the response failed, due to a malformed encoding.</p> class <code>httpx.TooManyRedirects</code>(message, *, request=None) <p>Too many redirects.</p> class <code>httpx.HTTPStatusError</code>(message, *, request, response) <p>The response had an error HTTP status of 4xx or 5xx.</p> <p>May be raised when calling <code>response.raise_for_status()</code></p> class <code>httpx.InvalidURL</code>(message) <p>URL is improperly formed or cannot be parsed.</p> class <code>httpx.CookieConflict</code>(message) <p>Attempted to lookup a cookie by name, but multiple cookies existed.</p> <p>Can occur when calling <code>response.cookies.get(...)</code>.</p> class <code>httpx.StreamError</code>(message) <p>The base class for stream exceptions.</p> <p>The developer made an error in accessing the request stream in an invalid way.</p> class <code>httpx.StreamConsumed</code>() <p>Attempted to read or stream content, but the content has already been streamed.</p> class <code>httpx.StreamClosed</code>() <p>Attempted to read or stream response content, but the request has been closed.</p> class <code>httpx.ResponseNotRead</code>() <p>Attempted to access streaming response content, without having called <code>read()</code>.</p> class <code>httpx.RequestNotRead</code>() <p>Attempted to access streaming request content, without having called <code>read()</code>.</p>"},{"location":"http2/","title":"HTTP/2","text":"<p>HTTP/2 is a major new iteration of the HTTP protocol, that provides a far more efficient transport, with potential performance benefits. HTTP/2 does not change the core semantics of the request or response, but alters the way that data is sent to and from the server.</p> <p>Rather than the text format that HTTP/1.1 uses, HTTP/2 is a binary format. The binary format provides full request and response multiplexing, and efficient compression of HTTP headers. The stream multiplexing means that where HTTP/1.1 requires one TCP stream for each concurrent request, HTTP/2 allows a single TCP stream to handle multiple concurrent requests.</p> <p>HTTP/2 also provides support for functionality such as response prioritization, and server push.</p> <p>For a comprehensive guide to HTTP/2 you may want to check out \"http2 explained\".</p>"},{"location":"http2/#enabling-http2","title":"Enabling HTTP/2","text":"<p>When using the <code>httpx</code> client, HTTP/2 support is not enabled by default, because HTTP/1.1 is a mature, battle-hardened transport layer, and our HTTP/1.1 implementation may be considered the more robust option at this point in time. It is possible that a future version of <code>httpx</code> may enable HTTP/2 support by default.</p> <p>If you're issuing highly concurrent requests you might want to consider trying out our HTTP/2 support. You can do so by first making sure to install the optional HTTP/2 dependencies...</p> <pre><code>$ pip install httpx[http2]\n</code></pre> <p>And then instantiating a client with HTTP/2 support enabled:</p> <pre><code>client = httpx.AsyncClient(http2=True)\n...\n</code></pre> <p>You can also instantiate a client as a context manager, to ensure that all HTTP connections are nicely scoped, and will be closed once the context block is exited.</p> <pre><code>async with httpx.AsyncClient(http2=True) as client:\n ...\n</code></pre> <p>HTTP/2 support is available on both <code>Client</code> and <code>AsyncClient</code>, although it's typically more useful in async contexts if you're issuing lots of concurrent requests.</p>"},{"location":"http2/#inspecting-the-http-version","title":"Inspecting the HTTP version","text":"<p>Enabling HTTP/2 support on the client does not necessarily mean that your requests and responses will be transported over HTTP/2, since both the client and the server need to support HTTP/2. If you connect to a server that only supports HTTP/1.1 the client will use a standard HTTP/1.1 connection instead.</p> <p>You can determine which version of the HTTP protocol was used by examining the <code>.http_version</code> property on the response.</p> <pre><code>client = httpx.AsyncClient(http2=True)\nresponse = await client.get(...)\nprint(response.http_version) # \"HTTP/1.0\", \"HTTP/1.1\", or \"HTTP/2\".\n</code></pre>"},{"location":"logging/","title":"Logging","text":"<p>If you need to inspect the internal behaviour of <code>httpx</code>, you can use Python's standard logging to output information about the underlying network behaviour.</p> <p>For example, the following configuration...</p> <pre><code>import logging\nimport httpx\n\nlogging.basicConfig(\n format=\"%(levelname)s [%(asctime)s] %(name)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n level=logging.DEBUG\n)\n\nhttpx.get(\"https://www.example.com\")\n</code></pre> <p>Will send debug level output to the console, or wherever <code>stdout</code> is directed too...</p> <pre><code>DEBUG [2024-09-28 17:27:40] httpcore.connection - connect_tcp.started host='www.example.com' port=443 local_address=None timeout=5.0 socket_options=None\nDEBUG [2024-09-28 17:27:41] httpcore.connection - connect_tcp.complete return_value=<httpcore._backends.sync.SyncStream object at 0x101f1e8e0>\nDEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.started ssl_context=SSLContext(verify=True) server_hostname='www.example.com' timeout=5.0\nDEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.complete return_value=<httpcore._backends.sync.SyncStream object at 0x1020f49a0>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.started request=<Request [b'GET']>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.complete\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.started request=<Request [b'GET']>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.complete\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_headers.started request=<Request [b'GET']>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Content-Encoding', b'gzip'), (b'Accept-Ranges', b'bytes'), (b'Age', b'407727'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Sat, 28 Sep 2024 13:27:42 GMT'), (b'Etag', b'\"3147526947+gzip\"'), (b'Expires', b'Sat, 05 Oct 2024 13:27:42 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECAcc (dcd/7D43)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'648')])\nINFO [2024-09-28 17:27:41] httpx - HTTP Request: GET https://www.example.com \"HTTP/1.1 200 OK\"\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.started request=<Request [b'GET']>\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.complete\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.started\nDEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.complete\nDEBUG [2024-09-28 17:27:41] httpcore.connection - close.started\nDEBUG [2024-09-28 17:27:41] httpcore.connection - close.complete\n</code></pre> <p>Logging output includes information from both the high-level <code>httpx</code> logger, and the network-level <code>httpcore</code> logger, which can be configured separately.</p> <p>For handling more complex logging configurations you might want to use the dictionary configuration style...</p> <pre><code>import logging.config\nimport httpx\n\nLOGGING_CONFIG = {\n \"version\": 1,\n \"handlers\": {\n \"default\": {\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"http\",\n \"stream\": \"ext://sys.stderr\"\n }\n },\n \"formatters\": {\n \"http\": {\n \"format\": \"%(levelname)s [%(asctime)s] %(name)s - %(message)s\",\n \"datefmt\": \"%Y-%m-%d %H:%M:%S\",\n }\n },\n 'loggers': {\n 'httpx': {\n 'handlers': ['default'],\n 'level': 'DEBUG',\n },\n 'httpcore': {\n 'handlers': ['default'],\n 'level': 'DEBUG',\n },\n }\n}\n\nlogging.config.dictConfig(LOGGING_CONFIG)\nhttpx.get('https://www.example.com')\n</code></pre> <p>The exact formatting of the debug logging may be subject to change across different versions of <code>httpx</code> and <code>httpcore</code>. If you need to rely on a particular format it is recommended that you pin installation of these packages to fixed versions.</p>"},{"location":"quickstart/","title":"QuickStart","text":"<p>First, start by importing HTTPX:</p> <pre><code>>>> import httpx\n</code></pre> <p>Now, let\u2019s try to get a webpage.</p> <pre><code>>>> r = httpx.get('https://httpbin.org/get')\n>>> r\n<Response [200 OK]>\n</code></pre> <p>Similarly, to make an HTTP POST request:</p> <pre><code>>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})\n</code></pre> <p>The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:</p> <pre><code>>>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})\n>>> r = httpx.delete('https://httpbin.org/delete')\n>>> r = httpx.head('https://httpbin.org/get')\n>>> r = httpx.options('https://httpbin.org/get')\n</code></pre>"},{"location":"quickstart/#passing-parameters-in-urls","title":"Passing Parameters in URLs","text":"<p>To include URL query parameters in the request, use the <code>params</code> keyword:</p> <pre><code>>>> params = {'key1': 'value1', 'key2': 'value2'}\n>>> r = httpx.get('https://httpbin.org/get', params=params)\n</code></pre> <p>To see how the values get encoding into the URL string, we can inspect the resulting URL that was used to make the request:</p> <pre><code>>>> r.url\nURL('https://httpbin.org/get?key2=value2&key1=value1')\n</code></pre> <p>You can also pass a list of items as a value:</p> <pre><code>>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}\n>>> r = httpx.get('https://httpbin.org/get', params=params)\n>>> r.url\nURL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')\n</code></pre>"},{"location":"quickstart/#response-content","title":"Response Content","text":"<p>HTTPX will automatically handle decoding the response content into Unicode text.</p> <pre><code>>>> r = httpx.get('https://www.example.org/')\n>>> r.text\n'<!doctype html>\\n<html>\\n<head>\\n<title>Example Domain</title>...'\n</code></pre> <p>You can inspect what encoding will be used to decode the response.</p> <pre><code>>>> r.encoding\n'UTF-8'\n</code></pre> <p>In some cases the response may not contain an explicit encoding, in which case HTTPX will attempt to automatically determine an encoding to use.</p> <pre><code>>>> r.encoding\nNone\n>>> r.text\n'<!doctype html>\\n<html>\\n<head>\\n<title>Example Domain</title>...'\n</code></pre> <p>If you need to override the standard behaviour and explicitly set the encoding to use, then you can do that too.</p> <pre><code>>>> r.encoding = 'ISO-8859-1'\n</code></pre>"},{"location":"quickstart/#binary-response-content","title":"Binary Response Content","text":"<p>The response content can also be accessed as bytes, for non-text responses:</p> <pre><code>>>> r.content\nb'<!doctype html>\\n<html>\\n<head>\\n<title>Example Domain</title>...'\n</code></pre> <p>Any <code>gzip</code> and <code>deflate</code> HTTP response encodings will automatically be decoded for you. If <code>brotlipy</code> is installed, then the <code>brotli</code> response encoding will be supported. If <code>zstandard</code> is installed, then <code>zstd</code> response encodings will also be supported.</p> <p>For example, to create an image from binary data returned by a request, you can use the following code:</p> <pre><code>>>> from PIL import Image\n>>> from io import BytesIO\n>>> i = Image.open(BytesIO(r.content))\n</code></pre>"},{"location":"quickstart/#json-response-content","title":"JSON Response Content","text":"<p>Often Web API responses will be encoded as JSON.</p> <pre><code>>>> r = httpx.get('https://api.github.com/events')\n>>> r.json()\n[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]\n</code></pre>"},{"location":"quickstart/#custom-headers","title":"Custom Headers","text":"<p>To include additional headers in the outgoing request, use the <code>headers</code> keyword argument:</p> <pre><code>>>> url = 'https://httpbin.org/headers'\n>>> headers = {'user-agent': 'my-app/0.0.1'}\n>>> r = httpx.get(url, headers=headers)\n</code></pre>"},{"location":"quickstart/#sending-form-encoded-data","title":"Sending Form Encoded Data","text":"<p>Some types of HTTP requests, such as <code>POST</code> and <code>PUT</code> requests, can include data in the request body. One common way of including that is as form-encoded data, which is used for HTML forms.</p> <pre><code>>>> data = {'key1': 'value1', 'key2': 'value2'}\n>>> r = httpx.post(\"https://httpbin.org/post\", data=data)\n>>> print(r.text)\n{\n ...\n \"form\": {\n \"key2\": \"value2\",\n \"key1\": \"value1\"\n },\n ...\n}\n</code></pre> <p>Form encoded data can also include multiple values from a given key.</p> <pre><code>>>> data = {'key1': ['value1', 'value2']}\n>>> r = httpx.post(\"https://httpbin.org/post\", data=data)\n>>> print(r.text)\n{\n ...\n \"form\": {\n \"key1\": [\n \"value1\",\n \"value2\"\n ]\n },\n ...\n}\n</code></pre>"},{"location":"quickstart/#sending-multipart-file-uploads","title":"Sending Multipart File Uploads","text":"<p>You can also upload files, using HTTP multipart encoding:</p> <pre><code>>>> with open('report.xls', 'rb') as report_file:\n... files = {'upload-file': report_file}\n... r = httpx.post(\"https://httpbin.org/post\", files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {\n \"upload-file\": \"<... binary content ...>\"\n },\n ...\n}\n</code></pre> <p>You can also explicitly set the filename and content type, by using a tuple of items for the file value:</p> <pre><code>>>> with open('report.xls', 'rb') report_file:\n... files = {'upload-file': ('report.xls', report_file, 'application/vnd.ms-excel')}\n... r = httpx.post(\"https://httpbin.org/post\", files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {\n \"upload-file\": \"<... binary content ...>\"\n },\n ...\n}\n</code></pre> <p>If you need to include non-file data fields in the multipart form, use the <code>data=...</code> parameter:</p> <pre><code>>>> data = {'message': 'Hello, world!'}\n>>> with open('report.xls', 'rb') as report_file:\n... files = {'file': report_file}\n... r = httpx.post(\"https://httpbin.org/post\", data=data, files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {\n \"file\": \"<... binary content ...>\"\n },\n \"form\": {\n \"message\": \"Hello, world!\",\n },\n ...\n}\n</code></pre>"},{"location":"quickstart/#sending-json-encoded-data","title":"Sending JSON Encoded Data","text":"<p>Form encoded data is okay if all you need is a simple key-value data structure. For more complicated data structures you'll often want to use JSON encoding instead.</p> <pre><code>>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}\n>>> r = httpx.post(\"https://httpbin.org/post\", json=data)\n>>> print(r.text)\n{\n ...\n \"json\": {\n \"boolean\": true,\n \"integer\": 123,\n \"list\": [\n \"a\",\n \"b\",\n \"c\"\n ]\n },\n ...\n}\n</code></pre>"},{"location":"quickstart/#sending-binary-request-data","title":"Sending Binary Request Data","text":"<p>For other encodings, you should use the <code>content=...</code> parameter, passing either a <code>bytes</code> type or a generator that yields <code>bytes</code>.</p> <pre><code>>>> content = b'Hello, world'\n>>> r = httpx.post(\"https://httpbin.org/post\", content=content)\n</code></pre> <p>You may also want to set a custom <code>Content-Type</code> header when uploading binary data.</p>"},{"location":"quickstart/#response-status-codes","title":"Response Status Codes","text":"<p>We can inspect the HTTP status code of the response:</p> <pre><code>>>> r = httpx.get('https://httpbin.org/get')\n>>> r.status_code\n200\n</code></pre> <p>HTTPX also includes an easy shortcut for accessing status codes by their text phrase.</p> <pre><code>>>> r.status_code == httpx.codes.OK\nTrue\n</code></pre> <p>We can raise an exception for any responses which are not a 2xx success code:</p> <pre><code>>>> not_found = httpx.get('https://httpbin.org/status/404')\n>>> not_found.status_code\n404\n>>> not_found.raise_for_status()\nTraceback (most recent call last):\n File \"/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py\", line 837, in raise_for_status\n raise HTTPStatusError(message, response=self)\nhttpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404\nFor more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404\n</code></pre> <p>Any successful response codes will return the <code>Response</code> instance rather than raising an exception.</p> <pre><code>>>> r.raise_for_status()\n</code></pre> <p>The method returns the response instance, allowing you to use it inline. For example:</p> <pre><code>>>> r = httpx.get('...').raise_for_status()\n>>> data = httpx.get('...').raise_for_status().json()\n</code></pre>"},{"location":"quickstart/#response-headers","title":"Response Headers","text":"<p>The response headers are available as a dictionary-like interface.</p> <pre><code>>>> r.headers\nHeaders({\n 'content-encoding': 'gzip',\n 'transfer-encoding': 'chunked',\n 'connection': 'close',\n 'server': 'nginx/1.0.4',\n 'x-runtime': '148ms',\n 'etag': '\"e1ca502697e5c9317743dc078f67693f\"',\n 'content-type': 'application/json'\n})\n</code></pre> <p>The <code>Headers</code> data type is case-insensitive, so you can use any capitalization.</p> <pre><code>>>> r.headers['Content-Type']\n'application/json'\n\n>>> r.headers.get('content-type')\n'application/json'\n</code></pre> <p>Multiple values for a single response header are represented as a single comma-separated value, as per RFC 7230:</p> <p>A recipient MAY combine multiple header fields with the same field name into one \u201cfield-name: field-value\u201d pair, without changing the semantics of the message, by appending each subsequent field-value to the combined field value in order, separated by a comma.</p>"},{"location":"quickstart/#streaming-responses","title":"Streaming Responses","text":"<p>For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.</p> <p>You can stream the binary content of the response...</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... for data in r.iter_bytes():\n... print(data)\n</code></pre> <p>Or the text of the response...</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... for text in r.iter_text():\n... print(text)\n</code></pre> <p>Or stream the text, on a line-by-line basis...</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... for line in r.iter_lines():\n... print(line)\n</code></pre> <p>HTTPX will use universal line endings, normalising all cases to <code>\\n</code>.</p> <p>In some cases you might want to access the raw bytes on the response without applying any HTTP content decoding. In this case any content encoding that the web server has applied such as <code>gzip</code>, <code>deflate</code>, <code>brotli</code>, or <code>zstd</code> will not be automatically decoded.</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... for chunk in r.iter_raw():\n... print(chunk)\n</code></pre> <p>If you're using streaming responses in any of these ways then the <code>response.content</code> and <code>response.text</code> attributes will not be available, and will raise errors if accessed. However you can also use the response streaming functionality to conditionally load the response body:</p> <pre><code>>>> with httpx.stream(\"GET\", \"https://www.example.com\") as r:\n... if int(r.headers['Content-Length']) < TOO_LONG:\n... r.read()\n... print(r.text)\n</code></pre>"},{"location":"quickstart/#cookies","title":"Cookies","text":"<p>Any cookies that are set on the response can be easily accessed:</p> <pre><code>>>> r = httpx.get('https://httpbin.org/cookies/set?chocolate=chip')\n>>> r.cookies['chocolate']\n'chip'\n</code></pre> <p>To include cookies in an outgoing request, use the <code>cookies</code> parameter:</p> <pre><code>>>> cookies = {\"peanut\": \"butter\"}\n>>> r = httpx.get('https://httpbin.org/cookies', cookies=cookies)\n>>> r.json()\n{'cookies': {'peanut': 'butter'}}\n</code></pre> <p>Cookies are returned in a <code>Cookies</code> instance, which is a dict-like data structure with additional API for accessing cookies by their domain or path.</p> <pre><code>>>> cookies = httpx.Cookies()\n>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')\n>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')\n>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)\n>>> r.json()\n{'cookies': {'cookie_on_domain': 'hello, there!'}}\n</code></pre>"},{"location":"quickstart/#redirection-and-history","title":"Redirection and History","text":"<p>By default, HTTPX will not follow redirects for all HTTP methods, although this can be explicitly enabled.</p> <p>For example, GitHub redirects all HTTP requests to HTTPS.</p> <pre><code>>>> r = httpx.get('http://github.com/')\n>>> r.status_code\n301\n>>> r.history\n[]\n>>> r.next_request\n<Request('GET', 'https://github.com/')>\n</code></pre> <p>You can modify the default redirection handling with the <code>follow_redirects</code> parameter:</p> <pre><code>>>> r = httpx.get('http://github.com/', follow_redirects=True)\n>>> r.url\nURL('https://github.com/')\n>>> r.status_code\n200\n>>> r.history\n[<Response [301 Moved Permanently]>]\n</code></pre> <p>The <code>history</code> property of the response can be used to inspect any followed redirects. It contains a list of any redirect responses that were followed, in the order in which they were made.</p>"},{"location":"quickstart/#timeouts","title":"Timeouts","text":"<p>HTTPX defaults to including reasonable timeouts for all network operations, meaning that if a connection is not properly established then it should always raise an error rather than hanging indefinitely.</p> <p>The default timeout for network inactivity is five seconds. You can modify the value to be more or less strict:</p> <pre><code>>>> httpx.get('https://github.com/', timeout=0.001)\n</code></pre> <p>You can also disable the timeout behavior completely...</p> <pre><code>>>> httpx.get('https://github.com/', timeout=None)\n</code></pre> <p>For advanced timeout management, see Timeout fine-tuning.</p>"},{"location":"quickstart/#authentication","title":"Authentication","text":"<p>HTTPX supports Basic and Digest HTTP authentication.</p> <p>To provide Basic authentication credentials, pass a 2-tuple of plaintext <code>str</code> or <code>bytes</code> objects as the <code>auth</code> argument to the request functions:</p> <pre><code>>>> httpx.get(\"https://example.com\", auth=(\"my_user\", \"password123\"))\n</code></pre> <p>To provide credentials for Digest authentication you'll need to instantiate a <code>DigestAuth</code> object with the plaintext username and password as arguments. This object can be then passed as the <code>auth</code> argument to the request methods as above:</p> <pre><code>>>> auth = httpx.DigestAuth(\"my_user\", \"password123\")\n>>> httpx.get(\"https://example.com\", auth=auth)\n<Response [200 OK]>\n</code></pre>"},{"location":"quickstart/#exceptions","title":"Exceptions","text":"<p>HTTPX will raise exceptions if an error occurs.</p> <p>The most important exception classes in HTTPX are <code>RequestError</code> and <code>HTTPStatusError</code>.</p> <p>The <code>RequestError</code> class is a superclass that encompasses any exception that occurs while issuing an HTTP request. These exceptions include a <code>.request</code> attribute.</p> <pre><code>try:\n response = httpx.get(\"https://www.example.com/\")\nexcept httpx.RequestError as exc:\n print(f\"An error occurred while requesting {exc.request.url!r}.\")\n</code></pre> <p>The <code>HTTPStatusError</code> class is raised by <code>response.raise_for_status()</code> on responses which are not a 2xx success code. These exceptions include both a <code>.request</code> and a <code>.response</code> attribute.</p> <pre><code>response = httpx.get(\"https://www.example.com/\")\ntry:\n response.raise_for_status()\nexcept httpx.HTTPStatusError as exc:\n print(f\"Error response {exc.response.status_code} while requesting {exc.request.url!r}.\")\n</code></pre> <p>There is also a base class <code>HTTPError</code> that includes both of these categories, and can be used to catch either failed requests, or 4xx and 5xx responses.</p> <p>You can either use this base class to catch both categories...</p> <pre><code>try:\n response = httpx.get(\"https://www.example.com/\")\n response.raise_for_status()\nexcept httpx.HTTPError as exc:\n print(f\"Error while requesting {exc.request.url!r}.\")\n</code></pre> <p>Or handle each case explicitly...</p> <pre><code>try:\n response = httpx.get(\"https://www.example.com/\")\n response.raise_for_status()\nexcept httpx.RequestError as exc:\n print(f\"An error occurred while requesting {exc.request.url!r}.\")\nexcept httpx.HTTPStatusError as exc:\n print(f\"Error response {exc.response.status_code} while requesting {exc.request.url!r}.\")\n</code></pre> <p>For a full list of available exceptions, see Exceptions (API Reference).</p>"},{"location":"third_party_packages/","title":"Third Party Packages","text":"<p>As HTTPX usage grows, there is an expanding community of developers building tools and libraries that integrate with HTTPX, or depend on HTTPX. Here are some of them.</p>"},{"location":"third_party_packages/#plugins","title":"Plugins","text":""},{"location":"third_party_packages/#hishel","title":"Hishel","text":"<p>GitHub - Documentation</p> <p>An elegant HTTP Cache implementation for HTTPX and HTTP Core.</p>"},{"location":"third_party_packages/#httpx-auth","title":"HTTPX-Auth","text":"<p>GitHub - Documentation</p> <p>Provides authentication classes to be used with HTTPX's authentication parameter.</p>"},{"location":"third_party_packages/#httpx-caching","title":"httpx-caching","text":"<p>Github</p> <p>This package adds caching functionality to HTTPX</p>"},{"location":"third_party_packages/#httpx-secure","title":"httpx-secure","text":"<p>GitHub</p> <p>Drop-in SSRF protection for httpx with DNS caching and custom validation support.</p>"},{"location":"third_party_packages/#httpx-socks","title":"httpx-socks","text":"<p>GitHub</p> <p>Proxy (HTTP, SOCKS) transports for httpx.</p>"},{"location":"third_party_packages/#httpx-sse","title":"httpx-sse","text":"<p>GitHub</p> <p>Allows consuming Server-Sent Events (SSE) with HTTPX.</p>"},{"location":"third_party_packages/#httpx-retries","title":"httpx-retries","text":"<p>GitHub - Documentation</p> <p>A retry layer for HTTPX.</p>"},{"location":"third_party_packages/#httpx-ws","title":"httpx-ws","text":"<p>GitHub - Documentation</p> <p>WebSocket support for HTTPX.</p>"},{"location":"third_party_packages/#pytest-httpx","title":"pytest-HTTPX","text":"<p>GitHub - Documentation</p> <p>Provides a pytest fixture to mock HTTPX within test cases.</p>"},{"location":"third_party_packages/#respx","title":"RESPX","text":"<p>GitHub - Documentation</p> <p>A utility for mocking out HTTPX.</p>"},{"location":"third_party_packages/#rpcpy","title":"rpc.py","text":"<p>Github - Documentation</p> <p>A fast and powerful RPC framework based on ASGI/WSGI. Use HTTPX as the client of the RPC service.</p>"},{"location":"third_party_packages/#libraries-with-httpx-support","title":"Libraries with HTTPX support","text":""},{"location":"third_party_packages/#authlib","title":"Authlib","text":"<p>GitHub - Documentation</p> <p>A python library for building OAuth and OpenID Connect clients and servers. Includes an OAuth HTTPX client.</p>"},{"location":"third_party_packages/#gidgethub","title":"Gidgethub","text":"<p>GitHub - Documentation</p> <p>An asynchronous GitHub API library. Includes HTTPX support.</p>"},{"location":"third_party_packages/#httpdbg","title":"httpdbg","text":"<p>GitHub - Documentation</p> <p>A tool for python developers to easily debug the HTTP(S) client requests in a python program.</p>"},{"location":"third_party_packages/#vcrpy","title":"VCR.py","text":"<p>GitHub - Documentation</p> <p>Record and repeat requests.</p>"},{"location":"third_party_packages/#gists","title":"Gists","text":""},{"location":"third_party_packages/#urllib3-transport","title":"urllib3-transport","text":"<p>GitHub</p> <p>This public gist provides an example implementation for a custom transport implementation on top of the battle-tested <code>urllib3</code> library.</p>"},{"location":"troubleshooting/","title":"Troubleshooting","text":"<p>This page lists some common problems or issues you could encounter while developing with HTTPX, as well as possible solutions.</p>"},{"location":"troubleshooting/#proxies","title":"Proxies","text":""},{"location":"troubleshooting/#the-handshake-operation-timed-out-on-https-requests-when-using-a-proxy","title":"\"<code>The handshake operation timed out</code>\" on HTTPS requests when using a proxy","text":"<p>Description: When using a proxy and making an HTTPS request, you see an exception looking like this:</p> <pre><code>httpx.ProxyError: _ssl.c:1091: The handshake operation timed out\n</code></pre> <p>Similar issues: encode/httpx#1412, encode/httpx#1433</p> <p>Resolution: it is likely that you've set up your proxies like this...</p> <pre><code>mounts = {\n \"http://\": httpx.HTTPTransport(proxy=\"http://myproxy.org\"),\n \"https://\": httpx.HTTPTransport(proxy=\"https://myproxy.org\"),\n}\n</code></pre> <p>Using this setup, you're telling HTTPX to connect to the proxy using HTTP for HTTP requests, and using HTTPS for HTTPS requests.</p> <p>But if you get the error above, it is likely that your proxy doesn't support connecting via HTTPS. Don't worry: that's a common gotcha.</p> <p>Change the scheme of your HTTPS proxy to <code>http://...</code> instead of <code>https://...</code>:</p> <pre><code>mounts = {\n \"http://\": httpx.HTTPTransport(proxy=\"http://myproxy.org\"),\n \"https://\": httpx.HTTPTransport(proxy=\"http://myproxy.org\"),\n}\n</code></pre> <p>This can be simplified to:</p> <pre><code>proxy = \"http://myproxy.org\"\nwith httpx.Client(proxy=proxy) as client:\n ...\n</code></pre> <p>For more information, see Proxies: FORWARD vs TUNNEL.</p>"},{"location":"troubleshooting/#error-when-making-requests-to-an-https-proxy","title":"Error when making requests to an HTTPS proxy","text":"<p>Description: your proxy does support connecting via HTTPS, but you are seeing errors along the lines of...</p> <pre><code>httpx.ProxyError: [SSL: PRE_MAC_LENGTH_TOO_LONG] invalid alert (_ssl.c:1091)\n</code></pre> <p>Similar issues: encode/httpx#1424.</p> <p>Resolution: HTTPX does not properly support HTTPS proxies at this time. If that's something you're interested in having, please see encode/httpx#1434 and consider lending a hand there.</p>"},{"location":"advanced/authentication/","title":"Authentication","text":"<p>Authentication can either be included on a per-request basis...</p> <pre><code>>>> auth = httpx.BasicAuth(username=\"username\", password=\"secret\")\n>>> client = httpx.Client()\n>>> response = client.get(\"https://www.example.com/\", auth=auth)\n</code></pre> <p>Or configured on the client instance, ensuring that all outgoing requests will include authentication credentials...</p> <pre><code>>>> auth = httpx.BasicAuth(username=\"username\", password=\"secret\")\n>>> client = httpx.Client(auth=auth)\n>>> response = client.get(\"https://www.example.com/\")\n</code></pre>"},{"location":"advanced/authentication/#basic-authentication","title":"Basic authentication","text":"<p>HTTP basic authentication is an unencrypted authentication scheme that uses a simple encoding of the username and password in the request <code>Authorization</code> header. Since it is unencrypted it should typically only be used over <code>https</code>, although this is not strictly enforced.</p> <pre><code>>>> auth = httpx.BasicAuth(username=\"finley\", password=\"secret\")\n>>> client = httpx.Client(auth=auth)\n>>> response = client.get(\"https://httpbin.org/basic-auth/finley/secret\")\n>>> response\n<Response [200 OK]>\n</code></pre>"},{"location":"advanced/authentication/#digest-authentication","title":"Digest authentication","text":"<p>HTTP digest authentication is a challenge-response authentication scheme. Unlike basic authentication it provides encryption, and can be used over unencrypted <code>http</code> connections. It requires an additional round-trip in order to negotiate the authentication. </p> <pre><code>>>> auth = httpx.DigestAuth(username=\"olivia\", password=\"secret\")\n>>> client = httpx.Client(auth=auth)\n>>> response = client.get(\"https://httpbin.org/digest-auth/auth/olivia/secret\")\n>>> response\n<Response [200 OK]>\n>>> response.history\n[<Response [401 UNAUTHORIZED]>]\n</code></pre>"},{"location":"advanced/authentication/#netrc-authentication","title":"NetRC authentication","text":"<p>HTTPX can be configured to use a <code>.netrc</code> config file for authentication.</p> <p>The <code>.netrc</code> config file allows authentication credentials to be associated with specified hosts. When a request is made to a host that is found in the netrc file, the username and password will be included using HTTP basic authentication.</p> <p>Example <code>.netrc</code> file:</p> <pre><code>machine example.org\nlogin example-username\npassword example-password\n\nmachine python-httpx.org\nlogin other-username\npassword other-password\n</code></pre> <p>Some examples of configuring <code>.netrc</code> authentication with <code>httpx</code>.</p> <p>Use the default <code>.netrc</code> file in the users home directory:</p> <pre><code>>>> auth = httpx.NetRCAuth()\n>>> client = httpx.Client(auth=auth)\n</code></pre> <p>Use an explicit path to a <code>.netrc</code> file:</p> <pre><code>>>> auth = httpx.NetRCAuth(file=\"/path/to/.netrc\")\n>>> client = httpx.Client(auth=auth)\n</code></pre> <p>Use the <code>NETRC</code> environment variable to configure a path to the <code>.netrc</code> file, or fallback to the default.</p> <pre><code>>>> auth = httpx.NetRCAuth(file=os.environ.get(\"NETRC\"))\n>>> client = httpx.Client(auth=auth)\n</code></pre> <p>The <code>NetRCAuth()</code> class uses the <code>netrc.netrc()</code> function from the Python standard library. See the documentation there for more details on exceptions that may be raised if the <code>.netrc</code> file is not found, or cannot be parsed.</p>"},{"location":"advanced/authentication/#custom-authentication-schemes","title":"Custom authentication schemes","text":"<p>When issuing requests or instantiating a client, the <code>auth</code> argument can be used to pass an authentication scheme to use. The <code>auth</code> argument may be one of the following...</p> <ul> <li>A two-tuple of <code>username</code>/<code>password</code>, to be used with basic authentication.</li> <li>An instance of <code>httpx.BasicAuth()</code>, <code>httpx.DigestAuth()</code>, or <code>httpx.NetRCAuth()</code>.</li> <li>A callable, accepting a request and returning an authenticated request instance.</li> <li>An instance of subclasses of <code>httpx.Auth</code>.</li> </ul> <p>The most involved of these is the last, which allows you to create authentication flows involving one or more requests. A subclass of <code>httpx.Auth</code> should implement <code>def auth_flow(request)</code>, and yield any requests that need to be made...</p> <pre><code>class MyCustomAuth(httpx.Auth):\n def __init__(self, token):\n self.token = token\n\n def auth_flow(self, request):\n # Send the request, with a custom `X-Authentication` header.\n request.headers['X-Authentication'] = self.token\n yield request\n</code></pre> <p>If the auth flow requires more than one request, you can issue multiple yields, and obtain the response in each case...</p> <pre><code>class MyCustomAuth(httpx.Auth):\n def __init__(self, token):\n self.token = token\n\n def auth_flow(self, request):\n response = yield request\n if response.status_code == 401:\n # If the server issues a 401 response then resend the request,\n # with a custom `X-Authentication` header.\n request.headers['X-Authentication'] = self.token\n yield request\n</code></pre> <p>Custom authentication classes are designed to not perform any I/O, so that they may be used with both sync and async client instances. If you are implementing an authentication scheme that requires the request body, then you need to indicate this on the class using a <code>requires_request_body</code> property.</p> <p>You will then be able to access <code>request.content</code> inside the <code>.auth_flow()</code> method.</p> <pre><code>class MyCustomAuth(httpx.Auth):\n requires_request_body = True\n\n def __init__(self, token):\n self.token = token\n\n def auth_flow(self, request):\n response = yield request\n if response.status_code == 401:\n # If the server issues a 401 response then resend the request,\n # with a custom `X-Authentication` header.\n request.headers['X-Authentication'] = self.sign_request(...)\n yield request\n\n def sign_request(self, request):\n # Create a request signature, based on `request.method`, `request.url`,\n # `request.headers`, and `request.content`.\n ...\n</code></pre> <p>Similarly, if you are implementing a scheme that requires access to the response body, then use the <code>requires_response_body</code> property. You will then be able to access response body properties and methods such as <code>response.content</code>, <code>response.text</code>, <code>response.json()</code>, etc.</p> <pre><code>class MyCustomAuth(httpx.Auth):\n requires_response_body = True\n\n def __init__(self, access_token, refresh_token, refresh_url):\n self.access_token = access_token\n self.refresh_token = refresh_token\n self.refresh_url = refresh_url\n\n def auth_flow(self, request):\n request.headers[\"X-Authentication\"] = self.access_token\n response = yield request\n\n if response.status_code == 401:\n # If the server issues a 401 response, then issue a request to\n # refresh tokens, and resend the request.\n refresh_response = yield self.build_refresh_request()\n self.update_tokens(refresh_response)\n\n request.headers[\"X-Authentication\"] = self.access_token\n yield request\n\n def build_refresh_request(self):\n # Return an `httpx.Request` for refreshing tokens.\n ...\n\n def update_tokens(self, response):\n # Update the `.access_token` and `.refresh_token` tokens\n # based on a refresh response.\n data = response.json()\n ...\n</code></pre> <p>If you do need to perform I/O other than HTTP requests, such as accessing a disk-based cache, or you need to use concurrency primitives, such as locks, then you should override <code>.sync_auth_flow()</code> and <code>.async_auth_flow()</code> (instead of <code>.auth_flow()</code>). The former will be used by <code>httpx.Client</code>, while the latter will be used by <code>httpx.AsyncClient</code>.</p> <pre><code>import asyncio\nimport threading\nimport httpx\n\n\nclass MyCustomAuth(httpx.Auth):\n def __init__(self):\n self._sync_lock = threading.RLock()\n self._async_lock = asyncio.Lock()\n\n def sync_get_token(self):\n with self._sync_lock:\n ...\n\n def sync_auth_flow(self, request):\n token = self.sync_get_token()\n request.headers[\"Authorization\"] = f\"Token {token}\"\n yield request\n\n async def async_get_token(self):\n async with self._async_lock:\n ...\n\n async def async_auth_flow(self, request):\n token = await self.async_get_token()\n request.headers[\"Authorization\"] = f\"Token {token}\"\n yield request\n</code></pre> <p>If you only want to support one of the two methods, then you should still override it, but raise an explicit <code>RuntimeError</code>.</p> <pre><code>import httpx\nimport sync_only_library\n\n\nclass MyCustomAuth(httpx.Auth):\n def sync_auth_flow(self, request):\n token = sync_only_library.get_token(...)\n request.headers[\"Authorization\"] = f\"Token {token}\"\n yield request\n\n async def async_auth_flow(self, request):\n raise RuntimeError(\"Cannot use a sync authentication class with httpx.AsyncClient\")\n</code></pre>"},{"location":"advanced/clients/","title":"Clients","text":"<p>Hint</p> <p>If you are coming from Requests, <code>httpx.Client()</code> is what you can use instead of <code>requests.Session()</code>.</p>"},{"location":"advanced/clients/#why-use-a-client","title":"Why use a Client?","text":"<p>TL;DR</p> <p>If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a <code>Client</code> instance.</p> <p>More efficient usage of network resources</p> <p>When you make requests using the top-level API as documented in the Quickstart guide, HTTPX has to establish a new connection for every single request (connections are not reused). As the number of requests to a host increases, this quickly becomes inefficient.</p> <p>On the other hand, a <code>Client</code> instance uses HTTP connection pooling. This means that when you make several requests to the same host, the <code>Client</code> will reuse the underlying TCP connection, instead of recreating one for every single request.</p> <p>This can bring significant performance improvements compared to using the top-level API, including:</p> <ul> <li>Reduced latency across requests (no handshaking).</li> <li>Reduced CPU usage and round-trips.</li> <li>Reduced network congestion.</li> </ul> <p>Extra features</p> <p><code>Client</code> instances also support features that aren't available at the top-level API, such as:</p> <ul> <li>Cookie persistence across requests.</li> <li>Applying configuration across all outgoing requests.</li> <li>Sending requests through HTTP proxies.</li> <li>Using HTTP/2.</li> </ul> <p>The other sections on this page go into further detail about what you can do with a <code>Client</code> instance.</p>"},{"location":"advanced/clients/#usage","title":"Usage","text":"<p>The recommended way to use a <code>Client</code> is as a context manager. This will ensure that connections are properly cleaned up when leaving the <code>with</code> block:</p> <pre><code>with httpx.Client() as client:\n ...\n</code></pre> <p>Alternatively, you can explicitly close the connection pool without block-usage using <code>.close()</code>:</p> <pre><code>client = httpx.Client()\ntry:\n ...\nfinally:\n client.close()\n</code></pre>"},{"location":"advanced/clients/#making-requests","title":"Making requests","text":"<p>Once you have a <code>Client</code>, you can send requests using <code>.get()</code>, <code>.post()</code>, etc. For example:</p> <pre><code>>>> with httpx.Client() as client:\n... r = client.get('https://example.com')\n...\n>>> r\n<Response [200 OK]>\n</code></pre> <p>These methods accept the same arguments as <code>httpx.get()</code>, <code>httpx.post()</code>, etc. This means that all features documented in the Quickstart guide are also available at the client level.</p> <p>For example, to send a request with custom headers:</p> <pre><code>>>> with httpx.Client() as client:\n... headers = {'X-Custom': 'value'}\n... r = client.get('https://example.com', headers=headers)\n...\n>>> r.request.headers['X-Custom']\n'value'\n</code></pre>"},{"location":"advanced/clients/#sharing-configuration-across-requests","title":"Sharing configuration across requests","text":"<p>Clients allow you to apply configuration to all outgoing requests by passing parameters to the <code>Client</code> constructor.</p> <p>For example, to apply a set of custom headers on every request:</p> <pre><code>>>> url = 'http://httpbin.org/headers'\n>>> headers = {'user-agent': 'my-app/0.0.1'}\n>>> with httpx.Client(headers=headers) as client:\n... r = client.get(url)\n...\n>>> r.json()['headers']['User-Agent']\n'my-app/0.0.1'\n</code></pre>"},{"location":"advanced/clients/#merging-of-configuration","title":"Merging of configuration","text":"<p>When a configuration option is provided at both the client-level and request-level, one of two things can happen:</p> <ul> <li>For headers, query parameters and cookies, the values are combined together. For example:</li> </ul> <pre><code>>>> headers = {'X-Auth': 'from-client'}\n>>> params = {'client_id': 'client1'}\n>>> with httpx.Client(headers=headers, params=params) as client:\n... headers = {'X-Custom': 'from-request'}\n... params = {'request_id': 'request1'}\n... r = client.get('https://example.com', headers=headers, params=params)\n...\n>>> r.request.url\nURL('https://example.com?client_id=client1&request_id=request1')\n>>> r.request.headers['X-Auth']\n'from-client'\n>>> r.request.headers['X-Custom']\n'from-request'\n</code></pre> <ul> <li>For all other parameters, the request-level value takes priority. For example:</li> </ul> <pre><code>>>> with httpx.Client(auth=('tom', 'mot123')) as client:\n... r = client.get('https://example.com', auth=('alice', 'ecila123'))\n...\n>>> _, _, auth = r.request.headers['Authorization'].partition(' ')\n>>> import base64\n>>> base64.b64decode(auth)\nb'alice:ecila123'\n</code></pre> <p>If you need finer-grained control on the merging of client-level and request-level parameters, see Request instances.</p>"},{"location":"advanced/clients/#other-client-only-configuration-options","title":"Other Client-only configuration options","text":"<p>Additionally, <code>Client</code> accepts some configuration options that aren't available at the request level.</p> <p>For example, <code>base_url</code> allows you to prepend an URL to all outgoing requests:</p> <pre><code>>>> with httpx.Client(base_url='http://httpbin.org') as client:\n... r = client.get('/headers')\n...\n>>> r.request.url\nURL('http://httpbin.org/headers')\n</code></pre> <p>For a list of all available client parameters, see the <code>Client</code> API reference.</p>"},{"location":"advanced/clients/#request-instances","title":"Request instances","text":"<p>For maximum control on what gets sent over the wire, HTTPX supports building explicit <code>Request</code> instances:</p> <pre><code>request = httpx.Request(\"GET\", \"https://example.com\")\n</code></pre> <p>To dispatch a <code>Request</code> instance across to the network, create a <code>Client</code> instance and use <code>.send()</code>:</p> <pre><code>with httpx.Client() as client:\n response = client.send(request)\n ...\n</code></pre> <p>If you need to mix client-level and request-level options in a way that is not supported by the default Merging of parameters, you can use <code>.build_request()</code> and then make arbitrary modifications to the <code>Request</code> instance. For example:</p> <pre><code>headers = {\"X-Api-Key\": \"...\", \"X-Client-ID\": \"ABC123\"}\n\nwith httpx.Client(headers=headers) as client:\n request = client.build_request(\"GET\", \"https://api.example.com\")\n\n print(request.headers[\"X-Client-ID\"]) # \"ABC123\"\n\n # Don't send the API key for this particular request.\n del request.headers[\"X-Api-Key\"]\n\n response = client.send(request)\n ...\n</code></pre>"},{"location":"advanced/clients/#monitoring-download-progress","title":"Monitoring download progress","text":"<p>If you need to monitor download progress of large responses, you can use response streaming and inspect the <code>response.num_bytes_downloaded</code> property.</p> <p>This interface is required for properly determining download progress, because the total number of bytes returned by <code>response.content</code> or <code>response.iter_content()</code> will not always correspond with the raw content length of the response if HTTP response compression is being used.</p> <p>For example, showing a progress bar using the <code>tqdm</code> library while a response is being downloaded could be done like this\u2026</p> <pre><code>import tempfile\n\nimport httpx\nfrom tqdm import tqdm\n\nwith tempfile.NamedTemporaryFile() as download_file:\n url = \"https://speed.hetzner.de/100MB.bin\"\n with httpx.stream(\"GET\", url) as response:\n total = int(response.headers[\"Content-Length\"])\n\n with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit=\"B\") as progress:\n num_bytes_downloaded = response.num_bytes_downloaded\n for chunk in response.iter_bytes():\n download_file.write(chunk)\n progress.update(response.num_bytes_downloaded - num_bytes_downloaded)\n num_bytes_downloaded = response.num_bytes_downloaded\n</code></pre> <p></p> <p>Or an alternate example, this time using the <code>rich</code> library\u2026</p> <pre><code>import tempfile\nimport httpx\nimport rich.progress\n\nwith tempfile.NamedTemporaryFile() as download_file:\n url = \"https://speed.hetzner.de/100MB.bin\"\n with httpx.stream(\"GET\", url) as response:\n total = int(response.headers[\"Content-Length\"])\n\n with rich.progress.Progress(\n \"[progress.percentage]{task.percentage:>3.0f}%\",\n rich.progress.BarColumn(bar_width=None),\n rich.progress.DownloadColumn(),\n rich.progress.TransferSpeedColumn(),\n ) as progress:\n download_task = progress.add_task(\"Download\", total=total)\n for chunk in response.iter_bytes():\n download_file.write(chunk)\n progress.update(download_task, completed=response.num_bytes_downloaded)\n</code></pre> <p></p>"},{"location":"advanced/clients/#monitoring-upload-progress","title":"Monitoring upload progress","text":"<p>If you need to monitor upload progress of large responses, you can use request content generator streaming.</p> <p>For example, showing a progress bar using the <code>tqdm</code> library.</p> <pre><code>import io\nimport random\n\nimport httpx\nfrom tqdm import tqdm\n\n\ndef gen():\n \"\"\"\n this is a complete example with generated random bytes.\n you can replace `io.BytesIO` with real file object.\n \"\"\"\n total = 32 * 1024 * 1024 # 32m\n with tqdm(ascii=True, unit_scale=True, unit='B', unit_divisor=1024, total=total) as bar:\n with io.BytesIO(random.randbytes(total)) as f:\n while data := f.read(1024):\n yield data\n bar.update(len(data))\n\n\nhttpx.post(\"https://httpbin.org/post\", content=gen())\n</code></pre> <p></p>"},{"location":"advanced/clients/#multipart-file-encoding","title":"Multipart file encoding","text":"<p>As mentioned in the quickstart multipart file encoding is available by passing a dictionary with the name of the payloads as keys and either tuple of elements or a file-like object or a string as values.</p> <pre><code>>>> with open('report.xls', 'rb') as report_file:\n... files = {'upload-file': ('report.xls', report_file, 'application/vnd.ms-excel')}\n... r = httpx.post(\"https://httpbin.org/post\", files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {\n \"upload-file\": \"<... binary content ...>\"\n },\n ...\n}\n</code></pre> <p>More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:</p> <ul> <li>The first element is an optional file name which can be set to <code>None</code>.</li> <li>The second element may be a file-like object or a string which will be automatically encoded in UTF-8.</li> <li>An optional third element can be used to specify the MIME type of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based on the file name, with unknown file extensions defaulting to \"application/octet-stream\". If the file name is explicitly set to <code>None</code> then HTTPX will not include a content-type MIME header field.</li> </ul> <pre><code>>>> files = {'upload-file': (None, 'text content', 'text/plain')}\n>>> r = httpx.post(\"https://httpbin.org/post\", files=files)\n>>> print(r.text)\n{\n ...\n \"files\": {},\n \"form\": {\n \"upload-file\": \"text-content\"\n },\n ...\n}\n</code></pre> <p>Tip</p> <p>It is safe to upload large files this way. File uploads are streaming by default, meaning that only one chunk will be loaded into memory at a time.</p> <p>Non-file data fields can be included in the multipart form using by passing them to <code>data=...</code>.</p> <p>You can also send multiple files in one go with a multiple file field form. To do that, pass a list of <code>(field, <file>)</code> items instead of a dictionary, allowing you to pass multiple items with the same <code>field</code>. For instance this request sends 2 files, <code>foo.png</code> and <code>bar.png</code> in one request on the <code>images</code> form field:</p> <pre><code>>>> with open('foo.png', 'rb') as foo_file, open('bar.png', 'rb') as bar_file:\n... files = [\n... ('images', ('foo.png', foo_file, 'image/png')),\n... ('images', ('bar.png', bar_file, 'image/png')),\n... ]\n... r = httpx.post(\"https://httpbin.org/post\", files=files)\n</code></pre>"},{"location":"advanced/event-hooks/","title":"Event Hooks","text":"<p>HTTPX allows you to register \"event hooks\" with the client, that are called every time a particular type of event takes place.</p> <p>There are currently two event hooks:</p> <ul> <li><code>request</code> - Called after a request is fully prepared, but before it is sent to the network. Passed the <code>request</code> instance.</li> <li><code>response</code> - Called after the response has been fetched from the network, but before it is returned to the caller. Passed the <code>response</code> instance.</li> </ul> <p>These allow you to install client-wide functionality such as logging, monitoring or tracing.</p> <pre><code>def log_request(request):\n print(f\"Request event hook: {request.method} {request.url} - Waiting for response\")\n\ndef log_response(response):\n request = response.request\n print(f\"Response event hook: {request.method} {request.url} - Status {response.status_code}\")\n\nclient = httpx.Client(event_hooks={'request': [log_request], 'response': [log_response]})\n</code></pre> <p>You can also use these hooks to install response processing code, such as this example, which creates a client instance that always raises <code>httpx.HTTPStatusError</code> on 4xx and 5xx responses.</p> <pre><code>def raise_on_4xx_5xx(response):\n response.raise_for_status()\n\nclient = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})\n</code></pre> <p>Note</p> <p>Response event hooks are called before determining if the response body should be read or not.</p> <p>If you need access to the response body inside an event hook, you'll need to call <code>response.read()</code>, or for AsyncClients, <code>response.aread()</code>.</p> <p>The hooks are also allowed to modify <code>request</code> and <code>response</code> objects.</p> <pre><code>def add_timestamp(request):\n request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat()\n\nclient = httpx.Client(event_hooks={'request': [add_timestamp]})\n</code></pre> <p>Event hooks must always be set as a list of callables, and you may register multiple event hooks for each type of event.</p> <p>As well as being able to set event hooks on instantiating the client, there is also an <code>.event_hooks</code> property, that allows you to inspect and modify the installed hooks.</p> <pre><code>client = httpx.Client()\nclient.event_hooks['request'] = [log_request]\nclient.event_hooks['response'] = [log_response, raise_on_4xx_5xx]\n</code></pre> <p>Note</p> <p>If you are using HTTPX's async support, then you need to be aware that hooks registered with <code>httpx.AsyncClient</code> MUST be async functions, rather than plain functions.</p>"},{"location":"advanced/extensions/","title":"Extensions","text":"<p>Request and response extensions provide a untyped space where additional information may be added.</p> <p>Extensions should be used for features that may not be available on all transports, and that do not fit neatly into the simplified request/response model that the underlying <code>httpcore</code> package uses as its API.</p> <p>Several extensions are supported on the request:</p> <pre><code># Request timeouts actually implemented as an extension on\n# the request, ensuring that they are passed throughout the\n# entire call stack.\nclient = httpx.Client()\nresponse = client.get(\n \"https://www.example.com\",\n extensions={\"timeout\": {\"connect\": 5.0}}\n)\nresponse.request.extensions[\"timeout\"]\n{\"connect\": 5.0}\n</code></pre> <p>And on the response:</p> <pre><code>client = httpx.Client()\nresponse = client.get(\"https://www.example.com\")\nprint(response.extensions[\"http_version\"]) # b\"HTTP/1.1\"\n# Other server responses could have been\n# b\"HTTP/0.9\", b\"HTTP/1.0\", or b\"HTTP/1.1\"\n</code></pre>"},{"location":"advanced/extensions/#request-extensions","title":"Request Extensions","text":""},{"location":"advanced/extensions/#trace","title":"<code>\"trace\"</code>","text":"<p>The trace extension allows a callback handler to be installed to monitor the internal flow of events within the underlying <code>httpcore</code> transport.</p> <p>The simplest way to explain this is with an example:</p> <pre><code>import httpx\n\ndef log(event_name, info):\n print(event_name, info)\n\nclient = httpx.Client()\nresponse = client.get(\"https://www.example.com/\", extensions={\"trace\": log})\n# connection.connect_tcp.started {'host': 'www.example.com', 'port': 443, 'local_address': None, 'timeout': None}\n# connection.connect_tcp.complete {'return_value': <httpcore.backends.sync.SyncStream object at 0x1093f94d0>}\n# connection.start_tls.started {'ssl_context': <ssl.SSLContext object at 0x1093ee750>, 'server_hostname': b'www.example.com', 'timeout': None}\n# connection.start_tls.complete {'return_value': <httpcore.backends.sync.SyncStream object at 0x1093f9450>}\n# http11.send_request_headers.started {'request': <Request [b'GET']>}\n# http11.send_request_headers.complete {'return_value': None}\n# http11.send_request_body.started {'request': <Request [b'GET']>}\n# http11.send_request_body.complete {'return_value': None}\n# http11.receive_response_headers.started {'request': <Request [b'GET']>}\n# http11.receive_response_headers.complete {'return_value': (b'HTTP/1.1', 200, b'OK', [(b'Age', b'553715'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Thu, 21 Oct 2021 17:08:42 GMT'), (b'Etag', b'\"3147526947+ident\"'), (b'Expires', b'Thu, 28 Oct 2021 17:08:42 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECS (nyb/1DCD)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'1256')])}\n# http11.receive_response_body.started {'request': <Request [b'GET']>}\n# http11.receive_response_body.complete {'return_value': None}\n# http11.response_closed.started {}\n# http11.response_closed.complete {'return_value': None}\n</code></pre> <p>The <code>event_name</code> and <code>info</code> arguments here will be one of the following:</p> <ul> <li><code>{event_type}.{event_name}.started</code>, <code><dictionary of keyword arguments></code></li> <li><code>{event_type}.{event_name}.complete</code>, <code>{\"return_value\": <...>}</code></li> <li><code>{event_type}.{event_name}.failed</code>, <code>{\"exception\": <...>}</code></li> </ul> <p>Note that when using async code the handler function passed to <code>\"trace\"</code> must be an <code>async def ...</code> function.</p> <p>The following event types are currently exposed...</p> <p>Establishing the connection</p> <ul> <li><code>\"connection.connect_tcp\"</code></li> <li><code>\"connection.connect_unix_socket\"</code></li> <li><code>\"connection.start_tls\"</code></li> </ul> <p>HTTP/1.1 events</p> <ul> <li><code>\"http11.send_request_headers\"</code></li> <li><code>\"http11.send_request_body\"</code></li> <li><code>\"http11.receive_response\"</code></li> <li><code>\"http11.receive_response_body\"</code></li> <li><code>\"http11.response_closed\"</code></li> </ul> <p>HTTP/2 events</p> <ul> <li><code>\"http2.send_connection_init\"</code></li> <li><code>\"http2.send_request_headers\"</code></li> <li><code>\"http2.send_request_body\"</code></li> <li><code>\"http2.receive_response_headers\"</code></li> <li><code>\"http2.receive_response_body\"</code></li> <li><code>\"http2.response_closed\"</code></li> </ul> <p>The exact set of trace events may be subject to change across different versions of <code>httpcore</code>. If you need to rely on a particular set of events it is recommended that you pin installation of the package to a fixed version.</p>"},{"location":"advanced/extensions/#sni_hostname","title":"<code>\"sni_hostname\"</code>","text":"<p>The server's hostname, which is used to confirm the hostname supplied by the SSL certificate.</p> <p>If you want to connect to an explicit IP address rather than using the standard DNS hostname lookup, then you'll need to use this request extension.</p> <p>For example:</p> <pre><code># Connect to '185.199.108.153' but use 'www.encode.io' in the Host header,\n#\u00a0and use 'www.encode.io' when SSL verifying the server hostname.\nclient = httpx.Client()\nheaders = {\"Host\": \"www.encode.io\"}\nextensions = {\"sni_hostname\": \"www.encode.io\"}\nresponse = client.get(\n \"https://185.199.108.153/path\",\n headers=headers,\n extensions=extensions\n)\n</code></pre>"},{"location":"advanced/extensions/#timeout","title":"<code>\"timeout\"</code>","text":"<p>A dictionary of <code>str: Optional[float]</code> timeout values.</p> <p>May include values for <code>'connect'</code>, <code>'read'</code>, <code>'write'</code>, or <code>'pool'</code>.</p> <p>For example:</p> <pre><code># Timeout if a connection takes more than 5 seconds to established, or if\n# we are blocked waiting on the connection pool for more than 10 seconds.\nclient = httpx.Client()\nresponse = client.get(\n \"https://www.example.com\",\n extensions={\"timeout\": {\"connect\": 5.0, \"pool\": 10.0}}\n)\n</code></pre> <p>This extension is how the <code>httpx</code> timeouts are implemented, ensuring that the timeout values are associated with the request instance and passed throughout the stack. You shouldn't typically be working with this extension directly, but use the higher level <code>timeout</code> API instead.</p>"},{"location":"advanced/extensions/#target","title":"<code>\"target\"</code>","text":"<p>The target that is used as the HTTP target instead of the URL path.</p> <p>This enables support constructing requests that would otherwise be unsupported.</p> <ul> <li>URL paths with non-standard escaping applied.</li> <li>Forward proxy requests using an absolute URI.</li> <li>Tunneling proxy requests using <code>CONNECT</code> with hostname as the target.</li> <li>Server-wide <code>OPTIONS *</code> requests.</li> </ul> <p>Some examples:</p> <p>Using the 'target' extension to send requests without the standard path escaping rules...</p> <pre><code># Typically a request to \"https://www.example.com/test^path\" would\n# connect to \"www.example.com\" and send an HTTP/1.1 request like...\n#\n# GET /test%5Epath HTTP/1.1\n#\n# Using the target extension we can include the literal '^'...\n#\n# GET /test^path HTTP/1.1\n#\n# Note that requests must still be valid HTTP requests.\n# For example including whitespace in the target will raise a `LocalProtocolError`.\nextensions = {\"target\": b\"/test^path\"}\nresponse = httpx.get(\"https://www.example.com\", extensions=extensions)\n</code></pre> <p>The <code>target</code> extension also allows server-wide <code>OPTIONS *</code> requests to be constructed...</p> <pre><code># This will send the following request...\n#\n# CONNECT * HTTP/1.1\nextensions = {\"target\": b\"*\"}\nresponse = httpx.request(\"CONNECT\", \"https://www.example.com\", extensions=extensions)\n</code></pre>"},{"location":"advanced/extensions/#response-extensions","title":"Response Extensions","text":""},{"location":"advanced/extensions/#http_version","title":"<code>\"http_version\"</code>","text":"<p>The HTTP version, as bytes. Eg. <code>b\"HTTP/1.1\"</code>.</p> <p>When using HTTP/1.1 the response line includes an explicit version, and the value of this key could feasibly be one of <code>b\"HTTP/0.9\"</code>, <code>b\"HTTP/1.0\"</code>, or <code>b\"HTTP/1.1\"</code>.</p> <p>When using HTTP/2 there is no further response versioning included in the protocol, and the value of this key will always be <code>b\"HTTP/2\"</code>.</p>"},{"location":"advanced/extensions/#reason_phrase","title":"<code>\"reason_phrase\"</code>","text":"<p>The reason-phrase of the HTTP response, as bytes. For example <code>b\"OK\"</code>. Some servers may include a custom reason phrase, although this is not recommended.</p> <p>HTTP/2 onwards does not include a reason phrase on the wire.</p> <p>When no key is included, a default based on the status code may be used.</p>"},{"location":"advanced/extensions/#stream_id","title":"<code>\"stream_id\"</code>","text":"<p>When HTTP/2 is being used the <code>\"stream_id\"</code> response extension can be accessed to determine the ID of the data stream that the response was sent on.</p>"},{"location":"advanced/extensions/#network_stream","title":"<code>\"network_stream\"</code>","text":"<p>The <code>\"network_stream\"</code> extension allows developers to handle HTTP <code>CONNECT</code> and <code>Upgrade</code> requests, by providing an API that steps outside the standard request/response model, and can directly read or write to the network.</p> <p>The interface provided by the network stream:</p> <ul> <li><code>read(max_bytes, timeout = None) -> bytes</code></li> <li><code>write(buffer, timeout = None)</code></li> <li><code>close()</code></li> <li><code>start_tls(ssl_context, server_hostname = None, timeout = None) -> NetworkStream</code></li> <li><code>get_extra_info(info) -> Any</code></li> </ul> <p>This API can be used as the foundation for working with HTTP proxies, WebSocket upgrades, and other advanced use-cases.</p> <p>See the network backends documentation for more information on working directly with network streams.</p> <p>Extra network information</p> <p>The network stream abstraction also allows access to various low-level information that may be exposed by the underlying socket:</p> <pre><code>response = httpx.get(\"https://www.example.com\")\nnetwork_stream = response.extensions[\"network_stream\"]\n\nclient_addr = network_stream.get_extra_info(\"client_addr\")\nserver_addr = network_stream.get_extra_info(\"server_addr\")\nprint(\"Client address\", client_addr)\nprint(\"Server address\", server_addr)\n</code></pre> <p>The socket SSL information is also available through this interface, although you need to ensure that the underlying connection is still open, in order to access it...</p> <pre><code>with httpx.stream(\"GET\", \"https://www.example.com\") as response:\n network_stream = response.extensions[\"network_stream\"]\n\n ssl_object = network_stream.get_extra_info(\"ssl_object\")\n print(\"TLS version\", ssl_object.version())\n</code></pre>"},{"location":"advanced/proxies/","title":"Proxies","text":"<p>HTTPX supports setting up HTTP proxies via the <code>proxy</code> parameter to be passed on client initialization or top-level API functions like <code>httpx.get(..., proxy=...)</code>.</p> Diagram of how a proxy works (source: Wikipedia). The left hand side \"Internet\" blob may be your HTTPX client requesting <code>example.com</code> through a proxy."},{"location":"advanced/proxies/#http-proxies","title":"HTTP Proxies","text":"<p>To route all traffic (HTTP and HTTPS) to a proxy located at <code>http://localhost:8030</code>, pass the proxy URL to the client...</p> <pre><code>with httpx.Client(proxy=\"http://localhost:8030\") as client:\n ...\n</code></pre> <p>For more advanced use cases, pass a mounts <code>dict</code>. For example, to route HTTP and HTTPS requests to 2 different proxies, respectively located at <code>http://localhost:8030</code>, and <code>http://localhost:8031</code>, pass a <code>dict</code> of proxy URLs:</p> <pre><code>proxy_mounts = {\n \"http://\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n \"https://\": httpx.HTTPTransport(proxy=\"http://localhost:8031\"),\n}\n\nwith httpx.Client(mounts=proxy_mounts) as client:\n ...\n</code></pre> <p>For detailed information about proxy routing, see the Routing section.</p> <p>Gotcha</p> <p>In most cases, the proxy URL for the <code>https://</code> key should use the <code>http://</code> scheme (that's not a typo!).</p> <p>This is because HTTP proxying requires initiating a connection with the proxy server. While it's possible that your proxy supports doing it via HTTPS, most proxies only support doing it via HTTP.</p> <p>For more information, see FORWARD vs TUNNEL.</p>"},{"location":"advanced/proxies/#authentication","title":"Authentication","text":"<p>Proxy credentials can be passed as the <code>userinfo</code> section of the proxy URL. For example:</p> <pre><code>with httpx.Client(proxy=\"http://username:password@localhost:8030\") as client:\n ...\n</code></pre>"},{"location":"advanced/proxies/#proxy-mechanisms","title":"Proxy mechanisms","text":"<p>Note</p> <p>This section describes advanced proxy concepts and functionality.</p>"},{"location":"advanced/proxies/#forward-vs-tunnel","title":"FORWARD vs TUNNEL","text":"<p>In general, the flow for making an HTTP request through a proxy is as follows:</p> <ol> <li>The client connects to the proxy (initial connection request).</li> <li>The proxy transfers data to the server on your behalf.</li> </ol> <p>How exactly step 2/ is performed depends on which of two proxying mechanisms is used:</p> <ul> <li>Forwarding: the proxy makes the request for you, and sends back the response it obtained from the server.</li> <li>Tunnelling: the proxy establishes a TCP connection to the server on your behalf, and the client reuses this connection to send the request and receive the response. This is known as an HTTP Tunnel. This mechanism is how you can access websites that use HTTPS from an HTTP proxy (the client \"upgrades\" the connection to HTTPS by performing the TLS handshake with the server over the TCP connection provided by the proxy).</li> </ul>"},{"location":"advanced/proxies/#troubleshooting-proxies","title":"Troubleshooting proxies","text":"<p>If you encounter issues when setting up proxies, please refer to our Troubleshooting guide.</p>"},{"location":"advanced/proxies/#socks","title":"SOCKS","text":"<p>In addition to HTTP proxies, <code>httpcore</code> also supports proxies using the SOCKS protocol. This is an optional feature that requires an additional third-party library be installed before use.</p> <p>You can install SOCKS support using <code>pip</code>:</p> <pre><code>$ pip install httpx[socks]\n</code></pre> <p>You can now configure a client to make requests via a proxy using the SOCKS protocol:</p> <pre><code>httpx.Client(proxy='socks5://user:pass@host:port')\n</code></pre>"},{"location":"advanced/resource-limits/","title":"Resource Limits","text":"<p>You can control the connection pool size using the <code>limits</code> keyword argument on the client. It takes instances of <code>httpx.Limits</code> which define:</p> <ul> <li><code>max_keepalive_connections</code>, number of allowable keep-alive connections, or <code>None</code> to always allow. (Defaults 20)</li> <li><code>max_connections</code>, maximum number of allowable connections, or <code>None</code> for no limits. (Default 100)</li> <li><code>keepalive_expiry</code>, time limit on idle keep-alive connections in seconds, or <code>None</code> for no limits. (Default 5)</li> </ul> <pre><code>limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)\nclient = httpx.Client(limits=limits)\n</code></pre>"},{"location":"advanced/ssl/","title":"SSL","text":"<p>When making a request over HTTPS, HTTPX needs to verify the identity of the requested host. To do this, it uses a bundle of SSL certificates (a.k.a. CA bundle) delivered by a trusted certificate authority (CA).</p>"},{"location":"advanced/ssl/#enabling-and-disabling-verification","title":"Enabling and disabling verification","text":"<p>By default httpx will verify HTTPS connections, and raise an error for invalid SSL cases...</p> <pre><code>>>> httpx.get(\"https://expired.badssl.com/\")\nhttpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)\n</code></pre> <p>You can disable SSL verification completely and allow insecure requests...</p> <pre><code>>>> httpx.get(\"https://expired.badssl.com/\", verify=False)\n<Response [200 OK]>\n</code></pre>"},{"location":"advanced/ssl/#configuring-client-instances","title":"Configuring client instances","text":"<p>If you're using a <code>Client()</code> instance you should pass any <code>verify=<...></code> configuration when instantiating the client.</p> <p>By default the certifi CA bundle is used for SSL verification.</p> <p>For more complex configurations you can pass an SSL Context instance...</p> <pre><code>import certifi\nimport httpx\nimport ssl\n\n# This SSL context is equivelent to the default `verify=True`.\nctx = ssl.create_default_context(cafile=certifi.where())\nclient = httpx.Client(verify=ctx)\n</code></pre> <p>Using the <code>truststore</code> package to support system certificate stores...</p> <pre><code>import ssl\nimport truststore\nimport httpx\n\n# Use system certificate stores.\nctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\nclient = httpx.Client(verify=ctx)\n</code></pre> <p>Loding an alternative certificate verification store using the standard SSL context API...</p> <pre><code>import httpx\nimport ssl\n\n# Use an explicitly configured certificate store.\nctx = ssl.create_default_context(cafile=\"path/to/certs.pem\") # Either cafile or capath.\nclient = httpx.Client(verify=ctx)\n</code></pre>"},{"location":"advanced/ssl/#client-side-certificates","title":"Client side certificates","text":"<p>Client side certificates allow a remote server to verify the client. They tend to be used within private organizations to authenticate requests to remote servers.</p> <p>You can specify client-side certificates, using the <code>.load_cert_chain()</code> API...</p> <pre><code>ctx = ssl.create_default_context()\nctx.load_cert_chain(certfile=\"path/to/client.pem\") # Optionally also keyfile or password.\nclient = httpx.Client(verify=ctx)\n</code></pre>"},{"location":"advanced/ssl/#working-with-ssl_cert_file-and-ssl_cert_dir","title":"Working with <code>SSL_CERT_FILE</code> and <code>SSL_CERT_DIR</code>","text":"<p><code>httpx</code> does respect the <code>SSL_CERT_FILE</code> and <code>SSL_CERT_DIR</code> environment variables by default. For details, refer to the section on the environment variables page.</p>"},{"location":"advanced/ssl/#making-https-requests-to-a-local-server","title":"Making HTTPS requests to a local server","text":"<p>When making requests to local servers, such as a development server running on <code>localhost</code>, you will typically be using unencrypted HTTP connections.</p> <p>If you do need to make HTTPS connections to a local server, for example to test an HTTPS-only service, you will need to create and use your own certificates. Here's one way to do it...</p> <ol> <li>Use trustme to generate a pair of server key/cert files, and a client cert file.</li> <li>Pass the server key/cert files when starting your local server. (This depends on the particular web server you're using. For example, Uvicorn provides the <code>--ssl-keyfile</code> and <code>--ssl-certfile</code> options.)</li> <li>Configure <code>httpx</code> to use the certificates stored in <code>client.pem</code>.</li> </ol> <pre><code>ctx = ssl.create_default_context(cafile=\"client.pem\")\nclient = httpx.Client(verify=ctx)\n</code></pre>"},{"location":"advanced/text-encodings/","title":"Text Encodings","text":"<p>When accessing <code>response.text</code>, we need to decode the response bytes into a unicode text representation.</p> <p>By default <code>httpx</code> will use <code>\"charset\"</code> information included in the response <code>Content-Type</code> header to determine how the response bytes should be decoded into text.</p> <p>In cases where no charset information is included on the response, the default behaviour is to assume \"utf-8\" encoding, which is by far the most widely used text encoding on the internet.</p>"},{"location":"advanced/text-encodings/#using-the-default-encoding","title":"Using the default encoding","text":"<p>To understand this better let's start by looking at the default behaviour for text decoding...</p> <pre><code>import httpx\n# Instantiate a client with the default configuration.\nclient = httpx.Client()\n# Using the client...\nresponse = client.get(...)\nprint(response.encoding) # This will either print the charset given in\n # the Content-Type charset, or else \"utf-8\".\nprint(response.text) # The text will either be decoded with the Content-Type\n # charset, or using \"utf-8\".\n</code></pre> <p>This is normally absolutely fine. Most servers will respond with a properly formatted Content-Type header, including a charset encoding. And in most cases where no charset encoding is included, UTF-8 is very likely to be used, since it is so widely adopted.</p>"},{"location":"advanced/text-encodings/#using-an-explicit-encoding","title":"Using an explicit encoding","text":"<p>In some cases we might be making requests to a site where no character set information is being set explicitly by the server, but we know what the encoding is. In this case it's best to set the default encoding explicitly on the client.</p> <pre><code>import httpx\n# Instantiate a client with a Japanese character set as the default encoding.\nclient = httpx.Client(default_encoding=\"shift-jis\")\n# Using the client...\nresponse = client.get(...)\nprint(response.encoding) # This will either print the charset given in\n # the Content-Type charset, or else \"shift-jis\".\nprint(response.text) # The text will either be decoded with the Content-Type\n # charset, or using \"shift-jis\".\n</code></pre>"},{"location":"advanced/text-encodings/#using-auto-detection","title":"Using auto-detection","text":"<p>In cases where the server is not reliably including character set information, and where we don't know what encoding is being used, we can enable auto-detection to make a best-guess attempt when decoding from bytes to text.</p> <p>To use auto-detection you need to set the <code>default_encoding</code> argument to a callable instead of a string. This callable should be a function which takes the input bytes as an argument and returns the character set to use for decoding those bytes to text.</p> <p>There are two widely used Python packages which both handle this functionality:</p> <ul> <li><code>chardet</code> - This is a well established package, and is a port of the auto-detection code in Mozilla.</li> <li><code>charset-normalizer</code> - A newer package, motivated by <code>chardet</code>, with a different approach.</li> </ul> <p>Let's take a look at installing autodetection using one of these packages...</p> <pre><code>$ pip install httpx\n$ pip install chardet\n</code></pre> <p>Once <code>chardet</code> is installed, we can configure a client to use character-set autodetection.</p> <pre><code>import httpx\nimport chardet\n\ndef autodetect(content):\n return chardet.detect(content).get(\"encoding\")\n\n# Using a client with character-set autodetection enabled.\nclient = httpx.Client(default_encoding=autodetect)\nresponse = client.get(...)\nprint(response.encoding) # This will either print the charset given in\n # the Content-Type charset, or else the auto-detected\n # character set.\nprint(response.text)\n</code></pre>"},{"location":"advanced/timeouts/","title":"Timeouts","text":"<p>HTTPX is careful to enforce timeouts everywhere by default.</p> <p>The default behavior is to raise a <code>TimeoutException</code> after 5 seconds of network inactivity.</p>"},{"location":"advanced/timeouts/#setting-and-disabling-timeouts","title":"Setting and disabling timeouts","text":"<p>You can set timeouts for an individual request:</p> <pre><code># Using the top-level API:\nhttpx.get('http://example.com/api/v1/example', timeout=10.0)\n\n# Using a client instance:\nwith httpx.Client() as client:\n client.get(\"http://example.com/api/v1/example\", timeout=10.0)\n</code></pre> <p>Or disable timeouts for an individual request:</p> <pre><code># Using the top-level API:\nhttpx.get('http://example.com/api/v1/example', timeout=None)\n\n# Using a client instance:\nwith httpx.Client() as client:\n client.get(\"http://example.com/api/v1/example\", timeout=None)\n</code></pre>"},{"location":"advanced/timeouts/#setting-a-default-timeout-on-a-client","title":"Setting a default timeout on a client","text":"<p>You can set a timeout on a client instance, which results in the given <code>timeout</code> being used as the default for requests made with this client:</p> <pre><code>client = httpx.Client() # Use a default 5s timeout everywhere.\nclient = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.\nclient = httpx.Client(timeout=None) # Disable all timeouts by default.\n</code></pre>"},{"location":"advanced/timeouts/#fine-tuning-the-configuration","title":"Fine tuning the configuration","text":"<p>HTTPX also allows you to specify the timeout behavior in more fine grained detail.</p> <p>There are four different types of timeouts that may occur. These are connect, read, write, and pool timeouts.</p> <ul> <li>The connect timeout specifies the maximum amount of time to wait until a socket connection to the requested host is established. If HTTPX is unable to connect within this time frame, a <code>ConnectTimeout</code> exception is raised.</li> <li>The read timeout specifies the maximum duration to wait for a chunk of data to be received (for example, a chunk of the response body). If HTTPX is unable to receive data within this time frame, a <code>ReadTimeout</code> exception is raised.</li> <li>The write timeout specifies the maximum duration to wait for a chunk of data to be sent (for example, a chunk of the request body). If HTTPX is unable to send data within this time frame, a <code>WriteTimeout</code> exception is raised.</li> <li>The pool timeout specifies the maximum duration to wait for acquiring a connection from the connection pool. If HTTPX is unable to acquire a connection within this time frame, a <code>PoolTimeout</code> exception is raised. A related configuration here is the maximum number of allowable connections in the connection pool, which is configured by the <code>limits</code> argument.</li> </ul> <p>You can configure the timeout behavior for any of these values...</p> <pre><code># A client with a 60s timeout for connecting, and a 10s timeout elsewhere.\ntimeout = httpx.Timeout(10.0, connect=60.0)\nclient = httpx.Client(timeout=timeout)\n\nresponse = client.get('http://example.com/')\n</code></pre>"},{"location":"advanced/transports/","title":"Transports","text":"<p>HTTPX's <code>Client</code> also accepts a <code>transport</code> argument. This argument allows you to provide a custom Transport object that will be used to perform the actual sending of the requests.</p>"},{"location":"advanced/transports/#http-transport","title":"HTTP Transport","text":"<p>For some advanced configuration you might need to instantiate a transport class directly, and pass it to the client instance. One example is the <code>local_address</code> configuration which is only available via this low-level API.</p> <pre><code>>>> import httpx\n>>> transport = httpx.HTTPTransport(local_address=\"0.0.0.0\")\n>>> client = httpx.Client(transport=transport)\n</code></pre> <p>Connection retries are also available via this interface. Requests will be retried the given number of times in case an <code>httpx.ConnectError</code> or an <code>httpx.ConnectTimeout</code> occurs, allowing smoother operation under flaky networks. If you need other forms of retry behaviors, such as handling read/write errors or reacting to <code>503 Service Unavailable</code>, consider general-purpose tools such as tenacity.</p> <pre><code>>>> import httpx\n>>> transport = httpx.HTTPTransport(retries=1)\n>>> client = httpx.Client(transport=transport)\n</code></pre> <p>Similarly, instantiating a transport directly provides a <code>uds</code> option for connecting via a Unix Domain Socket that is only available via this low-level API:</p> <pre><code>>>> import httpx\n>>> # Connect to the Docker API via a Unix Socket.\n>>> transport = httpx.HTTPTransport(uds=\"/var/run/docker.sock\")\n>>> client = httpx.Client(transport=transport)\n>>> response = client.get(\"http://docker/info\")\n>>> response.json()\n{\"ID\": \"...\", \"Containers\": 4, \"Images\": 74, ...}\n</code></pre>"},{"location":"advanced/transports/#wsgi-transport","title":"WSGI Transport","text":"<p>You can configure an <code>httpx</code> client to call directly into a Python web application using the WSGI protocol.</p> <p>This is particularly useful for two main use-cases:</p> <ul> <li>Using <code>httpx</code> as a client inside test cases.</li> <li>Mocking out external services during tests or in dev or staging environments.</li> </ul>"},{"location":"advanced/transports/#example","title":"Example","text":"<p>Here's an example of integrating against a Flask application:</p> <pre><code>from flask import Flask\nimport httpx\n\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello World!\"\n\ntransport = httpx.WSGITransport(app=app)\nwith httpx.Client(transport=transport, base_url=\"http://testserver\") as client:\n r = client.get(\"/\")\n assert r.status_code == 200\n assert r.text == \"Hello World!\"\n</code></pre>"},{"location":"advanced/transports/#configuration","title":"Configuration","text":"<p>For some more complex cases you might need to customize the WSGI transport. This allows you to:</p> <ul> <li>Inspect 500 error responses rather than raise exceptions by setting <code>raise_app_exceptions=False</code>.</li> <li>Mount the WSGI application at a subpath by setting <code>script_name</code> (WSGI).</li> <li>Use a given client address for requests by setting <code>remote_addr</code> (WSGI).</li> </ul> <p>For example:</p> <pre><code># Instantiate a client that makes WSGI requests with a client IP of \"1.2.3.4\".\ntransport = httpx.WSGITransport(app=app, remote_addr=\"1.2.3.4\")\nwith httpx.Client(transport=transport, base_url=\"http://testserver\") as client:\n ...\n</code></pre>"},{"location":"advanced/transports/#asgi-transport","title":"ASGI Transport","text":"<p>You can configure an <code>httpx</code> client to call directly into an async Python web application using the ASGI protocol.</p> <p>This is particularly useful for two main use-cases:</p> <ul> <li>Using <code>httpx</code> as a client inside test cases.</li> <li>Mocking out external services during tests or in dev or staging environments.</li> </ul>"},{"location":"advanced/transports/#example_1","title":"Example","text":"<p>Let's take this Starlette application as an example:</p> <pre><code>from starlette.applications import Starlette\nfrom starlette.responses import HTMLResponse\nfrom starlette.routing import Route\n\n\nasync def hello(request):\n return HTMLResponse(\"Hello World!\")\n\n\napp = Starlette(routes=[Route(\"/\", hello)])\n</code></pre> <p>We can make requests directly against the application, like so:</p> <pre><code>transport = httpx.ASGITransport(app=app)\n\nasync with httpx.AsyncClient(transport=transport, base_url=\"http://testserver\") as client:\n r = await client.get(\"/\")\n assert r.status_code == 200\n assert r.text == \"Hello World!\"\n</code></pre>"},{"location":"advanced/transports/#configuration_1","title":"Configuration","text":"<p>For some more complex cases you might need to customise the ASGI transport. This allows you to:</p> <ul> <li>Inspect 500 error responses rather than raise exceptions by setting <code>raise_app_exceptions=False</code>.</li> <li>Mount the ASGI application at a subpath by setting <code>root_path</code>.</li> <li>Use a given client address for requests by setting <code>client</code>.</li> </ul> <p>For example:</p> <pre><code># Instantiate a client that makes ASGI requests with a client IP of \"1.2.3.4\",\n# on port 123.\ntransport = httpx.ASGITransport(app=app, client=(\"1.2.3.4\", 123))\nasync with httpx.AsyncClient(transport=transport, base_url=\"http://testserver\") as client:\n ...\n</code></pre> <p>See the ASGI documentation for more details on the <code>client</code> and <code>root_path</code> keys.</p>"},{"location":"advanced/transports/#asgi-startup-and-shutdown","title":"ASGI startup and shutdown","text":"<p>It is not in the scope of HTTPX to trigger ASGI lifespan events of your app.</p> <p>However it is suggested to use <code>LifespanManager</code> from asgi-lifespan in pair with <code>AsyncClient</code>.</p>"},{"location":"advanced/transports/#custom-transports","title":"Custom transports","text":"<p>A transport instance must implement the low-level Transport API which deals with sending a single request, and returning a response. You should either subclass <code>httpx.BaseTransport</code> to implement a transport to use with <code>Client</code>, or subclass <code>httpx.AsyncBaseTransport</code> to implement a transport to use with <code>AsyncClient</code>.</p> <p>At the layer of the transport API we're using the familiar <code>Request</code> and <code>Response</code> models.</p> <p>See the <code>handle_request</code> and <code>handle_async_request</code> docstrings for more details on the specifics of the Transport API.</p> <p>A complete example of a custom transport implementation would be:</p> <pre><code>import json\nimport httpx\n\nclass HelloWorldTransport(httpx.BaseTransport):\n \"\"\"\n A mock transport that always returns a JSON \"Hello, world!\" response.\n \"\"\"\n\n def handle_request(self, request):\n return httpx.Response(200, json={\"text\": \"Hello, world!\"})\n</code></pre> <p>Or this example, which uses a custom transport and <code>httpx.Mounts</code> to always redirect <code>http://</code> requests.</p> <pre><code>class HTTPSRedirect(httpx.BaseTransport):\n \"\"\"\n A transport that always redirects to HTTPS.\n \"\"\"\n def handle_request(self, request):\n url = request.url.copy_with(scheme=\"https\")\n return httpx.Response(303, headers={\"Location\": str(url)})\n\n# A client where any `http` requests are always redirected to `https`\ntransport = httpx.Mounts({\n 'http://': HTTPSRedirect()\n 'https://': httpx.HTTPTransport()\n})\nclient = httpx.Client(transport=transport)\n</code></pre> <p>A useful pattern here is custom transport classes that wrap the default HTTP implementation. For example...</p> <pre><code>class DebuggingTransport(httpx.BaseTransport):\n def __init__(self, **kwargs):\n self._wrapper = httpx.HTTPTransport(**kwargs)\n\n def handle_request(self, request):\n print(f\">>> {request}\")\n response = self._wrapper.handle_request(request)\n print(f\"<<< {response}\")\n return response\n\n def close(self):\n self._wrapper.close()\n\ntransport = DebuggingTransport()\nclient = httpx.Client(transport=transport)\n</code></pre> <p>Here's another case, where we're using a round-robin across a number of different proxies...</p> <pre><code>class ProxyRoundRobin(httpx.BaseTransport):\n def __init__(self, proxies, **kwargs):\n self._transports = [\n httpx.HTTPTransport(proxy=proxy, **kwargs)\n for proxy in proxies\n ]\n self._idx = 0\n\n def handle_request(self, request):\n transport = self._transports[self._idx]\n self._idx = (self._idx + 1) % len(self._transports)\n return transport.handle_request(request)\n\n def close(self):\n for transport in self._transports:\n transport.close()\n\nproxies = [\n httpx.Proxy(\"http://127.0.0.1:8081\"),\n httpx.Proxy(\"http://127.0.0.1:8082\"),\n httpx.Proxy(\"http://127.0.0.1:8083\"),\n]\ntransport = ProxyRoundRobin(proxies=proxies)\nclient = httpx.Client(transport=transport)\n</code></pre>"},{"location":"advanced/transports/#mock-transports","title":"Mock transports","text":"<p>During testing it can often be useful to be able to mock out a transport, and return pre-determined responses, rather than making actual network requests.</p> <p>The <code>httpx.MockTransport</code> class accepts a handler function, which can be used to map requests onto pre-determined responses:</p> <pre><code>def handler(request):\n return httpx.Response(200, json={\"text\": \"Hello, world!\"})\n\n\n# Switch to a mock transport, if the TESTING environment variable is set.\nif os.environ.get('TESTING', '').upper() == \"TRUE\":\n transport = httpx.MockTransport(handler)\nelse:\n transport = httpx.HTTPTransport()\n\nclient = httpx.Client(transport=transport)\n</code></pre> <p>For more advanced use-cases you might want to take a look at either the third-party mocking library, RESPX, or the pytest-httpx library.</p>"},{"location":"advanced/transports/#mounting-transports","title":"Mounting transports","text":"<p>You can also mount transports against given schemes or domains, to control which transport an outgoing request should be routed via, with the same style used for specifying proxy routing.</p> <pre><code>import httpx\n\nclass HTTPSRedirectTransport(httpx.BaseTransport):\n \"\"\"\n A transport that always redirects to HTTPS.\n \"\"\"\n\n def handle_request(self, method, url, headers, stream, extensions):\n scheme, host, port, path = url\n if port is None:\n location = b\"https://%s%s\" % (host, path)\n else:\n location = b\"https://%s:%d%s\" % (host, port, path)\n stream = httpx.ByteStream(b\"\")\n headers = [(b\"location\", location)]\n extensions = {}\n return 303, headers, stream, extensions\n\n\n# A client where any `http` requests are always redirected to `https`\nmounts = {'http://': HTTPSRedirectTransport()}\nclient = httpx.Client(mounts=mounts)\n</code></pre> <p>A couple of other sketches of how you might take advantage of mounted transports...</p> <p>Disabling HTTP/2 on a single given domain...</p> <pre><code>mounts = {\n \"all://\": httpx.HTTPTransport(http2=True),\n \"all://*example.org\": httpx.HTTPTransport()\n}\nclient = httpx.Client(mounts=mounts)\n</code></pre> <p>Mocking requests to a given domain:</p> <pre><code># All requests to \"example.org\" should be mocked out.\n# Other requests occur as usual.\ndef handler(request):\n return httpx.Response(200, json={\"text\": \"Hello, World!\"})\n\nmounts = {\"all://example.org\": httpx.MockTransport(handler)}\nclient = httpx.Client(mounts=mounts)\n</code></pre> <p>Adding support for custom schemes:</p> <pre><code># Support URLs like \"file:///Users/sylvia_green/websites/new_client/index.html\"\nmounts = {\"file://\": FileSystemTransport()}\nclient = httpx.Client(mounts=mounts)\n</code></pre>"},{"location":"advanced/transports/#routing","title":"Routing","text":"<p>HTTPX provides a powerful mechanism for routing requests, allowing you to write complex rules that specify which transport should be used for each request.</p> <p>The <code>mounts</code> dictionary maps URL patterns to HTTP transports. HTTPX matches requested URLs against URL patterns to decide which transport should be used, if any. Matching is done from most specific URL patterns (e.g. <code>https://<domain>:<port></code>) to least specific ones (e.g. <code>https://</code>).</p> <p>HTTPX supports routing requests based on scheme, domain, port, or a combination of these.</p>"},{"location":"advanced/transports/#wildcard-routing","title":"Wildcard routing","text":"<p>Route everything through a transport...</p> <pre><code>mounts = {\n \"all://\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre>"},{"location":"advanced/transports/#scheme-routing","title":"Scheme routing","text":"<p>Route HTTP requests through one transport, and HTTPS requests through another...</p> <pre><code>mounts = {\n \"http://\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n \"https://\": httpx.HTTPTransport(proxy=\"http://localhost:8031\"),\n}\n</code></pre>"},{"location":"advanced/transports/#domain-routing","title":"Domain routing","text":"<p>Proxy all requests on domain \"example.com\", let other requests pass through...</p> <pre><code>mounts = {\n \"all://example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre> <p>Proxy HTTP requests on domain \"example.com\", let HTTPS and other requests pass through...</p> <pre><code>mounts = {\n \"http://example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre> <p>Proxy all requests to \"example.com\" and its subdomains, let other requests pass through...</p> <pre><code>mounts = {\n \"all://*example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre> <p>Proxy all requests to strict subdomains of \"example.com\", let \"example.com\" and other requests pass through...</p> <pre><code>mounts = {\n \"all://*.example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre>"},{"location":"advanced/transports/#port-routing","title":"Port routing","text":"<p>Proxy HTTPS requests on port 1234 to \"example.com\"...</p> <pre><code>mounts = {\n \"https://example.com:1234\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre> <p>Proxy all requests on port 1234...</p> <pre><code>mounts = {\n \"all://*:1234\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n}\n</code></pre>"},{"location":"advanced/transports/#no-proxy-support","title":"No-proxy support","text":"<p>It is also possible to define requests that shouldn't be routed through the transport.</p> <p>To do so, pass <code>None</code> as the proxy URL. For example...</p> <pre><code>mounts = {\n # Route requests through a proxy by default...\n \"all://\": httpx.HTTPTransport(proxy=\"http://localhost:8031\"),\n # Except those for \"example.com\".\n \"all://example.com\": None,\n}\n</code></pre>"},{"location":"advanced/transports/#complex-configuration-example","title":"Complex configuration example","text":"<p>You can combine the routing features outlined above to build complex proxy routing configurations. For example...</p> <pre><code>mounts = {\n # Route all traffic through a proxy by default...\n \"all://\": httpx.HTTPTransport(proxy=\"http://localhost:8030\"),\n # But don't use proxies for HTTPS requests to \"domain.io\"...\n \"https://domain.io\": None,\n # And use another proxy for requests to \"example.com\" and its subdomains...\n \"all://*example.com\": httpx.HTTPTransport(proxy=\"http://localhost:8031\"),\n # And yet another proxy if HTTP is used,\n # and the \"internal\" subdomain on port 5550 is requested...\n \"http://internal.example.com:5550\": httpx.HTTPTransport(proxy=\"http://localhost:8032\"),\n}\n</code></pre>"},{"location":"advanced/transports/#environment-variables","title":"Environment variables","text":"<p>There are also environment variables that can be used to control the dictionary of the client mounts. They can be used to configure HTTP proxying for clients.</p> <p>See documentation on <code>HTTP_PROXY</code>, <code>HTTPS_PROXY</code>, <code>ALL_PROXY</code> and <code>NO_PROXY</code> for more information.</p>"}]}
\ No newline at end of file
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://www.python-httpx.org/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/api/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/async/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/code_of_conduct/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/compatibility/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/contributing/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/environment_variables/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/exceptions/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/http2/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/logging/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/quickstart/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/third_party_packages/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/troubleshooting/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/authentication/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/clients/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/event-hooks/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/extensions/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/proxies/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/resource-limits/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/ssl/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/text-encodings/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/timeouts/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
<url>
<loc>https://www.python-httpx.org/advanced/transports/</loc>
- <lastmod>2024-12-06</lastmod>
+ <lastmod>2025-09-11</lastmod>
</url>
</urlset>
\ No newline at end of file
<ul class="md-nav__list">
<li class="md-nav__item">
- <a href="#httpx-ws" class="md-nav__link">
+ <a href="#hishel" class="md-nav__link">
<span class="md-ellipsis">
- httpx-ws
+ Hishel
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#httpx-socks" class="md-nav__link">
+ <a href="#httpx-auth" class="md-nav__link">
<span class="md-ellipsis">
- httpx-socks
+ HTTPX-Auth
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#hishel" class="md-nav__link">
+ <a href="#httpx-caching" class="md-nav__link">
<span class="md-ellipsis">
- Hishel
+ httpx-caching
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#authlib" class="md-nav__link">
+ <a href="#httpx-secure" class="md-nav__link">
<span class="md-ellipsis">
- Authlib
+ httpx-secure
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#gidgethub" class="md-nav__link">
+ <a href="#httpx-socks" class="md-nav__link">
<span class="md-ellipsis">
- Gidgethub
+ httpx-socks
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#httpx-auth" class="md-nav__link">
+ <a href="#httpx-sse" class="md-nav__link">
<span class="md-ellipsis">
- HTTPX-Auth
+ httpx-sse
+ </span>
+ </a>
+
+</li>
+
+ <li class="md-nav__item">
+ <a href="#httpx-retries" class="md-nav__link">
+ <span class="md-ellipsis">
+ httpx-retries
+ </span>
+ </a>
+
+</li>
+
+ <li class="md-nav__item">
+ <a href="#httpx-ws" class="md-nav__link">
+ <span class="md-ellipsis">
+ httpx-ws
</span>
</a>
</li>
+ </ul>
+ </nav>
+
+</li>
+
+ <li class="md-nav__item">
+ <a href="#libraries-with-httpx-support" class="md-nav__link">
+ <span class="md-ellipsis">
+ Libraries with HTTPX support
+ </span>
+ </a>
+
+ <nav class="md-nav" aria-label="Libraries with HTTPX support">
+ <ul class="md-nav__list">
+
<li class="md-nav__item">
- <a href="#vcrpy" class="md-nav__link">
+ <a href="#authlib" class="md-nav__link">
<span class="md-ellipsis">
- VCR.py
+ Authlib
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#httpx-caching" class="md-nav__link">
+ <a href="#gidgethub" class="md-nav__link">
<span class="md-ellipsis">
- httpx-caching
+ Gidgethub
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#httpx-sse" class="md-nav__link">
+ <a href="#httpdbg" class="md-nav__link">
<span class="md-ellipsis">
- httpx-sse
+ httpdbg
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#robox" class="md-nav__link">
+ <a href="#vcrpy" class="md-nav__link">
<span class="md-ellipsis">
- robox
+ VCR.py
</span>
</a>
<ul class="md-nav__list">
<li class="md-nav__item">
- <a href="#httpx-ws" class="md-nav__link">
+ <a href="#hishel" class="md-nav__link">
<span class="md-ellipsis">
- httpx-ws
+ Hishel
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#httpx-socks" class="md-nav__link">
+ <a href="#httpx-auth" class="md-nav__link">
<span class="md-ellipsis">
- httpx-socks
+ HTTPX-Auth
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#hishel" class="md-nav__link">
+ <a href="#httpx-caching" class="md-nav__link">
<span class="md-ellipsis">
- Hishel
+ httpx-caching
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#authlib" class="md-nav__link">
+ <a href="#httpx-secure" class="md-nav__link">
<span class="md-ellipsis">
- Authlib
+ httpx-secure
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#gidgethub" class="md-nav__link">
+ <a href="#httpx-socks" class="md-nav__link">
<span class="md-ellipsis">
- Gidgethub
+ httpx-socks
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#httpx-auth" class="md-nav__link">
+ <a href="#httpx-sse" class="md-nav__link">
<span class="md-ellipsis">
- HTTPX-Auth
+ httpx-sse
+ </span>
+ </a>
+
+</li>
+
+ <li class="md-nav__item">
+ <a href="#httpx-retries" class="md-nav__link">
+ <span class="md-ellipsis">
+ httpx-retries
+ </span>
+ </a>
+
+</li>
+
+ <li class="md-nav__item">
+ <a href="#httpx-ws" class="md-nav__link">
+ <span class="md-ellipsis">
+ httpx-ws
</span>
</a>
</li>
+ </ul>
+ </nav>
+
+</li>
+
+ <li class="md-nav__item">
+ <a href="#libraries-with-httpx-support" class="md-nav__link">
+ <span class="md-ellipsis">
+ Libraries with HTTPX support
+ </span>
+ </a>
+
+ <nav class="md-nav" aria-label="Libraries with HTTPX support">
+ <ul class="md-nav__list">
+
<li class="md-nav__item">
- <a href="#vcrpy" class="md-nav__link">
+ <a href="#authlib" class="md-nav__link">
<span class="md-ellipsis">
- VCR.py
+ Authlib
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#httpx-caching" class="md-nav__link">
+ <a href="#gidgethub" class="md-nav__link">
<span class="md-ellipsis">
- httpx-caching
+ Gidgethub
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#httpx-sse" class="md-nav__link">
+ <a href="#httpdbg" class="md-nav__link">
<span class="md-ellipsis">
- httpx-sse
+ httpdbg
</span>
</a>
</li>
<li class="md-nav__item">
- <a href="#robox" class="md-nav__link">
+ <a href="#vcrpy" class="md-nav__link">
<span class="md-ellipsis">
- robox
+ VCR.py
</span>
</a>
<h1 id="third-party-packages">Third Party Packages</h1>
<p>As HTTPX usage grows, there is an expanding community of developers building tools and libraries that integrate with HTTPX, or depend on HTTPX. Here are some of them.</p>
+<!-- NOTE: Entries are alphabetised. -->
+
<h2 id="plugins">Plugins</h2>
-<h3 id="httpx-ws">httpx-ws</h3>
-<p><a href="https://github.com/frankie567/httpx-ws">GitHub</a> - <a href="https://frankie567.github.io/httpx-ws/">Documentation</a></p>
-<p>WebSocket support for HTTPX.</p>
-<h3 id="httpx-socks">httpx-socks</h3>
-<p><a href="https://github.com/romis2012/httpx-socks">GitHub</a></p>
-<p>Proxy (HTTP, SOCKS) transports for httpx.</p>
<h3 id="hishel">Hishel</h3>
<p><a href="https://github.com/karpetrosyan/hishel">GitHub</a> - <a href="https://hishel.com/">Documentation</a></p>
<p>An elegant HTTP Cache implementation for HTTPX and HTTP Core.</p>
-<h3 id="authlib">Authlib</h3>
-<p><a href="https://github.com/lepture/authlib">GitHub</a> - <a href="https://docs.authlib.org/en/latest/">Documentation</a></p>
-<p>The ultimate Python library in building OAuth and OpenID Connect clients and servers. Includes an <a href="https://docs.authlib.org/en/latest/client/httpx.html">OAuth HTTPX client</a>.</p>
-<h3 id="gidgethub">Gidgethub</h3>
-<p><a href="https://github.com/brettcannon/gidgethub">GitHub</a> - <a href="https://gidgethub.readthedocs.io/en/latest/index.html">Documentation</a></p>
-<p>An asynchronous GitHub API library. Includes <a href="https://gidgethub.readthedocs.io/en/latest/httpx.html">HTTPX support</a>.</p>
<h3 id="httpx-auth">HTTPX-Auth</h3>
<p><a href="https://github.com/Colin-b/httpx_auth">GitHub</a> - <a href="https://colin-b.github.io/httpx_auth/">Documentation</a></p>
-<p>Provides authentication classes to be used with HTTPX <a href="../advanced/authentication/#customizing-authentication">authentication parameter</a>.</p>
+<p>Provides authentication classes to be used with HTTPX's <a href="../advanced/authentication/#customizing-authentication">authentication parameter</a>.</p>
+<h3 id="httpx-caching">httpx-caching</h3>
+<p><a href="https://github.com/johtso/httpx-caching">Github</a></p>
+<p>This package adds caching functionality to HTTPX</p>
+<h3 id="httpx-secure">httpx-secure</h3>
+<p><a href="https://github.com/Zaczero/httpx-secure">GitHub</a></p>
+<p>Drop-in SSRF protection for httpx with DNS caching and custom validation support.</p>
+<h3 id="httpx-socks">httpx-socks</h3>
+<p><a href="https://github.com/romis2012/httpx-socks">GitHub</a></p>
+<p>Proxy (HTTP, SOCKS) transports for httpx.</p>
+<h3 id="httpx-sse">httpx-sse</h3>
+<p><a href="https://github.com/florimondmanca/httpx-sse">GitHub</a></p>
+<p>Allows consuming Server-Sent Events (SSE) with HTTPX.</p>
+<h3 id="httpx-retries">httpx-retries</h3>
+<p><a href="https://github.com/will-ockmore/httpx-retries">GitHub</a> - <a href="https://will-ockmore.github.io/httpx-retries/">Documentation</a></p>
+<p>A retry layer for HTTPX.</p>
+<h3 id="httpx-ws">httpx-ws</h3>
+<p><a href="https://github.com/frankie567/httpx-ws">GitHub</a> - <a href="https://frankie567.github.io/httpx-ws/">Documentation</a></p>
+<p>WebSocket support for HTTPX.</p>
<h3 id="pytest-httpx">pytest-HTTPX</h3>
<p><a href="https://github.com/Colin-b/pytest_httpx">GitHub</a> - <a href="https://colin-b.github.io/pytest_httpx/">Documentation</a></p>
-<p>Provides <code>httpx_mock</code> <a href="https://docs.pytest.org/en/latest/">pytest</a> fixture to mock HTTPX within test cases.</p>
+<p>Provides a <a href="https://docs.pytest.org/en/latest/">pytest</a> fixture to mock HTTPX within test cases.</p>
<h3 id="respx">RESPX</h3>
<p><a href="https://github.com/lundberg/respx">GitHub</a> - <a href="https://lundberg.github.io/respx/">Documentation</a></p>
-<p>A utility for mocking out the Python HTTPX library.</p>
+<p>A utility for mocking out HTTPX.</p>
<h3 id="rpcpy">rpc.py</h3>
<p><a href="https://github.com/abersheeran/rpc.py">Github</a> - <a href="https://github.com/abersheeran/rpc.py#rpcpy">Documentation</a></p>
-<p>An fast and powerful RPC framework based on ASGI/WSGI. Use HTTPX as the client of the RPC service.</p>
+<p>A fast and powerful RPC framework based on ASGI/WSGI. Use HTTPX as the client of the RPC service.</p>
+<h2 id="libraries-with-httpx-support">Libraries with HTTPX support</h2>
+<h3 id="authlib">Authlib</h3>
+<p><a href="https://github.com/lepture/authlib">GitHub</a> - <a href="https://docs.authlib.org/en/latest/">Documentation</a></p>
+<p>A python library for building OAuth and OpenID Connect clients and servers. Includes an <a href="https://docs.authlib.org/en/latest/client/httpx.html">OAuth HTTPX client</a>.</p>
+<h3 id="gidgethub">Gidgethub</h3>
+<p><a href="https://github.com/brettcannon/gidgethub">GitHub</a> - <a href="https://gidgethub.readthedocs.io/en/latest/index.html">Documentation</a></p>
+<p>An asynchronous GitHub API library. Includes <a href="https://gidgethub.readthedocs.io/en/latest/httpx.html">HTTPX support</a>.</p>
+<h3 id="httpdbg">httpdbg</h3>
+<p><a href="https://github.com/cle-b/httpdbg">GitHub</a> - <a href="https://httpdbg.readthedocs.io/">Documentation</a></p>
+<p>A tool for python developers to easily debug the HTTP(S) client requests in a python program.</p>
<h3 id="vcrpy">VCR.py</h3>
<p><a href="https://github.com/kevin1024/vcrpy">GitHub</a> - <a href="https://vcrpy.readthedocs.io/">Documentation</a></p>
-<p>A utility for record and repeat an http request.</p>
-<h3 id="httpx-caching">httpx-caching</h3>
-<p><a href="https://github.com/johtso/httpx-caching">Github</a></p>
-<p>This package adds caching functionality to HTTPX</p>
-<h3 id="httpx-sse">httpx-sse</h3>
-<p><a href="https://github.com/florimondmanca/httpx-sse">GitHub</a></p>
-<p>Allows consuming Server-Sent Events (SSE) with HTTPX.</p>
-<h3 id="robox">robox</h3>
-<p><a href="https://github.com/danclaudiupop/robox">Github</a></p>
-<p>A library for scraping the web built on top of HTTPX.</p>
+<p>Record and repeat requests.</p>
<h2 id="gists">Gists</h2>
-<!-- NOTE: this list is in alphabetical order. -->
-
<h3 id="urllib3-transport">urllib3-transport</h3>
<p><a href="https://gist.github.com/florimondmanca/d56764d78d748eb9f73165da388e546e">GitHub</a></p>
<p>This public gist provides an example implementation for a <a href="../advanced/transports/#custom-transports">custom transport</a> implementation on top of the battle-tested <a href="https://urllib3.readthedocs.io"><code>urllib3</code></a> library.</p>