Typing stubs for PyJWT (jwt package)

0.1.3 · active · verified Thu Apr 16

This library provides PEP 561 type stubs for the popular `PyJWT` library, which is commonly imported as `jwt`. It enables static type checkers like MyPy, PyCharm, and Pyright to analyze code that uses `PyJWT`. `types-jwt` is part of the `typeshed` project, which centrally manages type definitions for many third-party Python packages. `types-jwt` version 0.1.3 was released in May 2021. However, it's important to note that since `PyJWT` version 2.0.0 (released December 2020) and later include their own inline type annotations, `types-jwt` is primarily relevant for projects using older versions of `PyJWT` (pre-2.0.0) or specific legacy setups.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to encode and decode a JSON Web Token using the `PyJWT` library, for which `types-jwt` provides type annotations. The example includes setting an expiration time and handling basic decoding errors. Ensure you have `PyJWT` installed for this code to run. While `types-jwt` itself is not directly imported, its presence allows type checkers to provide richer feedback on `jwt` module usage. For production, always use robust, securely generated secret keys and appropriate algorithms.

import jwt
import os
from datetime import datetime, timedelta, timezone
from typing import Dict, Any # These types are enhanced by types-jwt if PyJWT < 2.0

# Note: This quickstart uses PyJWT (the runtime library)
# types-jwt provides type hints for this code during static analysis.

# Replace with a strong, secret key in a real application
secret_key: bytes = os.environ.get('JWT_SECRET_KEY', 'your-super-secret-key').encode('utf-8')
algorithm: str = "HS256"

# 1. Encode a JWT
payload: Dict[str, Any] = {
    "user_id": 123,
    "username": "testuser",
    "exp": datetime.now(timezone.utc) + timedelta(hours=1), # Token expires in 1 hour
    "iat": datetime.now(timezone.utc) # Issued at time
}

try:
    encoded_jwt: str = jwt.encode(payload, secret_key, algorithm=algorithm)
    print(f"Encoded JWT: {encoded_jwt}")

    # 2. Decode the JWT
    decoded_payload: Dict[str, Any] = jwt.decode(
        encoded_jwt, secret_key, algorithms=[algorithm]
    )
    print(f"Decoded Payload: {decoded_payload}")

except jwt.ExpiredSignatureError:
    print("Token has expired!")
except jwt.InvalidTokenError as e:
    print(f"Invalid token: {e}")

view raw JSON →