All jobs

Add Health Checks to a Django REST Framework API

Yes. An agent adds liveness and readiness endpoints to your DRF API that check the database and cache, answer 503 with detail, and come with tests in house style.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the project's conventions before it adds an endpoint, because a styleguide project is judged on following them. In an API like HackSoftware/Django-Styleguide-Example, requirements/base.txt pins Django==5.2.7, djangorestframework==3.16.1, drf-jwt, celery==5.5.3 with django-celery-results and django-celery-beat, django-structlog, django-cors-headers, psycopg2 and sentry-sdk, and runtime.txt fixes Python 3.12.4. config/django/base.py lists the apps in LOCAL_APPS, one AppConfig path per app, sets REST_FRAMEWORK with the project's own exception handler, DjangoFilterBackend and an empty DEFAULT_AUTHENTICATION_CLASSES, reads DATABASES from DATABASE_URL with a PostgreSQL default and switches to a github_actions database when GITHUB_WORKFLOW is set, and turns on ATOMIC_REQUESTS. config/urls.py mounts everything under api/, and styleguide_example/api/urls.py includes auth/, users/, errors/, files/ and google-oauth2/ with namespaces. Every API is an APIView with nested InputSerializer and OutputSerializer classes that calls a function in services.py or selectors.py, as styleguide_example/users/apis.py does. Procfile runs gunicorn config.wsgi:application and Celery worker and beat, and docker-compose.yml starts postgres:14.1, RabbitMQ, Django, a worker and beat. There is no health route.

The change is one new app in the house style. styleguide_example/health/ gets apps.py with HealthConfig, services.py with health_check_database, which opens a cursor on connections['default'] and runs SELECT 1, health_check_cache, which writes and reads one key through the configured cache, and health_check_celery_broker, which calls app.control.ping with a short timeout against the Celery instance in styleguide_example/tasks/celery.py and is only consulted when a HEALTH_CHECK_CELERY_BROKER setting is true, declared in a new config/settings/health.py imported from base.py the way celery.py and cors.py are. apis.py has HealthLiveApi, which answers 200 with { status: ok } and touches nothing, and HealthReadyApi, which runs the checks and answers 200, or 503 with each check's name and result, through an OutputSerializer. Both set authentication_classes and permission_classes to empty lists so a probe never needs a session or a JWT. Because ATOMIC_REQUESTS wraps every view in a transaction, an unreachable database would fail before the view ran and answer 500; the agent decorates HealthReadyApi.dispatch with transaction.non_atomic_requests so the outage is reported as the structured 503 instead. urls.py names the routes live and ready, api/urls.py includes them under health/ with the health namespace, and base.py adds styleguide_example.health.apps.HealthConfig to LOCAL_APPS.

Tests follow styleguide_example/authentication/tests/apis/test_user_login.py: a Django TestCase, an APIClient, and URLs from reverse with the api: namespace. styleguide_example/health/tests/apis/test_health.py asserts 200 on api:health:live, 200 on api:health:ready with the database and the locmem cache that config/django/test.py configures, 503 with database marked as failed when the connection's cursor is patched to raise OperationalError, and that the broker check is skipped when its setting is off, which it is under the test settings where Celery runs eagerly with a memory broker. pytest.ini points DJANGO_SETTINGS_MODULE at config.django.test, so pytest is the command.

