← All posts

Your First Journey into RabbitMQ with Python

Hello World with the Pika client: a minimal producer and consumer against RabbitMQ in Docker.

Webdev · Python · Learning

Hello World with Pika, the Python client for AMQP. You can choose any supported client for your stack.

Prerequisites

RabbitMQ is installed and running on localhost. The quickest way is the official Docker image with the management UI:

docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.12-management

Pika client

pip install pika --upgrade

Producer — sender.py

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
channel = connection.channel()

# Connects to a broker on the local machine (localhost).

# Declare the queue so it exists before we publish.
channel.queue_declare(queue="hello")

# With the default exchange (""), routing_key selects the queue name.
channel.basic_publish(exchange="", routing_key="hello", body="Hello World")

print("[x] Sent 'Hello World!'")

# Flush buffers and close cleanly so the message is delivered.
connection.close()

Consumer — receiver.py

import pika
import sys
import os


def main():
    connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
    channel = connection.channel()

    channel.queue_declare(queue="hello")

    def callback(ch, method, properties, body):
        print(f" [x] Received {body}")

    channel.basic_consume(queue="hello", on_message_callback=callback, auto_ack=True)

    print("[*] Waiting for messages. To exit press Ctrl+C")
    channel.start_consuming()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("Interrupted")
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

Running

  1. Start the consumer:

    python receiver.py
    
  2. In another terminal, run the producer:

    python sender.py
    

Output

From the consumer you should see something like:

[*] Waiting for messages. To exit press Ctrl+C
[x] Received b'Hello World!'

Reference

This follows the ideas from the official RabbitMQ tutorial — Hello World (Python).

Conclusion

That’s the first step into messaging with RabbitMQ and Python. From here you can explore exchanges, routing keys, acknowledgements, and durability.