Last modified: Oct 19, 2026

Install pika in Python

pika is the official Python client for RabbitMQ. It implements the AMQP 0-9-1 protocol and lets your applications send and receive messages reliably.

This guide walks you through installation, connection setup, publishing, consuming, and troubleshooting. It is written for beginners who want a clean and working setup.

Every section includes practical code and clear explanations. You can follow along step by step.

Prerequisites

You need Python 3.7 or newer and a running RabbitMQ server. A local RabbitMQ instance works well for learning.

Check your Python version before you start.

python --version
python3 --version

You also need network access to the RabbitMQ broker. The default AMQP port is 5672, and the management UI usually runs on 15672.

Set Up a Virtual Environment

Always isolate project dependencies. A virtual environment keeps packages separate and avoids version conflicts.

# Create a virtual environment
python -m venv pika-env

# Activate on Linux or macOS
source pika-env/bin/activate

# Activate on Windows
pika-env\Scripts\activate

Your prompt should change after activation. Confirm the interpreter path with which python or where python.

Install pika with pip

Install the package inside your active environment. The command is simple and fast.

pip install --upgrade pika

The --upgrade flag ensures you get the latest stable release. This matters because pika maintains compatibility with recent RabbitMQ versions.

Pin the version in your dependency file for reproducible deployments.

pip freeze | grep pika >> requirements.txt

If you plan to monitor message processing failures, you can also install sentry-sdk in Python and capture exceptions automatically.

Understand pika Basics

pika uses a small set of core objects. A connection represents a TCP session with RabbitMQ.

A channel is a lightweight logical connection inside a connection. Most AMQP operations happen on a channel.

Queues store messages. Exchanges route messages to queues based on routing rules.

Producers publish messages to exchanges. Consumers subscribe to queues and receive messages.

Start with a simple queue and default exchange. That keeps the first example easy to follow.

Connect to RabbitMQ

The pika.BlockingConnection class opens a synchronous connection. Use it for simple scripts and background workers.

Pass connection parameters with the host, port, and credentials.

import pika

# Connect to a local RabbitMQ broker
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host="localhost", port=5672)
)

# Open a channel for AMQP operations
channel = connection.channel()

print("Connected to RabbitMQ.")
connection.close()
Connected to RabbitMQ.

Always close the connection when done. A context manager does this automatically and is the safest pattern.

Publish a Message

Publishing a message requires a queue and a routing key. The default exchange routes by queue name.

Use channel.queue_declare to create the queue. It is idempotent, so calling it repeatedly is safe.

Then publish with channel.basic_publish. Include the exchange, routing key, and body.

import pika

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

# Declare a durable queue
channel.queue_declare(queue="tasks", durable=True)

# Publish a message to the default exchange
channel.basic_publish(
    exchange="",
    routing_key="tasks",
    body="Hello from pika",
    properties=pika.BasicProperties(delivery_mode=2),  # persistent message
)

print("Message published.")
connection.close()
Message published.

Set delivery_mode=2 to make messages persistent. This protects messages if RabbitMQ restarts.

Always declare the queue before publishing. A missing queue causes messages to be silently dropped.

Consume Messages

Consuming messages uses a callback function. pika calls it for each delivered message.

Use channel.basic_consume to register the callback and queue. Then call channel.start_consuming to block and process messages.

import pika

def on_message(channel, method, properties, body):
    print(f"Received: {body.decode()}")
    # Acknowledge the message after successful processing
    channel.basic_ack(delivery_tag=method.delivery_tag)

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

channel.queue_declare(queue="tasks", durable=True)
channel.basic_consume(queue="tasks", on_message_callback=on_message)

print("Waiting for messages. To exit press CTRL+C")
channel.start_consuming()
Waiting for messages. To exit press CTRL+C
Received: Hello from pika

The channel.basic_ack method confirms successful processing. Without an acknowledgement, RabbitMQ will redeliver the message.

Only acknowledge after the work is complete. A crash before acknowledgement causes a safe redelivery.

Handle Errors Gracefully

Network failures and broker restarts happen. Your consumer must handle them without losing data.

Wrap the connection and consumption loop in a try block. Catch pika.exceptions.AMQPConnectionError and retry with a delay.

import time
import pika
from pika.exceptions import AMQPConnectionError

def consume_forever():
    while True:
        try:
            connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
            channel = connection.channel()
            channel.queue_declare(queue="tasks", durable=True)
            channel.basic_consume(
                queue="tasks",
                on_message_callback=on_message,
                auto_ack=False,
            )
            channel.start_consuming()
        except AMQPConnectionError:
            print("Connection lost. Retrying in 5 seconds.")
            time.sleep(5)
Connection lost. Retrying in 5 seconds.

Log failures with context. This makes it easier to diagnose broker issues and consumer bugs.

If you test message throughput, you can write Locust tasks in Python to simulate many producers and consumers under load.

Troubleshoot Common Installation Errors

Most installation problems are easy to fix. The error messages usually point to the cause.

ModuleNotFoundError: No module named 'pika'

This error means the package is not installed in your active environment. Activate your virtual environment and install it again.

source pika-env/bin/activate
pip install pika

Connection refused

This error means the client cannot reach RabbitMQ. Check that the broker is running and that the host and port are correct.

If RabbitMQ runs in Docker, confirm the port mapping. Port 5672 must be exposed to the host.

ACCESS_REFUSED - Login was refused

This error means the credentials are wrong or the user lacks permissions. The default guest user only works from localhost.

Create a dedicated user and grant permissions on the virtual host.

rabbitmqctl add_user myuser mypassword
rabbitmqctl set_permissions -p / myuser ".*" ".*" ".*"

ConnectionResetError on long-running consumers

This usually means a heartbeat timeout. Increase the heartbeat interval or fix blocking work in your callback.

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host="localhost", heartbeat=60)
)

Best Practices for a Clean Setup

Use durable queues and persistent messages for important work. This prevents data loss during broker restarts.

Set auto_ack=False and acknowledge after processing. Automatic acknowledgement can lose messages on failure.

Keep callbacks short. Offload heavy work to a worker queue or background thread.

Reuse a single connection per process. Creating a connection for every message is expensive.

Pin the pika version in your dependency file. AMQP behavior is stable, but reproducibility still matters.

If your consumer also writes to a database, you may want to install mysqlclient in Python to connect to MySQL from the same worker.

Monitor consumer lag and connection errors. A quiet queue can hide a broken consumer.

Test message handling before deploying to production. A simple local RabbitMQ instance catches most issues early.

Conclusion

Installing pika in Python is quick. Create a virtual environment, install the package with pip, and connect to RabbitMQ.

Use pika.BlockingConnection for a connection and a channel for operations. Publish with channel.basic_publish and consume with channel.basic_consume.

Handle errors with retries and acknowledge messages only after successful processing.

With these patterns, your Python applications can exchange messages reliably and safely using RabbitMQ.