← Blog

Claude API Django Integration Tutorial & Guide

2026-11-17 · 5 min read · SubToAPI Team

If you're building a Django app and want to add Claude for chat, summarization, or content generation, the integration itself is straightforward: you make an HTTP request from a Django view to a Claude-compatible endpoint and return the result to your template or frontend. The parts that actually trip people up are streaming responses inside Django's request/response cycle, keeping API keys out of your repo, and handling retries without blocking your WSGI workers.

This guide walks through a working Django integration — views, settings, streaming, and error handling — plus a faster path using SubToAPI if you'd rather skip provider-specific SDK setup entirely.

Project setup

Install the requests library (or httpx if you want async support) and store your API key in environment variables, never in settings.py directly.

pip install requests python-dotenv
# settings.py
import os

CLAUDE_API_KEY = os.environ.get("SUBTOAPI_KEY")
CLAUDE_API_URL = "https://api.subtoapi.app/v1/messages"

Using an .env file locally and your host's secret manager in production keeps keys out of version control. If you're using Anthropic's API directly, swap in your own key and endpoint — the Django-side code below is identical either way.

A basic Django view

Here's a minimal synchronous view that sends a prompt to Claude and returns the response as JSON:

# views.py
import json
import requests
from django.conf import settings
from django.http import JsonResponse
from django.views import View

class ChatView(View):
    def post(self, request):
        body = json.loads(request.body)
        user_message = body.get("message", "")

        response = requests.post(
            settings.CLAUDE_API_URL,
            headers={
                "Authorization": f"Bearer {settings.CLAUDE_API_KEY}",
                "Content-Type": "application/json",
            },
            json={
                "model": "claude-sonnet-4",
                "max_tokens": 1024,
                "messages": [{"role": "user", "content": user_message}],
            },
            timeout=30,
        )
        response.raise_for_status()
        data = response.json()
        return JsonResponse({"reply": data["content"][0]["text"]})

Wire it into urls.py as usual:

# urls.py
from django.urls import path
from .views import ChatView

urlpatterns = [
    path("api/chat/", ChatView.as_view(), name="chat"),
]

This works fine for short responses, but it ties up a Django worker for the full duration of the Claude request. For anything beyond a quick prototype, you want either background processing or streaming.

Streaming responses from Django

Claude supports server-sent events for streaming tokens as they're generated, which matters for chat UIs where users expect text to appear progressively rather than after a multi-second wait. Django can proxy this using StreamingHttpResponse:

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

class StreamChatView(View):
    def post(self, request):
        body = json.loads(request.body)
        user_message = body.get("message", "")

        def event_stream():
            with requests.post(
                settings.CLAUDE_API_URL,
                headers={
                    "Authorization": f"Bearer {settings.CLAUDE_API_KEY}",
                    "Content-Type": "application/json",
                },
                json={
                    "model": "claude-sonnet-4",
                    "max_tokens": 1024,
                    "stream": True,
                    "messages": [{"role": "user", "content": user_message}],
                },
                stream=True,
                timeout=60,
            ) as resp:
                for line in resp.iter_lines():
                    if line:
                        yield line.decode("utf-8") + "\n\n"

        return StreamingHttpResponse(
            event_stream(), content_type="text/event-stream"
        )

A few things to watch for with this pattern:

If you're on Django 4.1+, an async view with httpx.AsyncClient avoids tying up a worker thread at all, which scales better under concurrent chat sessions.

Error handling and retries

Claude API calls can fail for reasons outside your control — rate limits, transient network issues, oversized payloads. Wrap requests with retry logic rather than letting a single failed call surface as a 500:

import time
import requests

def call_claude_with_retry(payload, headers, url, max_retries=3):
    for attempt in range(max_retries):
        try:
            resp = requests.post(url, headers=headers, json=payload, timeout=30)
            if resp.status_code == 429:
                time.sleep(2 ** attempt)
                continue
            resp.raise_for_status()
            return resp.json()
        except requests.RequestException:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)

Log the request_id or equivalent header from each response — it's the first thing you'll need if you have to debug a failed call later.

Skipping the plumbing with SubToAPI

Everything above works regardless of which Claude-compatible endpoint you call. If you'd rather not manage raw API keys, rate-limit backoff, or usage tracking yourself, SubToAPI gives you an HTTPS API with application keys (sub_live_...), built-in streaming support, and usage metadata per request — so your Django views stay almost identical to the examples above, just pointed at https://api.subtoapi.app/v1/messages.

Check the quickstart for the full request/response shape, docs/messages for the Messages endpoint reference, and docs/streaming if you're implementing the SSE view above. Team plans also add per-seat keys, which is useful if multiple developers or services are calling Claude from the same Django project and you want usage broken out per key rather than sharing one credential. Pricing starts at €9/month for solo use — see /pricing — and you can try it from /signup without rewriting your views later.

Testing your integration

Mock the outbound HTTP call in your Django tests rather than hitting the real API:

from unittest.mock import patch
from django.test import TestCase

class ChatViewTests(TestCase):
    @patch("myapp.views.requests.post")
    def test_chat_view_returns_reply(self, mock_post):
        mock_post.return_value.json.return_value = {
            "content": [{"text": "Hello back"}]
        }
        mock_post.return_value.raise_for_status = lambda: None

        response = self.client.post(
            "/api/chat/", {"message": "hi"}, content_type="application/json"
        )
        self.assertEqual(response.json()["reply"], "Hello back")

This keeps your test suite fast and avoids burning API quota on CI runs.

questions

Does Django need any special package to call the Claude API? No. The requests library (or httpx for async views) is enough — Claude API calls are standard HTTPS requests with a JSON body, no provider-specific SDK required.

Can Django stream Claude's token-by-token output to the browser? Yes, using StreamingHttpResponse with the Claude API's stream: true option, as shown above. Make sure your reverse proxy and WSGI worker type don't buffer the response.

Should I call the Claude API directly or through a gateway like SubToAPI? Calling it directly works fine for prototypes. For production apps with multiple developers or services, a gateway that provides per-key usage tracking and team seats — like SubToAPI — reduces the operational overhead of managing raw credentials inside Django settings.

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 →