Claude API Django REST Framework Integration
Integrating the Claude API into a Django REST Framework (DRF) project means adding a view that calls Anthropic's chat completion endpoint, wrapping the request/response in a serializer, and handling auth, errors, and rate limits the way the rest of your API already does. There's no official Django package for this — you're making HTTP calls from a view, same as you would to any third-party API — but DRF's structure (serializers, permissions, viewsets) makes it easy to keep this clean and testable.
This guide walks through a working setup: a ChatView that accepts a prompt, calls Claude, and returns a structured response, plus patterns for streaming and production error handling.
Why DRF needs its own pattern here
Claude's API is just HTTPS and JSON, so technically any requests.post() call works. But in a real DRF project you want:
- Input validation via serializers (prompt length, model name, temperature bounds)
- Consistent error responses matching your existing API conventions
- A place to enforce per-user rate limits or quotas
- Separation between the "talk to Claude" logic and the view/serializer layer, so it's mockable in tests
Installing dependencies
pip install djangorestframework requests
You don't need the official Anthropic Python SDK — requests is enough and keeps the dependency surface small. If you prefer the SDK, pip install anthropic works the same way inside a DRF view.
Settings
Store your API key as an environment variable, never in source:
# settings.py
import os
ANTHROPIC_API_KEY = os.environ["ANTHROPIC_API_KEY"]
ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages"
Serializer for the request
# serializers.py
from rest_framework import serializers
class ChatRequestSerializer(serializers.Serializer):
prompt = serializers.CharField(max_length=4000)
model = serializers.CharField(default="claude-3-5-sonnet-20241022")
max_tokens = serializers.IntegerField(default=1024, min_value=1, max_value=4096)
The view
# views.py
import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
from .serializers import ChatRequestSerializer
class ChatView(APIView):
def post(self, request):
serializer = ChatRequestSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
data = serializer.validated_data
try:
resp = requests.post(
settings.ANTHROPIC_API_URL,
headers={
"x-api-key": settings.ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
json={
"model": data["model"],
"max_tokens": data["max_tokens"],
"messages": [{"role": "user", "content": data["prompt"]}],
},
timeout=30,
)
resp.raise_for_status()
except requests.exceptions.Timeout:
return Response(
{"error": "upstream_timeout"},
status=status.HTTP_504_GATEWAY_TIMEOUT,
)
except requests.exceptions.HTTPError as e:
return Response(
{"error": "upstream_error", "detail": str(e)},
status=status.HTTP_502_BAD_GATEWAY,
)
payload = resp.json()
content = payload.get("content", [])
text = content[0]["text"] if content else ""
return Response({"reply": text, "usage": payload.get("usage", {})})
Wire it up in urls.py as you would any APIView, add it to a router if you'd rather use a ViewSet, and you have a working Claude-backed endpoint behind your existing DRF auth classes and permission checks.
Handling streaming in DRF
Anthropic's streaming responses use server-sent events. DRF's standard Response doesn't stream well, so for token-by-token output you'd drop down to Django's StreamingHttpResponse:
from django.http import StreamingHttpResponse
def event_stream(prompt):
with requests.post(
settings.ANTHROPIC_API_URL,
headers={...},
json={"model": "...", "stream": True, "messages": [...]},
stream=True,
) as resp:
for line in resp.iter_lines():
if line:
yield line + b"\n"
class ChatStreamView(APIView):
def post(self, request):
prompt = request.data.get("prompt", "")
return StreamingHttpResponse(
event_stream(prompt),
content_type="text/event-stream",
)
This works, but you're now responsible for reconnect logic, partial-message buffering, and keeping the connection open under Gunicorn/uWSGI worker timeouts — which is where a lot of DRF + Claude integrations get stuck in production.
Where SubToAPI fits in
If you'd rather not maintain raw requests calls, retry logic, and SSE plumbing inside your Django app, SubToAPI sits between your DRF backend and Claude. You get an application API key (sub_live_...) that speaks the same Messages-style schema, so your ChatView above barely changes — swap the URL and header:
resp = requests.post(
"https://api.subtoapi.app/v1/messages",
headers={"Authorization": f"Bearer {settings.SUBTOAPI_KEY}"},
json={
"model": data["model"],
"max_tokens": data["max_tokens"],
"messages": [{"role": "user", "content": data["prompt"]}],
},
)
That gives you usage metadata per request, streaming support out of the box, and a dashboard for team seats instead of sharing one Anthropic key across your Django deployment. See the quickstart and the Messages API reference for the exact request/response shape, and streaming docs for the SSE format if you're building the StreamingHttpResponse view above.
Testing the integration
Mock the HTTP call rather than hitting the real API in your test suite:
from unittest.mock import patch
@patch("myapp.views.requests.post")
def test_chat_view(self, mock_post):
mock_post.return_value.json.return_value = {
"content": [{"text": "Hello from Claude"}],
"usage": {"input_tokens": 5, "output_tokens": 3},
}
mock_post.return_value.raise_for_status = lambda: None
response = self.client.post("/api/chat/", {"prompt": "hi"})
assert response.status_code == 200
assert response.data["reply"] == "Hello from Claude"
This keeps your DRF test suite fast and avoids burning API quota on CI runs.
questions
Do I need the Anthropic Python SDK to use Claude with DRF? No. The SDK is convenient but unnecessary — requests or httpx work fine for a single endpoint, and avoiding the SDK keeps your dependency tree smaller in a Django project.
How should I handle Claude API keys in a multi-tenant DRF app? Store a single server-side key in environment variables and never expose it to clients; scope access through your own DRF permissions and user/team models instead of issuing separate Anthropic keys per tenant.
What's the best way to add streaming to a DRF view? Use Django's StreamingHttpResponse with requests' stream=True, since DRF's Response buffers the full body. If you want streaming without managing SSE parsing yourself, a proxy like SubToAPI handles that layer for you.