title: how do you properly reuse an httpx.AsyncClient wihtin a FastAPI application?
body: <p>I have a FastAPI application which, in several different occasions, needs to call external APIs. I use httpx.AsyncClient for these calls. The point is that I don't fully understand how I shoud use it.</p>
  <p>From <a href="https://www.python-httpx.org/async/" rel="nofollow noreferrer">httpx' documentation</a> I should use context managers,</p>
  <pre><code>async def foo():
      &quot;&quot;&quot;&quot;
      I need to call foo quite often from different 
      parts of my application
      &quot;&quot;&quot;
      async with httpx.AsyncClient() as aclient:
          # make some http requests, e.g.,
          await aclient.get(&quot;http://example.it&quot;)
  </code></pre>
  <p>However, I understand that in this way a new client is spawned each time I call <code>foo()</code>, and is precisely what we want to avoid by using a client in the first place.</p>
  <p>I suppose an alternative would be to have some global client defined somewhere, and just import it whenever I need it like so</p>
  <pre><code>aclient = httpx.AsyncClient()
  
  async def bar():
      # make some http requests using the global aclient, e.g.,
      await aclient.get(&quot;http://example.it&quot;)
  </code></pre>
  <p>This second option looks somewhat fishy, though, as nobody is taking care of closing the session and the like.</p>
  <p>So the question is: how do I properly (re)use <code>httpx.AsyncClient()</code> within a FastAPI application?</p>