← Blog

Claude API Django Backend Integration Example

2026-11-10 · 4 min read · SubToAPI Team

If you're building a Django backend and need to call Claude for chat, summarization, or structured data extraction, the integration pattern is straightforward: store your API key in settings, create a thin service module that wraps the HTTP calls, and expose it through a Django view or DRF endpoint. This article walks through a complete, working example — from project setup to streaming responses — so you can copy the pattern directly into your app.

The core challenge isn't calling the API itself (it's a standard HTTPS POST with a JSON body), it's structuring the Django side so the integration is testable, handles errors gracefully, and doesn't block your request workers when streaming. Below is a full example covering both a synchronous JSON response and a streaming view using Django's StreamingHttpResponse.

Project setup

Install the only dependency you need — requests — or use Django's async views with httpx if you're on Django 4.1+.

pip install requests python-dotenv

Add your key to settings using an environment variable, never hardcoded:

# settings.py
import os

CLAUDE_API_KEY = os.environ.get("CLAUDE_API_KEY")
CLAUDE_API_URL = "https://api.anthropic.com/v1/messages"

If you'd rather avoid managing Anthropic's raw API directly — handling retries, streaming edge cases, and key rotation yourself — you can point this same code at SubToAPI instead. It exposes a Claude-compatible HTTPS endpoint with application keys (sub_live_...), so the Django integration code below barely changes; you just swap the base URL and key.

A service module

Keep HTTP logic out of your views. Create services/claude.py:

# myapp/services/claude.py
import requests
from django.conf import settings

class ClaudeAPIError(Exception):
    pass

def send_message(prompt: str, model: str = "claude-sonnet-4-5", max_tokens: int = 1024) -> dict:
    headers = {
        "x-api-key": settings.CLAUDE_API_KEY,
        "anthropic-version": "2023-06-01",
        "content-type": "application/json",
    }
    payload = {
        "model": model,
        "max_tokens": max_tokens,
        "messages": [{"role": "user", "content": prompt}],
    }

    response = requests.post(settings.CLAUDE_API_URL, headers=headers, json=payload, timeout=30)

    if response.status_code != 200:
        raise ClaudeAPIError(f"Claude API error {response.status_code}: {response.text}")

    return response.json()

This same function works unchanged against SubToAPI — just point CLAUDE_API_URL at https://api.subtoapi.app/v1/messages and send Authorization: Bearer $SUBTOAPI_KEY instead of the x-api-key header. See the quickstart and messages docs for the exact request shape.

Wiring it into a view

A simple Django view that accepts a POST and returns Claude's reply:

# myapp/views.py
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .services.claude import send_message, ClaudeAPIError

@csrf_exempt
@require_POST
def chat_view(request):
    try:
        body = json.loads(request.body)
    except json.JSONDecodeError:
        return JsonResponse({"error": "invalid JSON"}, status=400)

    prompt = body.get("prompt")
    if not prompt:
        return JsonResponse({"error": "prompt is required"}, status=400)

    try:
        result = send_message(prompt)
    except ClaudeAPIError as e:
        return JsonResponse({"error": str(e)}, status=502)

    text = result["content"][0]["text"]
    return JsonResponse({"reply": text, "usage": result.get("usage")})

Add it to urls.py:

# urls.py
from django.urls import path
from myapp.views import chat_view

urlpatterns = [
    path("api/chat/", chat_view, name="chat"),
]

Streaming responses in Django

For chat UIs, streaming matters — users shouldn't wait for the full response before seeing anything. Django supports this with StreamingHttpResponse:

# myapp/views.py
import json
import requests
from django.conf import settings
from django.http import StreamingHttpResponse

def stream_claude(prompt):
    headers = {
        "x-api-key": settings.CLAUDE_API_KEY,
        "anthropic-version": "2023-06-01",
        "content-type": "application/json",
    }
    payload = {
        "model": "claude-sonnet-4-5",
        "max_tokens": 1024,
        "stream": True,
        "messages": [{"role": "user", "content": prompt}],
    }

    with requests.post(settings.CLAUDE_API_URL, headers=headers, json=payload, stream=True) as resp:
        for line in resp.iter_lines():
            if line:
                decoded = line.decode("utf-8")
                if decoded.startswith("data: "):
                    chunk = decoded[6:]
                    if chunk != "[DONE]":
                        yield f"data: {chunk}\n\n"

def chat_stream_view(request):
    prompt = request.GET.get("prompt", "")
    response = StreamingHttpResponse(stream_claude(prompt), content_type="text/event-stream")
    response["Cache-Control"] = "no-cache"
    return response

This same pattern applies to SubToAPI's streaming endpoint — see streaming docs for the full event format. In production behind Gunicorn, make sure you're running with an async worker class (gevent or uvicorn.workers.UvicornWorker) so a slow stream doesn't tie up a sync worker for the whole request.

Handling tool use and structured output

If your Django backend needs Claude to call functions — querying your database, triggering a workflow, or returning structured JSON — the request payload includes a tools array and you inspect stop_reason in the response to detect tool_use blocks. The service module above returns the raw JSON, so you can branch on result["stop_reason"] in your view logic before deciding whether to execute a tool and send a follow-up message.

Error handling and retries

Production Django integrations should handle three failure modes explicitly:

If you're running multiple Django services or a team of developers against the same Claude access, managing raw API keys across environments gets messy fast. SubToAPI adds per-app keys, usage metadata, and team seats on top of the same request format, so your Django code stays identical while key management moves to a dashboard. Plans start at €9/month on the pricing page, with a free trial at signup.

Questions

Do I need an async Django view to stream Claude responses? No. StreamingHttpResponse works with standard sync views, but you should run your WSGI server with workers that handle long-lived connections well (gevent or ASGI with Uvicorn) so streaming requests don't block other traffic.

Where should I store the Claude API key in a Django project? In an environment variable loaded via os.environ in settings.py, never committed to source control. Use python-dotenv locally and your platform's secrets manager in production.

Can I use this same Django code with SubToAPI instead of Anthropic directly? Yes. Swap the base URL to https://api.subtoapi.app/v1/messages, use a Bearer token instead of the x-api-key header, and the rest of the integration — views, streaming, error handling — stays the same. See the docs for details.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →