title: How to use pika with FastAPI's asyncio loop?
body: <p>I am trying to create a webhook endpoint with FastAPI, and write any json request body that arrives there to RabbitMQ.</p>
  <p>I cannot figure out how to connect to RabbitMQ, create the channel, and keep it all alive by being hooked into the FastAPI asyncio loop. None of the other questions or answers here on SO are helping.</p>
  <p>My current 'solution' is to start a 2nd thread in a FastAPI app startup method, and use a queue.SimpleQueue to talk between the threads. So the FastAPI path method writes the object to this SimpleQueue and the 2nd thread reads the object from it and publishes it to RabbitMQ.</p>
  <p>The problem with this simple-minded approach is that because the 2nd thread is blocking on reading the SimpleQueue the RabbitMQ connection is not getting the keepalives sent over it and the server closes it. My code catches exceptions on write to RabbitMQ and reconnects and tries again but that's pretty ugly.</p>
  <p>I cannot understand how to adapt the async examples in either pika or aio-pika map to a FastAPI app.</p>
  <p>Is anyone able to show me how, given the trivial FastAPI app below, I can open a RabbitMQ connection that will have the necessary keepalives sent over it to keep it open, such that I can publish via the connection in the path method?</p>
  <pre><code>from fastapi import FastAPI, Response
  from typing import Any, Dict
  
  app = FastAPI()
  
  @app.on_event(&quot;startup&quot;)
  async def startup() -&gt; None:
      # Connect to RabbitMQ
      # Create channel
      # Declare queue
  
  JSONObject = Dict[str, Any]
  
  @app.post(&quot;/webhook&quot;)
  async def webhook_endpoint(msg: JSONObject):
  
      # Write msg to RabbitMQ channel here.
  
      return Response(status_code=204)
  </code></pre>
  <p>My other idea was to still use a thread but have the thread perform a blocking read on the RabbitMQ connection in the hope that will keep sending keepalives over it, and that it won't interfere with publishing over the same connection from the path method. But that is obviously a hack. I'd prefer to do it the 'proper' way and use async code.</p>
  <p>EDIT: There does not seem to be a way to do a blocking read, so and endless loop with channel.basic_get() and sleep instead. Even more hacky.</p>