Last modified: Jun 14, 2026

Install NATS.py Client in Python

NATS is a fast and lightweight messaging system. It helps different services talk to each other. The NATS.py client lets you use NATS in Python. This guide shows you how to install it easily.

What Is NATS?

NATS stands for NATS Messaging System. It works like a post office for your apps. You send messages to a subject, and other apps receive them. It is simple, fast, and reliable.

Many companies use NATS for microservices. It handles millions of messages per second. NATS supports publish/subscribe, request/reply, and queue groups.

Why Use NATS.py?

The NATS.py client is the official Python library. It works with Python 3.7 and newer. You get full access to NATS features. It supports async operations with asyncio. This makes it perfect for modern Python apps.

NATS.py is well-maintained. It has clear documentation. The community is active and helpful.

Prerequisites

Before you install NATS.py, check these things:

  • Python 3.7 or newer installed on your system.
  • pip package manager available.
  • A working internet connection.
  • Basic Python knowledge.

Open your terminal or command prompt. Run this command to check your Python version:


python --version

You should see something like Python 3.10.12. If not, download Python from python.org.

Step 1: Create a Virtual Environment

Always use a virtual environment. It keeps your project dependencies separate. This avoids conflicts with other projects.

Navigate to your project folder. Then run:


python -m venv nats_env

This creates a folder called nats_env. Activate the environment:

  • Windows:nats_env\Scripts\activate
  • macOS/Linux:source nats_env/bin/activate

You will see (nats_env) in your terminal prompt. This means the environment is active.

Step 2: Install NATS.py with pip

Now install the NATS.py client. Use the pip install command:


pip install nats-py

This downloads and installs the library. It also installs dependencies like asyncio and msgpack. Wait for the process to finish.

You can verify the installation:


pip show nats-py

You will see details like version and location. The current version is usually 2.x or newer.

Step 3: Test Your Installation

Create a simple test script. Open a new file called test_nats.py. Add this code:


# test_nats.py
import asyncio
from nats.aio.client import Client as NATS

async def main():
    # Connect to a NATS server
    nc = NATS()
    await nc.connect("nats://demo.nats.io:4222")
    print("Connected to NATS server!")
    
    # Publish a simple message
    await nc.publish("hello.world", b"Hello from NATS.py!")
    print("Message published.")
    
    # Close the connection
    await nc.close()

if __name__ == "__main__":
    asyncio.run(main())

Run the script:


python test_nats.py

You should see this output:


Connected to NATS server!
Message published.

This confirms NATS.py works. You connected to a public demo server. You published a message to the subject hello.world.

Step 4: Understand the Code

The code uses asyncio for async operations. The connect method connects to a NATS server. The publish method sends a message. The message must be bytes, so we use b"...".

The nats://demo.nats.io:4222 is a public server. You can use it for testing. For production, run your own NATS server.

Step 5: Run a NATS Server Locally

For real projects, run a local NATS server. Download the NATS server from nats.io. Extract the binary and run it:


./nats-server

This starts a server on localhost:4222. Now update your script:


# Connect to local server
await nc.connect("nats://localhost:4222")

Run the script again. It will connect to your local server.

Step 6: Subscribe to Messages

Now let's subscribe to messages. Create a new file called subscribe.py:


# subscribe.py
import asyncio
from nats.aio.client import Client as NATS

async def main():
    nc = NATS()
    await nc.connect("nats://demo.nats.io:4222")
    print("Connected to NATS server")
    
    # Subscribe to a subject
    async def message_handler(msg):
        print(f"Received: {msg.subject} - {msg.data.decode()}")
    
    await nc.subscribe("hello.world", cb=message_handler)
    print("Subscribed to hello.world")
    
    # Keep the connection alive
    await asyncio.sleep(10)
    await nc.close()

if __name__ == "__main__":
    asyncio.run(main())

Run this script in one terminal. Open another terminal and run the publisher script again. You will see the subscriber receive the message.

Output in subscriber terminal:


Connected to NATS server
Subscribed to hello.world
Received: hello.world - Hello from NATS.py!

Step 7: Handle Connection Errors

Sometimes connections fail. Use try/except blocks:


# error_handling.py
import asyncio
from nats.aio.client import Client as NATS
from nats.errors import TimeoutError

async def main():
    nc = NATS()
    try:
        await nc.connect("nats://localhost:4222", timeout=5)
        print("Connected successfully")
    except TimeoutError:
        print("Connection timed out. Check if NATS server is running.")
    except Exception as e:
        print(f"Connection failed: {e}")
    finally:
        await nc.close()

if __name__ == "__main__":
    asyncio.run(main())

Always handle errors. This makes your code robust.

Step 8: Upgrade or Uninstall

To upgrade NATS.py to the latest version:


pip install --upgrade nats-py

To uninstall it:


pip uninstall nats-py

This removes the library from your environment.

Best Practices

Follow these tips for clean code:

  • Always use virtual environments.
  • Use async/await properly.
  • Close connections when done.
  • Handle exceptions gracefully.
  • Use environment variables for server URLs.

Conclusion

Installing NATS.py in Python is simple. Use pip install nats-py in a virtual environment. Test with a basic publish/subscribe example. Handle errors and close connections. You now have a fast messaging system for your Python apps. Start building distributed systems today!