This error means Python loads the wrong jwt module, so jwt.encode is missing until you fix the install or a name clash.
Why AttributeError: Module ‘JWT’ Has No Attribute ‘Encode’ Happens In Python
When you see AttributeError: module 'jwt' has no attribute 'encode', Python is telling you that the object named
jwt is not the PyJWT library you expect. The name exists, so the import line passes, but that object does not define
an encode attribute. The message looks scary, yet it usually comes down to a small mismatch between package names,
local files, or environment setup.
In most projects the goal is simple: call jwt.encode() from the PyJWT package to sign a payload, often in web apps
that issue login tokens or API keys. When another package named jwt sits in the same environment, or a local file
named jwt.py shadows the library, Python imports the wrong thing. Then the call to jwt.encode() fails,
and the full text of the error shows up as attributeerror: module ‘jwt’ has no attribute ‘encode’.
The same string can appear when a virtual environment pulls in different packages than the one you installed on your main
system. You might test code in an interactive shell where jwt.encode works, then run the script through a runner or
a task that uses another interpreter. The fix is still the same idea: make sure the name jwt points to the PyJWT
package you intend to use, and make that consistent across every environment that runs the project.
Fixing Jwt Encode On The Jwt Module Step By Step
Before you change code, it helps to follow a short, repeatable path that starts with the package you installed and ends with a
clean jwt.encode call. This path applies whether you build a small script, a Django view, or a Flask endpoint that
returns JSON web tokens.
- Confirm Pyjwt Is Installed — Run
pip show PyJWTorpip listinside the same
environment that runs your script and make sure the line forPyJWTappears. - Remove The Plain jwt Package — If you see a separate package named
jwt, uninstall it with
pip uninstall jwtso that only PyJWT remains under that name. - Reinstall Pyjwt Cleanly — Run
pip uninstall PyJWTfollowed by
pip install PyJWTin the same shell to refresh the install and clear old files. - Test In A Fresh Python Shell — Open
python, runimport jwt, then
dir(jwt)and confirm that'encode'is in the list of attributes. - Run Your Script Again — If the shell shows
encode, run your application script from that
same environment and confirm that theAttributeErrorno longer appears.
Many users trigger attributeerror: module ‘jwt’ has no attribute ‘encode’ by installing both the plain
jwt package and PyJWT. The plain package is older and does not expose the same interface. Removing that package and
reinstalling PyJWT often resolves the error in one pass.
Check For Conflicting Jwt Packages
PyJWT provides the jwt.encode function that most tutorials show. A different library on PyPI also uses the short
name jwt, and it exposes a different set of attributes. When both live in one environment, the package that loads
first under the name jwt wins. That package might not define encode, which leads straight to the error.
You can verify this by checking metadata for the installed packages. If the summary mentions JSON web tokens and PyJWT, you are
in the right place. If the summary describes some other feature and still uses the same short name, that package is not the one
you need for token signing in Python.
- List Installed Jwt Packages — Run
pip list | grep -i jwton Unix like systems or
pip listand scan the output on Windows to see every package that contains the stringjwt. - Uninstall The Plain jwt Package — Use
pip uninstall jwtuntil that package no longer
appears in the list, leaving PyJWT as the active provider for thejwtname. - Pin A Stable Pyjwt Version — When you manage dependencies with a requirements file, add a line such
asPyJWT==2.8.0so that every environment installs the same release instead of drifting over time.
Some frameworks also ship extra helpers such as djangorestframework-jwt or Flask-JWT. These packages
still rely on PyJWT under the hood. If you keep the core PyJWT install healthy, those helpers can call the same
jwt.encode function without extra work on your side.
Rename Local jwt.py Files That Shadow Pyjwt
A second common cause appears when a project file shares a name with the library. If your script file is called
jwt.py or token.py, Python might import that file instead of the PyJWT package. The import line
succeeds, because there is a file with that name, but the module object does not contain the methods you expect. The result is
again the message module 'jwt' has no attribute 'encode'.
This pattern often shows up during early experiments, where a quick script starts as jwt.py in a test folder. Later
you try to reuse that folder in a larger app, but the name collision remains. The fix is simple once you spot it: change the
file name so that imports point back to the real library.
- Search For jwt.py And token.py — In your project root, look for files named
jwt.py,
token.py, or similar names that might shadow the package. - Rename Local Files — Change those file names to something more specific, such as
auth_tokens.pyorjwt_helpers.py, and adjust imports inside your project. - Remove Stale .pyc Files — Delete any
__pycache__folders in the same directories so that
Python rebuilds bytecode for the renamed modules. - Import Jwt Again — Start a Python shell in the project root, run
import jwt, and check
jwt.__file__to confirm that the path now points to the site-packages directory for PyJWT.
Name clashes can feel confusing because the code that calls jwt.encode might live in a different file. Once a
shadow file sits on the import path, though, it affects every part of the project. Renaming that file clears the clash in a
single step and lets the interpreter find the intended package again.
Use Correct Jwt Encode And Decode Patterns
After you clean up your packages and file names, a short, direct test helps confirm that jwt.encode behaves as
expected. PyJWT uses a simple signature: you pass a payload dictionary, a secret or private key, and an algorithm name. The
return value is a token string; later you call jwt.decode with the same key and algorithm to parse it.
import jwt
from datetime import datetime, timedelta
payload = {
"sub": "user-123",
"exp": datetime.utcnow() + timedelta(minutes=15),
}
token = jwt.encode(payload, "super-secret-key", algorithm="HS256")
print("Token:", token)
decoded = jwt.decode(token, "super-secret-key", algorithms=["HS256"])
print("Decoded:", decoded)
Older PyJWT versions returned bytes from jwt.encode, while newer releases return a string by default. If you have
legacy code that still calls .decode("utf-8") on the return value, that can raise a different error. A fast sanity
check in a shell keeps the code path clear before you hook these calls into a larger web framework or background worker.
- Test A Minimal Script — Place the snippet above in a small file, run it from the command line, and
confirm that it prints both a token and a decoded dictionary. - Match Secrets Across Services — Keep the same secret key or private key across every component that
signs and reads the tokens so that decode calls succeed. - Align Algorithms — Use the same algorithm string in both
encodeanddecode,
and include it in thealgorithmslist when you decode.
Once your minimal script works, drop the same pattern into your view, route, or command handler. If the error returns only when
the app framework runs, that often points back to environment differences between your shell and the runtime that loads the
project.
Quick Jwt Encode Troubleshooting Table
When you hit the error during a busy session, a short table can help you match symptoms to likely causes and fixes without
reading long logs each time.
| Symptom | Likely Cause | Fast Fix |
|---|---|---|
AttributeError: module 'jwt' has no attribute 'encode' |
Plain jwt package installed instead of PyJWT |
Uninstall jwt, reinstall PyJWT, then test dir(jwt) |
| Error appears only in one project folder | Local jwt.py or token.py shadows PyJWT |
Rename the file, clear __pycache__, import jwt again |
| Shell works but app runner fails | Different Python interpreter or virtual environment | Activate the same environment for both shell and app process |
New error on token.decode("utf-8") |
PyJWT version changed return type from bytes to string | Remove the extra .decode call or pin PyJWT to a known version |
You can keep this table near your project notes and adjust the entries as you see patterns in your own stack. The message
AttributeError: Module 'JWT' Has No Attribute 'Encode' may look the same on every machine, yet your own logs and
setups will reveal which row describes your situation best.
