# Migrate From python-jose to PyJWT in a FastAPI App

Yes. An agent swaps python-jose for PyJWT in a FastAPI app, shows that tokens issued before the change still verify, and opens a pull request.

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

## What the agent does

The agent first measures how far python-jose reaches into the code, and in a FastAPI app built from the security tutorial it is usually two files. In a project like Jahn16/fast-mock, `requirements.txt` pins `python-jose[cryptography]==3.3.0`. `app/security.py` has `from jose import jwt`, a `create_access_token` that signs `{"exp": expire, "sub": subject}` with `settings.SECRET_KEY` and `HS256`, and a `decode_token` that calls `jwt.decode` with `algorithms=[ALGORITHM]`. `app/api/deps.py` has `from jose.jwt import JWTError` and catches it in `get_current_user` to answer 401. Nothing else imports the library; `login.py` only calls `create_access_token(subject=str(user.id))`.

The edit is small on purpose. `from jose import jwt` becomes `import jwt`, the requirement becomes `PyJWT`, and `except JWTError` becomes `except jwt.InvalidTokenError`. The `encode` and `decode` calls keep their arguments. The agent then checks the three places where the two libraries part ways. python-jose decodes a token when `algorithms` is left out, and PyJWT refuses with a `DecodeError` saying the argument is required; this code already passes it. Both reject a `sub` claim that is not a string, and `login.py` already wraps the user id in `str()`. And where python-jose raised a plain `JWTError` for a bad signature or a malformed string, PyJWT raises `InvalidSignatureError` or `DecodeError`. Those two and `ExpiredSignatureError` are all subclasses of `InvalidTokenError`, so one `except` still covers them.

Then it answers the question that decides whether the deploy is safe: does a token issued before the change still verify after it. The two packages import as `jose` and `jwt`, so they install side by side. The agent signs the same payload with the same key in each, decodes each token with the other library, and compares the two strings. For HS256 they are the same string, so a user holding a token from the old build stays signed in. It also sends an expired token, a token signed with another key and a string that is not a token through `decode_token` under both libraries and records the exception class each one raises.

This repository has no tests, so the agent adds a `tests/test_security.py` for the round trip, the expiry and the 401 that `get_current_user` raises for a bad token, which happens before the database is read. `app/config.py` builds its settings at import time and requires `SECRET_KEY` and `SQLALCHEMY_DATABASE_URL`, so the tests set both. PyJWT 2.15 emits an `InsecureKeyLengthWarning` when an HS256 key is shorter than 32 bytes. The agent cannot see your production secret, so the pull request asks you to check its length. It also reports two things it leaves alone: `create_access_token` falls back to 15 minutes because `login.py` passes no `expires_delta`, so `ACCESS_TOKEN_EXPIRE_MINUTES = 30` is never read, and `datetime.utcnow()` is deprecated since Python 3.12.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Replace python-jose with PyJWT in this FastAPI app. Read the requirement files, the Dockerfile and every file that imports jose. List each call: jwt.encode, jwt.decode with its algorithms and options arguments, get_unverified_header or get_unverified_claims, any use of jose.jwe or jose.jwk, and every exception class imported from jose. Before editing, install both libraries side by side and write a script that, for the algorithm and claims this app uses, signs the same payload with each library, decodes each token with the other, and prints whether the two token strings are equal. Run an expired token, a token signed with a different key and a malformed string through both and print the exception class each raises. Then make the change: import jwt from PyJWT, map each jose exception to the PyJWT class that covers the same cases, keep algorithms explicit on every decode, and replace the requirement with PyJWT, adding the crypto extra only if an RS, ES or PS algorithm is used. If the code uses jose.jwe, stop and report it instead of porting it. Never print or log the secret key; if one is set in the environment, report only whether it is at least 32 bytes long. Add tests for token creation, decoding, expiry and the 401 path, set the environment variables the settings module needs, and run them. Resolve the requirements before and after and list the packages that leave. Report deprecated datetime calls and unused constants without changing them. Open a pull request with the script, its output and the test output.",
  "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 that changes `requirements.txt`, `app/security.py` and `app/api/deps.py` and adds the test file. Its description holds the comparison: for each case, what python-jose returned or raised and what PyJWT does, and the line saying the two libraries produce the same token string for this app's algorithm. It lists what leaves the install with the old package. python-jose 3.3.0 requires `ecdsa`, `rsa` and `pyasn1` whichever extra is chosen, and the `cryptography` extra adds that package. With plain `PyJWT` none of the four is resolved for this `requirements.txt`, and on the `python:3.10-slim` image the `Dockerfile` uses, PyJWT's one requirement is `typing_extensions`.

