# Turn Sentry Errors Into Fix Pull Requests for a Django REST Framework API

Yes. A Sentry alert starts a run; the agent reproduces the error with a pytest test against your DRF API, fixes the service or selector, and opens a pull request.

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

## What the agent does

The run starts when your handler receives a Sentry alert and sends this request with the alert's JSON after the prompt. The agent reads the payload for the issue id, then uses the Sentry connection to fetch the issue and its latest event: the exception type and message, the `culprit`, the transaction name, the release and environment tags, the request data, and every in-app frame with filename, function and line. In an API built like HackSoftware/Django-Styleguide-Example the frames name files under `styleguide_example/`, so the agent knows which app, and which of its layers, before it opens the clone.

It then reads how the project is wired, because the fix belongs in a particular layer. `requirements/base.txt` pins Django 5.2.7, `djangorestframework` 3.16.1, `sentry-sdk` 2.42.0, `celery` 5.5.3, `django-filter` 25.2 and `drf-jwt` 1.19.2 on Python 3.12.4 from `runtime.txt`. `config/settings/sentry.py` calls `sentry_sdk.init` with `DjangoIntegration` and `CeleryIntegration`, `send_default_pii` off and a `traces_sampler` that ignores `celery.task` transactions, so the event carries no user data and the agent reproduces from the request body and query string alone. `REST_FRAMEWORK` in `config/django/base.py` sets `EXCEPTION_HANDLER` to `drf_default_with_modifications_exception_handler` in `styleguide_example/api/exception_handlers.py`, which maps `DjangoValidationError`, `Http404` and `PermissionDenied` to DRF responses and lets everything else through as a 500. That is what Sentry sees, and it includes `ApplicationError` from `styleguide_example/core/exceptions.py`, because only the alternative `hacksoft_proposed_exception_handler` turns that into a 400.

The APIs are thin: `styleguide_example/users/apis.py` has `UserDetailApi`, `UserListApi` and `UserCreateApi` as `APIView` classes with nested `InputSerializer`, `FilterSerializer` and `OutputSerializer`, calling `user_get` and `user_list` in `selectors.py` and `user_create` in `services.py`. So a frame in a view usually means a serializer or response shape, a frame in a selector means a queryset or filter, and a frame in a service means business logic or a transaction. The agent writes a test that reproduces the event in the app's `tests/` package, beside `users/tests/services/test_user_create.py`, using `pytest-django`'s `APIClient` or calling the service directly with `factory-boy` data, sends the request the event recorded, and asserts the response the code should have given. `pytest.ini` points `DJANGO_SETTINGS_MODULE` at `config.django.test`, and the test needs Postgres, which the agent starts in the sandbox the way the `build` job in `.github/workflows/django.yml` does.