Verification follows the build job in .github/workflows/django.yml: Python 3.12.4, pip install -r requirements/local.txt, a PostgreSQL service, ruff check ., mypy --config mypy.ini styleguide_example/ with the Django and DRF stub plugins, and pytest. The agent starts PostgreSQL in its sandbox, sets DATABASE_URL, runs those three commands with the new app typed so mypy stays clean under pyproject.toml's Ruff settings, then starts manage.py runserver and requests both endpoints to quote their JSON. The README's table of contents gets a Health checks section naming the two routes and the broker setting.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add health checks to this Django REST Framework API. Read requirements/base.txt, runtime.txt, config/django/base.py, config/django/test.py, config/settings/celery.py, config/urls.py, styleguide_example/api/urls.py, styleguide_example/api/mixins.py, styleguide_example/users/apis.py, styleguide_example/tasks/celery.py, styleguide_example/authentication/tests/apis/test_user_login.py, pytest.ini, mypy.ini and .github/workflows/django.yml first. Add a styleguide_example/health app in the project's style: an apps.py, a services.py with a database check that runs SELECT 1 on the default connection, a cache check that writes and reads one key, and a Celery broker check through app.control.ping that only runs when a HEALTH_CHECK_CELERY_BROKER setting is true, declared in a new config/settings/health.py imported from base.py like the other settings modules. Add apis.py with HealthLiveApi answering 200 without touching anything and HealthReadyApi answering 200 or 503 with each check's name and result through an OutputSerializer, both with empty authentication and permission classes, and decorate the ready view so ATOMIC_REQUESTS does not wrap it. Add urls.py with live and ready route names, include it under health/ in api/urls.py, and register the app in LOCAL_APPS. Add tests in the style of test_user_login.py for both routes, a 503 with the database cursor patched to raise OperationalError, and the broker check skipped under test settings. Start PostgreSQL, set DATABASE_URL, and run ruff check ., mypy --config mypy.ini styleguide_example/ and pytest as the workflow does, then run the server and request both routes. Add a Health checks section to the README. Do not change requirements, the Celery configuration or any workflow. Open a pull request that lists the routes and checks, and quotes the lint, type check and test output with the two JSON responses.",
  "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 adds the styleguide_example/health app with apps.py, services.py, apis.py, urls.py and a tests/apis/test_health.py, adds config/settings/health.py, and changes config/django/base.py, styleguide_example/api/urls.py and README.md. The body lists the two routes and what ready checks, explains why its view is non-atomic, and quotes ruff, mypy and pytest with the two JSON responses from the running server.

The session read names the repository and the pull request. The transcript keeps the PostgreSQL start, the install, the first pytest run in which the health tests failed before the app existed, the passing run, the type check and lint, and the two requests. GET /o/{org}/p/{project}/sessions/{id}/changes returns the diff per file.

Before merging, a reviewer checks that live touches neither the database nor the cache so a database outage never restarts healthy processes, that ready is the only view exempt from ATOMIC_REQUESTS, that the broker check stays off unless the setting turns it on, and that the new app follows the services-and-selectors layout the styleguide asks for. A follow-up on the same session can add a migrations check or a storage check for the files app.

Run it on every new Django service

Health endpoints are the same shape on every service and worth handing off. From Claude Code or Codex with Rush connected as an MCP server at https://api.phoenix.so/mcp, ask for a create_session with this prompt and your repository, keep working, and read the pull request later with get_session; wait_for_sessions waits up to 50 seconds per call when you would rather block. The sandbox parks with the virtual environment and the database when the turn ends, so a send_session_message asking for a storage check wakes it where it stopped.

For the services you already run, a script lists what the Rush GitHub App installation reaches with GET /o/{org}/github, looks for a health route in each, and sends one POST /o/{org}/sessions per repository without one, with a request_id per repository so a retry returns the run it already started. A webhook_url on the key receives run.completed, run.failed or run.cancelled for each run the key started, with data.session_url to read for the pull request link.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

A health check written without reading the settings fails in the one case it exists for: with ATOMIC_REQUESTS on, a readiness view answers 500 rather than 503 when the database is down, and a probe placed behind the JWT or session authentication answers 401 to the load balancer. The agent reads base.py, the mixins and the test settings in its own sandbox, places the view and its decorator accordingly, and proves the 503 with a patched connection in a test it runs against a real PostgreSQL.

The pull request carries the lint, the type check, the test run and two live responses, and the new app looks like the apps beside it, so a reviewer who knows the styleguide reads it in minutes. Several Django services get the same pair of routes at once, each in its own sandbox and pull request, with each repository's settings read rather than assumed.

Frequently asked questions

Why is the readiness view exempt from ATOMIC_REQUESTS?

Because base.py sets ATOMIC_REQUESTS to true, Django opens a transaction before any view runs. If the database is unreachable, that fails first and the client sees a 500 with no detail. transaction.non_atomic_requests on the ready view lets the service function run its own check and answer a 503 that names the database.

Does the probe need a JWT or a session?

No. Both views set authentication_classes and permission_classes to empty lists, and the project's REST_FRAMEWORK default authentication is already empty, so a probe with no headers gets an answer. Only the routes under health/ are open in this way.

Will it check Celery and RabbitMQ too?

Only when HEALTH_CHECK_CELERY_BROKER is true. app.control.ping needs a reachable broker and a running worker, and under the test settings Celery runs eagerly with a memory broker, so the check is off by default and off in tests. Turn it on for the deployment that runs a worker.

Why a new app rather than two views in an existing one?

Because the project is organised one app per concern with apis.py, services.py and urls.py in each, and LOCAL_APPS lists them by AppConfig. A health app follows that layout, keeps the checks out of users or api, and gives the tests the same place as every other app's.

More Django REST Framework jobs

The same job on other stacks

Keep reading