The reviewer checks three things. That `algorithms` is still passed to `decode`, because that argument is what stops a token from naming its own algorithm. That the `except` in `get_current_user` names a class wide enough to turn every invalid token into a 401 and not a 500. And that the requirement reads `PyJWT` and not `jwt`, which is a different project on PyPI that installs a module with the same name.

The description also states the option it did not take. python-jose 3.4.0, released in February 2025, is the version PyPI's advisory data names as the fix for CVE-2024-33663 and CVE-2024-33664, so raising the pin would close those two without a code change. It says whether the endpoints were called against a real PostgreSQL started in the sandbox or only the token functions were exercised.

## Run it on every service that still imports jose

Teams that start several services from one FastAPI template end up with the same two files in each. A script on your server can list the repositories whose requirement files name python-jose and send this body once per repository to `POST /o/{org}/sessions`, with that repository as the `resources` URL. Send a `request_id` with each one, a UUID v5 of the repository name, so running the script twice returns the runs it already started and opens no second pull request.

A key starts at most `max_concurrent` runs at once, 4 by default. A request past that still answers `202` with `status: "queued"` and starts when a slot frees, so the script needs no retry loop. If the key has a `webhook_url`, each run posts `run.completed` there when it ends, and reading the session returns its pull request.

## Why run it on Rush?

The claim a reviewer has to trust is that tokens issued yesterday still work tomorrow. It is quick to assert and tedious to prove. The run installs both libraries in its own sandbox, signs and cross-verifies real tokens, and every command with its output stays in the session transcript. The pull request quotes that output, so the reviewer reads the comparison instead of repeating it on a laptop.

Authentication is also where a quiet regression costs the most: an `except` clause one class too narrow turns an expired token into a 500. The agent raises each failure on purpose and records its class, so the mapping in `deps.py` rests on observed behaviour. And because each repository gets its own sandbox, ten services cut from one template can be migrated at the same time without sharing a virtualenv or a secret.

## Frequently asked questions

### Is PyJWT a drop-in replacement for python-jose?

For signed tokens, nearly: `jwt.encode` and `jwt.decode` take the same arguments. The exception classes have other names, `algorithms` is required on every decode, and python-jose's `jwe` module for encrypted tokens has no PyJWT counterpart. An app that encrypts tokens needs a different library, and the agent reports that instead of porting it.

### Will users be logged out when this deploys?

No, as long as the secret and the algorithm stay the same. A token is a signed string that neither library stores, and for HS256 both produce and accept the same strings. The agent's script shows it with tokens signed by each library and verified by the other.

### Which PyJWT exception replaces JWTError?

`jwt.InvalidTokenError`. It covers expired tokens, bad signatures, malformed strings and failed claim checks. `jwt.PyJWTError` is its parent and the base of every PyJWT exception. Catch `ExpiredSignatureError` on its own only if an expired token should get a different answer from an invalid one.

### Do I need PyJWT[crypto]?

Only for RS256, ES256 and the other asymmetric algorithms, which use the `cryptography` package. HS256 with a shared secret, as in this app, needs plain `PyJWT`. The agent reads the `algorithm` argument of every `encode` call before it chooses.

## More jobs like this: Upgrade dependencies weekly

- [Migrate From raven to sentry-sdk in a Django App](https://getrush.ai/run/migrate-raven-to-sentry-sdk/raven/)
- [Migrate From React Query v3 to TanStack Query v5](https://getrush.ai/run/migrate-react-query-to-tanstack-query/react-query/)
- [Migrate a React App From Redux to Redux Toolkit](https://getrush.ai/run/migrate-redux-to-redux-toolkit/redux/)
- [Replace the Deprecated request Package With Native fetch](https://getrush.ai/run/migrate-request-to-fetch/request/)
- [Replace rimraf and mkdirp With fs.rm and fs.mkdir in a Node.js Package](https://getrush.ai/run/migrate-rimraf-to-fs-rm/rimraf/)
- [Migrate Sass @import to @use and Clear the Dart Sass Deprecation Warnings](https://getrush.ai/run/migrate-sass-import-to-use/sass/)

## 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/)
