# Add Role-Based Permissions to a Django REST Framework API

Yes. An agent adds a role field, DRF permission classes and a role service to your Django REST Framework API, covers them with tests and opens a pull request.

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

## What the agent does

The agent clones the repository into its own cloud sandbox and reads how users and permissions work today. In HackSoftware/Django-Styleguide-Example, `users/models.py` defines `BaseUser` with `email`, `is_active`, `is_admin`, a `jwt_key` and `PermissionsMixin`, on a `BaseModel` that adds `created_at` and `updated_at`; `create_superuser` sets `is_admin` and `is_superuser`. `api/mixins.py` has `ApiAuthMixin`, which lists the session, session-as-header and JWT authentication classes and `permission_classes = (IsAuthenticated,)`, while `REST_FRAMEWORK` in `config/django/base.py` leaves `DEFAULT_AUTHENTICATION_CLASSES` empty. `users/apis.py` exposes `UserListApi`, `UserDetailApi`, `UserCreateApi` and `UserUpdateApi`, none of which use the mixin, under a comment that says an authenticated version is still to come, and `users/services.py` holds `user_create` and `user_update` under `@transaction.atomic`.

It then reads the conventions the repository enforces, because the styleguide is the point of this project. Services do the writes, selectors do the reads, `model_update` handles plain field updates, tests live under `users/tests/services/` as `TestCase` classes, `authentication/tests/apis/test_user_login.py` drives endpoints through `APIClient` and `reverse('api:authentication:session:login')`, and CI runs `ruff check .`, `mypy --config mypy.ini styleguide_example/` with the Django and DRF stubs, and `pytest` against a Postgres service on Python 3.12.4. The agent keeps every new file inside those patterns.

The change itself: a `role` `TextChoices` with `admin`, `editor` and `viewer` on `BaseUser`, defaulting to `viewer`, with a migration and a data migration that sets `admin` wherever `is_admin` is true so `is_staff()` and the Django admin keep their meaning; a `users/permissions.py` with a `HasRole` permission class that takes the allowed roles and an `IsAdminRole` shortcut; a `user_set_role` service under `@transaction.atomic` that refuses to demote the last admin; and the APIs wired up, `UserListApi` and `UserDetailApi` behind `ApiAuthMixin`, `UserCreateApi` and `UserUpdateApi` additionally behind `IsAdminRole`, plus a `UserSetRoleApi` with an `InputSerializer` of one `role` field. `BaseUserAdmin` gains `role` in `list_display` and `list_filter`, and `BaseUserFilter` accepts `role` so the list endpoint can filter by it.

Tests follow the repository's two styles: service tests for `user_set_role`, including the last-admin refusal, and API tests under `users/tests/apis/` that log in through the session endpoint as a viewer and an admin and assert `403` and `200` on create, update and set-role. The agent runs `ruff check .`, the mypy command and `pytest` in the sandbox against a Postgres container and opens a pull request that links back to the issue.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "A Linear issue labeled agent says: \"Add role-based permissions to the users API. We need admin, editor and viewer roles, only admins may create or update users or change roles, and the list and detail endpoints must require login.\" Do the work in this repository following its service and selector conventions: add the role field with a migration that maps existing is_admin users to admin, add DRF permission classes, a role-change service that keeps at least one admin, wire the users APIs and expose the role in the admin and the list filter. Add service and API tests, run ruff, mypy and pytest, and open a pull request that links back to the issue.",
  "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

What comes back is a pull request on its own branch that links to the issue. The diff touches `users/models.py`, two new migrations, `users/permissions.py`, `users/services.py`, `users/selectors.py` and `users/filters.py`, `users/apis.py` and `users/urls.py`, `users/admin.py`, and new tests under `users/tests/services/` and `users/tests/apis/`. The description lists each endpoint with the role it now requires.

The run's record keeps the `ruff`, `mypy` and `pytest` output, so a reviewer sees the type checker accept the new permission classes under the DRF stubs and every new test named with its result, without running the compose stack.

Before merging, a reviewer checks the data migration against a copy of production, confirms that no client calls `UserCreateApi` anonymously today, since it becomes admin-only, and decides whether the role should also drive the Django admin's `is_staff()`, which the pull request leaves on `is_admin`.

## Run it on every Linear issue labeled agent

Add an automation with a `linear` trigger on the label you triage with, in the Project that has the repository. The trigger appends the issue to this prompt, so each labeled issue starts one run in its own sandbox and ends in its own pull request. From your own server, the same run is one `POST /o/{org}/sessions` naming the issue as a resource at `https://linear.app/<workspace>/issue/<ID>`, read through your Linear connection, with the repository in `resources`.

Set a webhook URL on the API key and Rush posts `run.completed` or `run.failed` with the `session_url` when a key-started run finishes, so a handler can write the pull request link back on the issue. Send a `request_id` with each body so a retried request cannot start a duplicate run.

## Why run it on Rush?

Permission changes are the kind of work where a missed endpoint is a security bug, and the only evidence that counts is the test matrix: each role against each endpoint, with the expected status. The sandbox runs the whole suite against Postgres with the repository's own `pytest` settings and keeps the output, so the pull request arrives with that matrix proven rather than described.

The styleguide's rules, services for writes, selectors for reads, typed code under mypy, are easy to break in a hurry. The agent reads them first and the linters run before the pull request opens, so review time goes to the policy, not the shape. The same prompt runs across several Django services at once, each in its own sandbox.

## Frequently asked questions

### Why a role field instead of Django groups?

The repository models everything explicitly on `BaseUser` and already carries `is_admin`, so a single `role` column with a `TextChoices` is the smaller change and the one the styleguide's selectors and filters work with directly. Groups remain available through `PermissionsMixin` if a finer grid is needed later.

### What happens to existing admins?

A data migration sets `role` to `admin` for every row where `is_admin` is true, and `create_superuser` sets both. `is_staff()` keeps reading `is_admin`, so Django admin access does not change.

### Does it require login on the list endpoint?

Yes. `UserListApi` and `UserDetailApi` gain `ApiAuthMixin`, so they accept a session, a session header or a JWT and answer `401` otherwise. The tests log in through the existing session login endpoint before calling them.

### Will mypy accept the new permission classes?

The repository runs mypy with `django-stubs` and `djangorestframework-stubs`, and `ApiAuthMixin` already types `permission_classes` as `PermissionClassesType`. The agent types `HasRole` as a `BasePermission` subclass and runs the same mypy command CI runs before opening the pull request.

## More Django REST Framework jobs

- [Add Security Headers to a Django REST Framework API](https://getrush.ai/run/add-security-headers/django-rest-framework/)
- [Add Soft Delete to a Django REST Framework API](https://getrush.ai/run/add-soft-delete/django-rest-framework/)
- [Add Throttling to a Django REST Framework API from a Linear Issue](https://getrush.ai/run/add-throttling/django-rest-framework/)

## More jobs like this: Turn a Linear label into a PR

- [Add a Route Guard for Unsaved Changes in an Angular App from a Linear Issue](https://getrush.ai/run/add-route-guard/angular/)
- [Add an RSS Feed to a Wagtail Blog](https://getrush.ai/run/add-rss-feed/wagtail/)
- [Add a Scheduled Function to a Serverless Framework API](https://getrush.ai/run/add-scheduled-functions/serverless/)

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