Last modified: Mar 28, 2025 By Alexander Williams

How to Install PyJWT in Python

PyJWT is a library for encoding and decoding JSON Web Tokens (JWT) in Python. It is widely used for authentication and data exchange.

This guide will walk you through installing PyJWT step by step. You will also learn basic usage and troubleshooting tips.

Prerequisites

Before installing PyJWT, ensure you have Python installed. You can check this by running:


python --version

If Python is not installed, download it from the official website. PyJWT works with Python 3.6 and above.

Install PyJWT Using pip

The easiest way to install PyJWT is using pip, Python's package manager. Open your terminal or command prompt.

Run the following command:


pip install PyJWT

This will download and install the latest version of PyJWT. Wait for the installation to complete.

Verify Installation

To ensure PyJWT is installed correctly, run a simple check. Open a Python shell by typing python in your terminal.

Then, try importing PyJWT:


import jwt
print("PyJWT installed successfully!")

If no errors appear, PyJWT is ready to use. If you see ModuleNotFoundError, check our guide on how to solve ModuleNotFoundError.

Basic Usage of PyJWT

PyJWT allows you to encode and decode JWTs. Here is a simple example:


import jwt

# Create a payload (data to encode)
payload = {"user_id": 123, "username": "john_doe"}

# Secret key for encoding and decoding
secret = "your_secret_key"

# Encode the payload into a JWT
token = jwt.encode(payload, secret, algorithm="HS256")
print("Encoded Token:", token)

# Decode the JWT back to the payload
decoded_payload = jwt.decode(token, secret, algorithms=["HS256"])
print("Decoded Payload:", decoded_payload)

This code encodes a payload into a JWT and decodes it back. Always keep your secret key secure.

Common Errors and Solutions

Sometimes, you may encounter errors while using PyJWT. Here are common issues and fixes.

1. Invalid Token Error: Ensure the token is correctly formatted and the secret key matches.

2. Expired Token Error: JWTs can have expiration times. Check if the token is still valid.

3. Algorithm Mismatch: Use the same algorithm for encoding and decoding.

Conclusion

Installing PyJWT in Python is simple with pip. This guide covered installation, basic usage, and troubleshooting.

Now you can start using PyJWT for secure authentication and data exchange in your projects.