# Upgrade PyJWT From 1.x to 2.x in a Flask API

Yes. An agent moves an API from PyJWT 1.7 to 2.x: encode() now returns a str, decode() needs algorithms, and each token route is tested end to end.

[Run this on Rush](https://cloud.getrush.ai/run/upgrade-pyjwt/pyjwt/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

PyJWT 2 changed two things that almost every caller touches. `jwt.encode()` returns a `str` where version 1 returned `bytes`, and `jwt.decode()` refuses to run without an explicit `algorithms` list. The agent reads the pin and then every call. In a small token service like udacity/cd0157-Server-Deployment-and-Containerization, `requirements.txt` pins `pyjwt==1.7.1`, and `main.py` has one `jwt.encode` call in `_get_jwt()` and two `jwt.decode` calls, one in the `require_jwt` decorator and one in the `/contents` route. The `/auth` route returns `jsonify(token=_get_jwt(user_data).decode('utf-8'))`, the idiom version 1 required to turn the bytes into JSON.

It records a baseline before changing anything: `pytest` collects two tests from `test_main.py`, `test_health` and `test_auth`, and both pass on 1.7.1. With PyJWT upgraded, `test_auth` fails with `AttributeError: 'str' object has no attribute 'decode'` at `main.py`, line 83. The fix is to delete the `.decode('utf-8')` call. The agent checks the two `jwt.decode` call sites for the second breaking change and finds both already pass `algorithms=['HS256']`, so they need no edit.

It does not stop at a green suite, because of how this file handles errors. Both decode calls sit inside a bare `except:` that answers 401. If a decode call had been missing `algorithms`, PyJWT 2 would raise a `DecodeError` on every request and the service would report it as 401 Unauthorized for every user, with no traceback anywhere. No existing test would notice, since nothing in `test_main.py` calls `/contents`. So the agent adds a round trip: post to `/auth`, send the returned token to `/contents` as a Bearer header, and assert a 200 with the same email, then send a corrupted token and assert 401. It runs that test on the old pin and the new one.

Two smaller findings come out of the run's warnings. Newer PyJWT prints `InsecureKeyLengthWarning: The HMAC key is 13 bytes long, which is below the minimum recommended length of 32 bytes for SHA256`. Thirteen bytes is the length of the fallback secret in `main.py`, which also shows that the `JWT_SECRET` the test fixture sets is never used: the module reads the variable once at import, before the fixture runs. The agent reports both and changes neither, since the secret is deployment configuration. It also reads the build files, because the two do not agree on Python: the `Dockerfile` builds on a Python 3.9 image, while `buildspec.yml` declares `python: 3.7` and runs `pip install -r requirements.txt` there. The newest PyJWT requires Python 3.9, and 2.8.0 is the last release that installs on 3.7.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Upgrade PyJWT in this repository from 1.x to 2.x. Read the dependency files for the pin, and find every jwt.encode, jwt.decode, jwt.get_unverified_header and PyJWT exception import, including calls that pass verify=False or omit algorithms. Run the test suite on the current pin and record the result. Upgrade PyJWT in a clean virtualenv on the Python version the project deploys with, run the suite again and quote each failure. Fix each call for the 2.x API: encode returns str, so remove .decode() on its result; decode must be given algorithms; verify=False becomes options={'verify_signature': False}. Use the algorithm the tokens are already signed with and do not widen the list. Look at the error handling around every decode call: where an except clause would turn a PyJWT usage error into a 401 or a silent None, add a test that issues a real token and sends it back through the protected route, plus one with a tampered token, and run both on the old and new versions. Report every warning PyJWT prints, including key length warnings, without changing secrets or configuration. Read the Dockerfile, CI and build files for the Python versions in use and choose a PyJWT pin that installs on all of them; if they disagree, say which file blocks the newest release. Do not change any other pin unless the upgrade requires it. Open a pull request with test results before and after.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request with three files changed: the pin in `requirements.txt`, one line in `main.py`, and the new round-trip tests in `test_main.py`. The description shows the `AttributeError` with its file and line, the test counts on each version, and a table of the three `jwt` call sites with what each needed, which for two of them is nothing.

The pin itself is argued in the description. If every build file ran Python 3.9 or later, the newest PyJWT would be the answer. Here one file still declares 3.7, so the agent either pins the last release that supports it or, if you say so in a follow-up message to the same session, raises the Python version in that file and takes the newest. It does not change a build runtime on its own.

A reviewer should look at one thing beyond the diff: what your clients do with the token. The JSON response is unchanged, a string before and a string after. Any other code that called `.decode()` on a token, in a worker or a script outside this repository, breaks the same way and is not covered by this pull request. The description lists the warnings it saw, including the short default secret, as items for the team.

## Run it on every Monday morning

Dependency upgrades like this one fit a `schedule` trigger. Create an automation in the Project with this prompt and a weekly `cron`, and it starts a run each week that checks the pin and opens a pull request only when there is an upgrade to make. The runs count against the automation's own `max_runs_per_hour`.

If you would rather react to a security advisory, have the handler that receives your scanner's alert call `POST /o/{org}/sessions` with the body above and the affected repository in `resources`. The handler can append the advisory text to `input`. Send a `request_id` that is a UUID v5 of the advisory id and repository so a repeated alert does not start a second run.

## Why run it on Rush?

Authentication code is the worst place for an upgrade that only looks finished. The usual pattern around `jwt.decode` is a broad `except` that returns 401, which means a library usage error and a bad token are indistinguishable from outside. The agent issues a real token and plays it back through the protected route on both versions, in a sandbox with a clean install of each, so the pull request shows a login that works and not only a suite that passes.

The record matters here too. A reviewer of an auth change wants to see the commands: which PyJWT version was installed, what the failing test printed, what the round trip returned. The run keeps each command and its output, and the description quotes from them.

## Frequently asked questions

### Why do I get "'str' object has no attribute 'decode'" after upgrading PyJWT?

`jwt.encode()` returned `bytes` in PyJWT 1 and returns `str` in PyJWT 2. Code that called `.decode('utf-8')` on the result to get a string now calls it on a string. Remove the `.decode()` call; the value is already what you wanted.

### What else breaks between PyJWT 1 and 2?

`jwt.decode()` requires the `algorithms` argument and raises `DecodeError` without it. `verify=False` is replaced by `options={"verify_signature": False}`. The agent searches for each pattern and lists every call site with what it changed.

### Will tokens issued before the upgrade still validate?

Yes. The token format, the signature and the secret are unchanged, so a token signed by version 1 verifies under version 2 with the same key and algorithm. Users do not need to sign in again because of this change.

### Does the agent change my JWT secret if PyJWT warns that it is too short?

No. It reports the warning and the length PyJWT measured. Rotating a signing secret invalidates every outstanding token and belongs to whoever runs the deployment.

## More PyJWT jobs

- [Add Logout That Revokes a JWT in FastAPI](https://getrush.ai/run/add-token-revocation/pyjwt/)
- [Fix "DecodeError: It is required that you pass in a value for the 'algorithms' argument" in PyJWT](https://getrush.ai/run/fix-jwt-decode-algorithms-argument-required/pyjwt/)

## More jobs like this: Upgrade dependencies weekly

- [Upgrade Python Dependencies Weekly for a Dagster Project](https://getrush.ai/run/upgrade-python-dependencies/dagster/)
- [Upgrade Python Dependencies Weekly for a LangGraph Agent](https://getrush.ai/run/upgrade-python-dependencies/langgraph/)
- [Upgrade Python Dependencies Weekly for a Litestar App](https://getrush.ai/run/upgrade-python-dependencies/litestar/)
- [Upgrade Python Dependencies in a Streamlit App](https://getrush.ai/run/upgrade-python-dependencies/streamlit/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