Then it fixes the cause in the layer the frame named and runs the test until it passes, followed by the three commands the workflow runs: `ruff check .` with the `E4`, `E7`, `E9`, `F` and `I` rules and 120-column lines from `pyproject.toml`, `mypy --config mypy.ini styleguide_example/` with `django-stubs` and `djangorestframework-stubs`, and `pytest`. It opens a pull request that links the Sentry issue, quotes the exception and frames, and shows the test failing before the fix and passing after.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "A Sentry alert fired for this Django REST Framework API; its payload follows this prompt. Use the Sentry connection to read the issue, its latest event, the request data and the in-app stack frames. Read config/settings/sentry.py, config/django/base.py and styleguide_example/api/exception_handlers.py to understand which exceptions reach Sentry, then follow the frames into the app's apis.py, selectors.py or services.py. Add a pytest test in that app's tests package, using APIClient or the service function directly with factory-boy data, that reproduces the exception from the request the event recorded, then fix the cause in the layer the frames name until the test passes. Start Postgres in the sandbox as .github/workflows/django.yml does, install requirements/local.txt, and run ruff check ., mypy --config mypy.ini styleguide_example/ and pytest. Open a pull request that links the Sentry issue, quotes the exception and the frames, and shows the test failing before the fix. Change nothing unrelated to this error. If you cannot reproduce it, open no pull request and say what you tried.\n\nAlert payload:\n{payload}",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ],
  "connections": [
    "sentry"
  ]
}
```

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

What comes back is a pull request on its own branch with two kinds of change: the fix in one of `apis.py`, `selectors.py` or `services.py` under the app the frames named, and a new test module in that app's `tests/` package that fails on the old code. The description links the Sentry issue, quotes the exception line and the in-app frames, shows the test's output before and after, and lists the `ruff`, `mypy` and `pytest` commands with their results.

The repository's `Django application` workflow runs on the branch: a Postgres service, `pip install -r requirements/local.txt`, `ruff check .`, `mypy` and `pytest`, plus the Docker Compose job. The session transcript at `GET /o/{org}/sessions/{id}/messages` keeps every Sentry call the agent made and every command with its output, and the `run.completed` webhook carries the agent's summary as `data.result`, so your handler can post the pull request link back to the Sentry issue.

Before merging, a reviewer checks that the test fails for the reason Sentry reported and not a nearby one, that the fix sits in the right layer rather than catching the exception in the view, and that a change to a selector keeps the `FilterSerializer` contract the `UserListApi` exposes. If the right fix is different, a follow-up to the same session asks for it on the same branch.

## Run it on every Sentry issue alert

In Sentry, give the project an alert rule whose action is a webhook and point it at a small handler on your server. Sentry signs its own requests and cannot send a custom `Authorization` header, so the handler is what calls Rush: it sends this request with the alert's JSON after the prompt and a `request_id` that is a UUID v5 of the Sentry issue id, so a resent alert returns the run already started instead of a second one. One alert becomes one run and one pull request.

Set a `webhook_url` on the API key and Rush POSTs `run.completed` or `run.failed` when the turn finishes, with `session_url` and the result, so the handler can comment the pull request link on the issue. Or have the handler forward the alert to a `webhook` trigger on an automation in the Project with this prompt, sending the trigger's secret as `Authorization: Bearer`; the body becomes the event text after the prompt, and the automation's `max_runs_per_hour` caps an issue that keeps firing.

## Why run it on Rush?

Fixing a Sentry issue by hand means reading frames in one tab, finding the selector or service they point at in another, bringing up Postgres and RabbitMQ to reproduce, and then convincing a reviewer the test you wrote is the same failure. In a Rush sandbox the agent does that in one place: it reads the event through your connection, installs `requirements/local.txt`, starts the database the workflow uses, and nothing on anyone's laptop changes.

The pull request carries its proof: a test that fails before and passes after, the `ruff` and `mypy` output the workflow would demand anyway, and a transcript of every command. Several issues after a release can be worked at once in separate sandboxes, each ending in its own pull request, instead of waiting in a queue behind whoever is on call.

## Frequently asked questions

### How does the agent reach my Sentry project?

Connect Sentry once with `POST /me/connections` as an MCP server that signs in with OAuth, and name it in the run's `connections` field as the request on this page does. A run gets only the connections it names. If you would rather it never resolves or comments on an issue, say so in the prompt; every call it makes is in the transcript.

### Why does an ApplicationError show up in Sentry at all?

Because `REST_FRAMEWORK` uses `drf_default_with_modifications_exception_handler`, which only maps Django validation, 404 and permission errors; anything else, `ApplicationError` included, returns `None` from the handler and becomes a 500 that the Django integration reports. The alternative `hacksoft_proposed_exception_handler` in the same file would answer 400 with the message. The agent fixes the cause rather than switching handlers, unless the pull request is asked to.

### What if the request data was scrubbed?

`send_default_pii` is off in `config/settings/sentry.py`, so the event has no user object, and Sentry's own scrubbing may remove fields that look like secrets. The agent builds the reproduction from what remains: the URL, query string, method and any body fields present. If that is not enough to trigger the exception, it opens no pull request and its final message says which fields it would need.

### Does it need Celery running?

Not for an error raised in a request. The `CeleryIntegration` in `sentry.py` also reports task failures, with `celery.task` as the transaction op; for one of those the agent reproduces by calling the task function directly in a test, since `CELERY_TASK_ALWAYS_EAGER` style execution needs no broker. The workflow's Docker Compose job starts RabbitMQ, but `pytest` alone does not.

### Will it touch the mypy configuration or ignore errors?

No. `mypy.ini` and the `django-stubs` plugin stay as they are, and the prompt forbids unrelated changes. If the fix needs an annotation to pass `mypy`, the annotation is part of the fix; a `type: ignore` would be called out in the description so a reviewer can decide.

## More Django REST Framework jobs

- [Migrate from drf-jwt to SimpleJWT in a Django REST Framework App](https://getrush.ai/run/migrate-to-simplejwt/django-rest-framework/)
- [Migrate a Django REST Framework Project to uv](https://getrush.ai/run/migrate-to-uv/django-rest-framework/)
- [Find the Test Coverage Gaps in a Django REST Framework API](https://getrush.ai/run/test-coverage-gaps/django-rest-framework/)

## The same job on other stacks

- [Turn Sentry Errors Into Fix Pull Requests for an Electron App](https://getrush.ai/run/fix-sentry-errors/electron/)
- [Fix Sentry Errors in an Express App](https://getrush.ai/run/fix-sentry-errors/express/)
- [Fix Sentry Errors in a FastAPI App](https://getrush.ai/run/fix-sentry-errors/fastapi/)

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