How to Add Custom Claims to a JWT in Python with PyJWT
PyJWT takes your custom claims as part of the dictionary you pass to jwt.encode: {"name": "Ada", "roles": ["editor"]}. Each key becomes a claim, with any value JSON can hold, and jwt.decode gives them back in a dictionary once it has checked the token.
Syntax
payload = {
"<name>": <value>,
}
token = jwt.encode(payload, <key>, algorithm="<alg>")
claims = jwt.decode(token, <key>, algorithms=["<alg>"])
claims["<name>"]
| Part | What it does |
|---|---|
"<name>" | The claim's name, a string. Any text works, a URL included. |
<value> | Any value JSON can hold: a str, an int or a float, True or False, None, a list or a dict. |
<key> | The signing key, here 32 bytes for HS256. |
<alg> | The signing algorithm, here HS256. |
claims | The verified claims, as a dictionary: yours and the registered ones. |
The PyJWT documentation for jwt.encode describes the payload as "JWT claims, e.g. dict(iss=..., aud=..., sub=...)", and says it raises a TypeError "if payload is not a dict".
The Example
The example signs a token for a user named Ada with three custom claims of three JSON types: name, a string; roles, a list; and https://photos.example.org/quota, a dictionary with an album limit and a storage limit. The last one has a URL as its name, so that no other service's claim can have the same name. Then the example verifies the token and reads one value back.
Prerequisites
- uv and Python. This guide uses uv 0.13.10 with Python 3.15.2.
Step 1: Create the Project
uv init --no-package demo
cd demo
uv add pyjwt
uv init --no-package demo makes a project folder named demo, and uv add pyjwt installs PyJWT, version 2.15.1 here.
Step 2: Write the Code
Replace the contents of main.py:

import base64
from datetime import datetime, timedelta, timezone
import jwt
# The signing key: 32 random bytes, written as base64.
# It's in the code only for this example; a real app loads it from its configuration.
key = base64.b64decode("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=")
payload = {
"sub": "ada",
"exp": datetime.now(tz=timezone.utc) + timedelta(hours=1),
"name": "Ada", # a string
"roles": ["editor", "viewer"], # a list
"https://photos.example.org/quota": {"albums": 10, "storage_gb": 50}, # a dictionary
}
token = jwt.encode(payload, key, algorithm="HS256")
print(token)
claims = jwt.decode(token, key, algorithms=["HS256"])
print(claims)
print(claims["https://photos.example.org/quota"]["albums"])
- The dictionary
payloadholds the claims.subandexpare registered claims, andname,rolesand the quota are custom ones. The comments name each one's type. expis adatetime. PyJWT turns adatetimeinexp,iatornbfinto a Unix time, but not in your own claims.jwt.decode(token, key, algorithms=["HS256"])checks the signature and the expiry, then returns the claims.claims["https://photos.example.org/quota"]["albums"]reads a value inside the dictionary claim.
Step 3: Run It
uv run main.py
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZGEiLCJleHAiOjE3OTYyOTE2MzEsIm5hbWUiOiJBZGEiLCJyb2xlcyI6WyJlZGl0b3IiLCJ2aWV3ZXIiXSwiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmcvcXVvdGEiOnsiYWxidW1zIjoxMCwic3RvcmFnZV9nYiI6NTB9fQ.CPPieTw6e0YVDeuTiWXqS6-eQ1CEiIlrksePw_-jdtY
{'sub': 'ada', 'exp': 1796291631, 'name': 'Ada', 'roles': ['editor', 'viewer'], 'https://photos.example.org/quota': {'albums': 10, 'storage_gb': 50}}
10

The command is the same in zsh, bash and PowerShell.
What Happened
- The claims came back with the same names and types.
rolesis a list and the quota a dictionary, not text. expcame back as a number, the Unix time one hour after the token was made.- The last line read
10from inside the dictionary claim, after the token was verified.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
A datetime in your own claim, such as "joined" | TypeError: Object of type datetime is not JSON serializable. PyJWT converts only exp, iat and nbf | Convert it to a Unix time: int(joined.timestamp()) |
A set as a value | TypeError: Object of type set is not JSON serializable | Use a list, such as sorted(roles) |
| A tuple as a value | It comes back as a list | Expect a list when you read it |
| A dictionary with numbers as keys | The keys come back as strings: {1: "a"} becomes {'1': 'a'} | Use strings as keys |
float("nan") or float("inf") as a value | PyJWT writes NaN or Infinity, which isn't JSON, and other services' libraries reject the token. See Fixed: "JWT Claims Set must be a top-level JSON object" in jose for a PyJWT Token | Send None for "no value" |
Reading a claim with claims["roles"] when some tokens don't have it | KeyError: 'roles' | claims.get("roles"), which gives None |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
TypeError: Expecting a dict object, as JWT only supports JSON objects as payloads. | A list, a string or another value that isn't a dictionary was passed to jwt.encode | Pass a dictionary |
TypeError: Object of type … is not JSON serializable | A claim holds a value JSON can't hold | Turn it into a string, a number, a list or a dictionary first |
KeyError when reading a claim | The token doesn't have that claim | Use .get(), or require the claim when decoding |
FAQ
Can a custom claim hold a list or a dictionary?
Yes. A claim's value can be any JSON value, and PyJWT writes it with Python's json module. Lists and dictionaries come back as they were.
Why does one claim have a URL as its name?
Short names like quota can collide with another service's claim of the same name. The JWT standard, RFC 7519, says a new claim name should either be registered with IANA or be collision-resistant, and it names domain names as one way to make it so. A URL on a domain you control is such a name.
Does PyJWT check my custom claims?
Only whether they're there, and only when you ask. jwt.decode(token, key, algorithms=["HS256"], options={"require": ["roles"]}) stops a token without roles with jwt.exceptions.MissingRequiredClaimError: Token is missing the "roles" claim. The PyJWT documentation for this require option says it "Only verifies that the claims exists. Does not verify that the claims are valid." Checking that roles is a list is up to your code.
Conclusion
Put your claims in the dictionary you pass to jwt.encode, and read them from what jwt.decode returns. Keep values to what JSON can hold, give claims that other services may see a URL name, and check each one's type before your code relies on it.
Additional Resources
- jwt.encode and jwt.decode, in the PyJWT documentation.
- RFC 7519 section 4, on registered, public and private claim names.
