# Python MQTT libraries

Python MQTT libraries connect devices and services to an MQTT broker to publish and subscribe to messages on topics. A client either runs its own network loop in a thread or exposes the connection through asyncio. These libraries let IoT devices, home automation systems, and backend services exchange sensor data and commands.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [paho-mqtt](#paho-mqtt) | 11.6M | 2.4K | Nov 2026 | EPL-2.0 OR BSD-3-Clause |
| [aiomqtt](#aiomqtt) | 1.6M | 581 | Mar 2026 | BSD-3-Clause |
| [awsiotsdk](#awsiotsdk) | 1.0M | 447 | Jul 2026 | Apache-2.0 |
| [gmqtt](#gmqtt) | 189.3K | 454 | Nov 2026 | MIT |
| [aMQTT](#amqtt) | 92.8K | 222 | Nov 2026 | MIT |
| [AWSIoTPythonSDK](#awsiotpythonsdk) | 45.1K | 688 | Oct 2026 | Apache-2.0 |
| [mqttools](#mqttools) | 3.3K | 66 | Dec 2021 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[paho-mqtt](#paho-mqtt) has the most monthly downloads in this comparison, at 11.6M.

## Capabilities

| Library | MQTT version five | Embedded broker | QoS level two |
| --- | --- | --- | --- |
| [paho-mqtt](#paho-mqtt) | Yes | No | Yes |
| [aiomqtt](#aiomqtt) | Yes | No | Yes |
| [awsiotsdk](#awsiotsdk) | Yes | No | No |
| [gmqtt](#gmqtt) | Yes | No | Yes |
| [aMQTT](#amqtt) | No | Yes | Yes |
| [AWSIoTPythonSDK](#awsiotpythonsdk) | No | No | No |
| [mqttools](#mqttools) | Yes | Yes | No |

## Libraries

### paho-mqtt

[GitHub](https://github.com/eclipse-paho/paho.mqtt.python) · [PyPI](https://pypi.org/project/paho-mqtt) · [Docs](https://eclipse.dev/paho/files/paho.mqtt.python/html/index.html)

Connects Python applications to MQTT brokers through callback-based publish and subscription APIs.

- Downloads / mo: 11.6M
- Stars: 2.4K
- Last release: 2.2.0
- License: EPL-2.0 OR BSD-3-Clause
- Capabilities: [From the paho-mqtt docs](https://eclipse.dev/paho/files/paho.mqtt.python/html/index.html)

**Strengths**

- **Supports several MQTT protocol generations.** Connect to brokers using the newer or older supported protocol versions.
- **Offers several network-loop integrations.** Choose blocking, threaded, or external-event-loop integration for the application.

**Watch out for**

- **Persistent sessions remain in memory.** With clean_session=False, recreating the client loses its saved session state.
- **Accepted publishes can remain pending.** Wait for completion before treating an accepted publish as sent.

```sh
python -m pip install paho-mqtt
```

**blakeblackshear/frigate** (37.6K stars)

[blakeblackshear/frigate](https://github.com/blakeblackshear/frigate) 

```python
def _create_client(self) -> mqtt.Client:
    """Build a fresh paho client for a single connect attempt."""
    client = mqtt.Client(
        callback_api_version=CallbackAPIVersion.VERSION2,
        client_id=self.mqtt_config.client_id,
        reconnect_on_failure=False,
    )
    client.on_connect = self._on_connect
    client.on_disconnect = self._on_disconnect
    client.on_message = self._on_message
    client.on_subscribe = self._on_subscribe
    client.on_publish = self._on_publish
    client.will_set(
        self.mqtt_config.topic_prefix + "/available",
        payload="offline",
        qos=1,
        retain=True,
    )

    if self.mqtt_config.tls_ca_certs is not None:
        if (
            self.mqtt_config.tls_client_cert is not None
            and self.mqtt_config.tls_client_key is not None
        ):
            client.tls_set(
                self.mqtt_config.tls_ca_certs,
                self.mqtt_config.tls_client_cert,
                self.mqtt_config.tls_client_key,
            )
        else:
            client.tls_set(self.mqtt_config.tls_ca_certs)

    if self.mqtt_config.tls_insecure is not None:
        client.tls_insecure_set(self.mqtt_config.tls_insecure)

    if self.mqtt_config.user is not None:
        client.username_pw_set(
            self.mqtt_config.user,
            password=self.mqtt_config.password,
        )

    return client
```

[frigate/comms/mqtt.py](https://github.com/blakeblackshear/frigate/blob/ec5f6d4f7fcfb3e9ab45ec63026cf0cf0dc1a7db/frigate/comms/mqtt.py#L276-L317) · [More projects using paho-mqtt →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20paho-mqtt%20for%20client%20setup%2C%20meter-state%20publication%20and%20subscription-handler%20registration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import paho.mqtt.publish as publish
publish.single('paho/test/topic', 'hello', hostname='localhost')

```

From [README.rst](https://pypi.org/pypi/paho-mqtt/2.2.0/json#info.description)

### aiomqtt

[GitHub](https://github.com/empicano/aiomqtt) · [PyPI](https://pypi.org/project/aiomqtt) · [Docs](https://aiomqtt.bo3hm.com)

Wraps stable Paho clients with awaitable MQTT operations and asynchronous context management.

- Downloads / mo: 1.6M
- Stars: 581
- Last release: 2.5.1
- License: BSD-3-Clause
- Capabilities: [From the aiomqtt docs](https://aiomqtt.bo3hm.com)

**Strengths**

- **Awaits publishing and subscriptions.** Use async context management and consume messages through asynchronous iteration.
- **Raises exceptions for MQTT failures.** Handle MQTT failures through MqttError in the application.

**Watch out for**

- **Reconnection needs an application loop.** Catch MqttError and re-enter the client context after a suitable delay.
- **Windows needs selector event loops.** Use an event loop that supports add_reader on Windows.

```sh
python -m pip install aiomqtt
```

**allangood/rtlamr2mqtt** (649 stars)

[allangood/rtlamr2mqtt](https://github.com/allangood/rtlamr2mqtt) 

```python
async def publish_reading(self, client, reading: dict):
    """
    Publish a meter reading: status, state, and attributes.
    """
    meter_id = reading['meter_id']
    meter_config = self.meters.get(meter_id, {})
    consumption = reading['consumption']

    # Format the reading if format is configured
    fmt = meter_config.get('format')
    if fmt:
        formatted = ro.format_number(consumption, fmt)
    else:
        formatted = consumption

    # Publish online status
    await self.publish_status(client, 'online')

    # Publish state
    timestamp = datetime.now().astimezone().replace(microsecond=0).isoformat()
    payload = {'reading': formatted, 'lastseen': timestamp}
    await client.publish(
        topic=f'{self.base_topic}/{meter_id}/state',
        payload=dumps(payload),
        qos=1,
        retain=False,
    )

    # Publish attributes
    attributes = dict(reading['message'])
    attributes['protocol'] = meter_config.get('protocol', 'unknown')
    await client.publish(
        topic=f'{self.base_topic}/{meter_id}/attributes',
        payload=dumps(attributes),
        qos=1,
        retain=False,
    )

    logger.info('Published reading for meter %s: %s', meter_id, formatted)
```

[rtlamr2mqtt-addon/app/mqtt_publisher.py](https://github.com/allangood/rtlamr2mqtt/blob/53ef59d4eaede836252c8e5b49673ec7e63366ef/rtlamr2mqtt-addon/app/mqtt_publisher.py#L190-L228) · [More projects using aiomqtt →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20aiomqtt%20for%20client%20setup%2C%20meter-state%20publication%20and%20subscription-handler%20registration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import asyncio
import aiomqtt
async def main():
    async with aiomqtt.Client('localhost') as client:
        await client.publish('temperature/outside', payload=28.4)
asyncio.run(main())

```

From [reconnection.html](https://pypi.org/pypi/aiomqtt/2.5.1/json#info.description)

### awsiotsdk

[GitHub](https://github.com/aws/aws-iot-device-sdk-python-v2) · [PyPI](https://pypi.org/project/awsiotsdk) · [Docs](https://pypi.org/project/awsiotsdk/)

Connects to AWS IoT through the AWS Common Runtime.

- Downloads / mo: 1.0M
- Stars: 447
- Last release: 1.31.0
- License: Apache-2.0
- Capabilities: [From the awsiotsdk docs](https://pypi.org/project/awsiotsdk/)

```sh
python -m pip install awsiotsdk
```

**Quickstart**

```python
from awsiot import mqtt_connection_builder
connection = mqtt_connection_builder.mtls_from_path(
    endpoint='YOUR_ENDPOINT', client_id='example',
    cert_filepath='device.pem.crt', pri_key_filepath='private.pem.key',
)
connection.connect().result()
connection.disconnect().result()

```

From [mqtt_connection_builder.py](https://aws.github.io/aws-iot-device-sdk-python-v2/awsiot/mqtt_connection_builder.html) · [Find projects using awsiotsdk →](https://dashboard.exa.ai/playground/search?q=awsiotsdk%20GitHub%20projects)

### gmqtt

[GitHub](https://github.com/wialon/gmqtt) · [PyPI](https://pypi.org/project/gmqtt) · [Docs](https://pypi.org/project/gmqtt/)

Provides an asyncio MQTT client with configurable reconnect behavior and protocol properties.

- Downloads / mo: 189.3K
- Stars: 454
- Last release: 0.10.0
- License: MIT
- Capabilities: [From the gmqtt docs](https://pypi.org/project/gmqtt/)

**Strengths**

- **Connects through native asyncio.** Await connection and disconnection while retaining MQTT event callbacks.
- **Configures reconnect attempts and delays.** Set retry limits and backoff settings for lost connections.

**Watch out for**

- **Reconnect attempts are unlimited initially.** Set reconnect_retries when a disconnected client should eventually stop trying.
- **Older brokers can reject negotiation.** Force the older protocol when a broker cannot parse the initial connection.

```sh
python -m pip install gmqtt
```

**sabuhish/fastapi-mqtt** (387 stars)

[sabuhish/fastapi-mqtt](https://github.com/sabuhish/fastapi-mqtt) 

```python
def subscribe(
    self,
    *topics,
    qos: int = 0,
    no_local: bool = False,
    retain_as_published: bool = False,
    retain_handling_options: int = 0,
    subscription_identifier: Any = None,
) -> Callable[..., Any]:
    """
    Decorator method used to subscribe for specific topics.

    Topics are subscribed on every (re)connection. If the client is already
    connected when the decorator runs, they are also subscribed right away.

    Handlers get (client, topic, payload, qos, properties). If a handler has a
    parameter typed as a pydantic model, the payload is parsed into that model instead,
    and the other parameters are passed by name:

        @mqtt.subscribe("sensors/+/temperature")
        async def temperature(item: Temperature, topic: str): ...
    """

    def subscribe_handler(handler: MQTTMessageHandler) -> MQTTMessageHandler:
        self._logger.debug("Subscribe for topics: %s", topics)
        message_handler = self._message_handler(handler)
        for topic in topics:
            if topic not in self.subscriptions:
                subscription = Subscription(
                    topic,
                    qos,
                    no_local,
                    retain_as_published,
                    retain_handling_options,
                    subscription_identifier,
                )
                self.subscriptions[topic] = (subscription, [message_handler])
            else:
                # Use the most restrictive field of the same subscription
                old_subscription, handlers = self.subscriptions[topic]
                subscription = Subscription(
                    topic,
                    max(qos, old_subscription.qos),
                    no_local or old_subscription.no_local,
                    retain_as_published or old_subscription.retain_as_published,
                    max(
                        retain_handling_options,
                        old_subscription.retain_handling_options,
                    ),
                    old_subscription.subscription_identifier or subscription_identifier,
                )
                handlers.append(message_handler)
                self.subscriptions[topic] = (subscription, handlers)

            if self.client.is_connected:
                self._logger.debug("Already connected, subscribing for %s", topic)
                self.client.subscribe(subscription)
        return handler

    return subscribe_handler
```

[fastapi_mqtt/fastmqtt.py](https://github.com/sabuhish/fastapi-mqtt/blob/055a2e4464ff2faeea26197ed84119a12aba7820/fastapi_mqtt/fastmqtt.py#L322-L381) · [More projects using gmqtt →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20gmqtt%20for%20client%20setup%2C%20meter-state%20publication%20and%20subscription-handler%20registration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import asyncio
from gmqtt import Client
async def main():
    client = Client('example')
    await client.connect('localhost')
    client.publish('example/topic', 'hello', qos=0)
    await client.disconnect()
asyncio.run(main())

```

From [README.md](https://pypi.org/pypi/gmqtt/0.10.0/json#info.description)

### aMQTT

[GitHub](https://github.com/Yakifo/amqtt) · [PyPI](https://pypi.org/project/amqtt) · [Docs](https://pypi.org/project/amqtt/)

Provides both an MQTT broker and a client implemented with Python asyncio.

- Downloads / mo: 92.8K
- Stars: 222
- Last release: 0.12.2
- License: MIT
- Capabilities: [From the aMQTT docs](https://pypi.org/project/amqtt/)

**Strengths**

- **Embeds a Python MQTT broker.** Run a broker and client within an asyncio-based application.
- **Supports encrypted MQTT transports.** Use TLS-protected TCP or secure WebSocket connections.

**Watch out for**

- **Default broker allows anonymous clients.** Replace the default anonymous plugin when the broker must authenticate its clients.

```sh
python -m pip install amqtt
```

**Quickstart**

```python
import asyncio
from amqtt.client import MQTTClient
async def main():
    client = MQTTClient()
    await client.connect('mqtt://localhost/')
    await client.publish('example/topic', b'hello', qos=0)
    await client.disconnect()
asyncio.run(main())

```

From [client_publish.py](https://amqtt.readthedocs.io/en/latest/references/client/) · [Find projects using aMQTT →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20amqtt%20for%20client%20setup%2C%20meter-state%20publication%20and%20subscription-handler%20registration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

### AWSIoTPythonSDK

[GitHub](https://github.com/aws/aws-iot-device-sdk-python) · [PyPI](https://pypi.org/project/AWSIoTPythonSDK) · [Docs](https://pypi.org/project/AWSIoTPythonSDK/)

Connects Python applications to AWS IoT.

- Downloads / mo: 45.1K
- Stars: 688
- Last release: 1.6.2
- License: Apache-2.0
- Capabilities: [From the AWSIoTPythonSDK docs](https://pypi.org/project/AWSIoTPythonSDK/)

```sh
python -m pip install AWSIoTPythonSDK
```

**aws-iot-builder-tools/iot-reference-architectures** (108 stars)

[aws-iot-builder-tools/iot-reference-architectures](https://github.com/aws-iot-builder-tools/iot-reference-architectures) 

```python
def setup():
    root_ca_file = "root-ca.pem"

    # Get the CA cert if we need it
    if not path.exists(root_ca_file):
        request = requests.get('https://www.amazontrust.com/repository/AmazonRootCA1.pem', allow_redirects=True)
        open(root_ca_file, 'wb').write(request.content)

    # Get the hostname for the customer's ATS endpoint in this region
    iot_client = boto3.client('iot')
    iot_data = iot_client.describe_endpoint(endpointType='iot:Data-ATS')
    host = iot_data['endpointAddress']

    # Get temporary credentials
    sts_client = boto3.client('sts')
    sts_data = sts_client.get_session_token()

    # Extract the temporary credential values
    credentials = sts_data['Credentials']
    access_key_id = credentials['AccessKeyId']
    secret_access_key = credentials['SecretAccessKey']
    session_token = credentials['SessionToken']

    # Create an MQTT client with a random client ID that uses WebSockets
    mqtt_client = AWSIoTMQTTClient(str(uuid.uuid4()), useWebsocket=True)
    # Use port 443 + ALPN on the customer's ATS endpoint
    mqtt_client.configureEndpoint(host, 443)
    # Explicitly enable the root CA we downloaded
    mqtt_client.configureCredentials(root_ca_file)

    # Configure the library to use the specified credentials instead of using another provider to fetch them
    AWSIoTMQTTClient.configureIAMCredentials(mqtt_client, access_key_id, secret_access_key, session_token)

    return mqtt_client
```

[tools/simple-pub-sub/shared.py](https://github.com/aws-iot-builder-tools/iot-reference-architectures/blob/559d50b6f4d63bf1eb8be474f5cf3bc3a75ab273/tools/simple-pub-sub/shared.py#L17-L50) · [More projects using AWSIoTPythonSDK →](https://dashboard.exa.ai/playground/search?q=AWSIoTPythonSDK%20GitHub%20projects)

**Quickstart**

```python
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
client = AWSIoTMQTTClient('example')
client.configureEndpoint('YOUR_ENDPOINT', 8883)
client.configureCredentials('root-ca.pem', 'private.pem.key', 'device.pem.crt')
client.connect()
client.disconnect()

```

From [index.html](https://s3.amazonaws.com/aws-iot-device-sdk-python-docs/html/index.html)

### mqttools

[GitHub](https://github.com/eerimoq/mqttools) · [PyPI](https://pypi.org/project/mqttools) · [Docs](https://pypi.org/project/mqttools/)

Provides MQTT tools.

- Downloads / mo: 3.3K
- Stars: 66
- Last release: 0.50.0
- License: MIT
- Capabilities: [From the mqttools docs](https://pypi.org/project/mqttools/)

```sh
python -m pip install mqttools
```

**Quickstart**

```python
import asyncio
import mqttools
async def publisher():
    async with mqttools.Client('localhost', 1883) as client:
        client.publish(mqttools.Message('/test/mqttools/foo', b'bar'))
asyncio.run(publisher())

```

From [README.md](https://pypi.org/pypi/mqttools/0.50.0/json#info.description) · [Find projects using mqttools →](https://dashboard.exa.ai/playground/search?q=mqttools%20GitHub%20projects)

## FAQ

### Which Python MQTT library should I use?

[paho-mqtt](#paho-mqtt) suits most clients, with callbacks and threaded, blocking, or external network loops. [aiomqtt](#aiomqtt) suits asyncio applications. [awsiotsdk](#awsiotsdk) suits devices that connect to AWS IoT.

### What is Paho MQTT?

[paho-mqtt](#paho-mqtt) is an MQTT client class with callbacks and a choice of threaded, blocking, or external network loops. It stores session state only in memory.

### What is aiomqtt?

[aiomqtt](#aiomqtt) is an asyncio MQTT client built on Paho MQTT. It opens connections as async context managers and delivers incoming messages through its messages property.

### Can Python run an MQTT broker?

[aMQTT](#amqtt) includes an asyncio broker with configurable listeners and plugins for authentication and authorization.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python MQTT libraries Paho aiomqtt gmqtt aMQTT publish subscribe code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
