A business application's API is a long-term contract with mobile apps, partner integrations, and your own future frontend. Design it carelessly and every mistake becomes permanent, because someone depends on it. Design it well and new features slot in without breaking anyone. This guide covers the patterns we use for Django business apps built on Django REST Framework (DRF): authentication, versioning, pagination, error handling, filtering, webhooks, rate limiting, and documentation.
It complements our article on API integration patterns in Django, which focuses on consuming third-party APIs. Here we look at designing your own.
- Authentication: JWT vs Token vs Session
- Error handling: one consistent envelope
- Webhook design
- Putting it together
Authentication: JWT vs Token vs Session
The right choice depends on who calls your API.
| Method | Best for | Pros | Cons |
|---|---|---|---|
| Session (cookie) | Same-domain web frontends, HTMX apps | Built in, CSRF protection, easy revocation | Awkward for mobile and third parties |
| Token (DRF TokenAuthentication) | Server-to-server, simple integrations | Simple, revocable, one DB lookup | No expiry by default, one token per user |
| JWT | Mobile apps, SPAs, microservices | Stateless, carries claims, short-lived | Hard to revoke, needs refresh flow |
For most business apps we use sessions for the first-party web UI and either tokens or short-lived JWTs with refresh tokens for external clients. Never put secrets in JWT payloads; they are only encoded, not encrypted.
Versioning: URL vs header
Put the version in the URL path, as in /api/v1/invoices/. It is visible, cacheable, easy to test in a browser, and simple to route. Header-based versioning is cleaner in theory but harder for clients and logs. DRF supports both through URLPathVersioning and AcceptHeaderVersioning. Only introduce v2 for breaking changes; adding fields is not breaking. Announce deprecation with a Sunset header and a timeline.
Offset pagination (?page=3) is simple but gets slower on large tables and gives inconsistent results when rows are inserted during paging.
Pagination: cursor vs offset
Offset pagination (?page=3) is simple but gets slower on large tables and gives inconsistent results when rows are inserted during paging. Cursor pagination uses an opaque pointer to the last item and stays fast and consistent, which is why it suits feeds and activity logs. Use PageNumberPagination for admin-style lists with total counts, and CursorPagination for large, append-heavy datasets.
from rest_framework.pagination import CursorPagination
class ActivityPagination(CursorPagination):
page_size = 50
ordering = "-created_at"
Use PageNumberPagination for admin-style lists with total counts, and CursorPagination for large, append-heavy datasets.
Error handling: one consistent envelope
Clients should never have to guess the shape of an error. Use a custom exception handler that wraps every error in the same structure:
{
"error": {
"code": "validation_error",
"message": "One or more fields are invalid.",
"details": {"email": ["Enter a valid email address."]},
"request_id": "9f1c2b..."
}
}
Use correct HTTP status codes: 400 for validation, 401 for unauthenticated, 403 for forbidden, 404 for missing, 409 for conflicts, 429 for rate limits. Include a request ID in every response, so support can trace issues in logs.
Filtering and search
Use django-filter with DRF's DjangoFilterBackend for exact and range filters, SearchFilter for text search, and OrderingFilter with an explicit whitelist of orderable fields. Always restrict the base queryset to what the current user may see before filters apply. This is the most common source of data leaks in multi-tenant apps; our article on SaaS architecture in Django explains tenant-scoped querysets in detail. Also use select_related and prefetch_related in viewsets to avoid N+1 queries.
Want expert help with this? Let's make it happen.
Get a Free ConsultationWebhook design
Webhooks let your system notify others when something happens. Done well, they are reliable. Done badly, they silently drop events.
- Sign every payload. Compute an HMAC-SHA256 of the raw body with a per-endpoint secret and send it in a header. Include a timestamp to prevent replay.
- Deliver asynchronously. Enqueue deliveries in a task queue; never call external URLs inside a request cycle.
- Retry with exponential backoff. For example 1 minute, 5 minutes, 30 minutes, 2 hours, 12 hours, then mark failed.
- Include an event ID so receivers can deduplicate, because delivery is at-least-once.
- Log every attempt with status code and response time, and expose a delivery log to customers.
import hmac, hashlib
def sign(secret: bytes, body: bytes, timestamp: str) -> str:
msg = timestamp.encode() + b"." + body
return hmac.new(secret, msg, hashlib.sha256).hexdigest()
Rate limiting
Use DRF throttling classes (UserRateThrottle, ScopedRateThrottle) backed by Redis. Set stricter limits for expensive endpoints like exports and search. Return 429 with a Retry-After header and expose remaining quota in response headers.
Documentation with drf-spectacular
An undocumented API is an unfinished API. drf-spectacular generates an OpenAPI 3 schema directly from your serializers and viewsets, and serves Swagger UI or Redoc. Add extend_schema annotations for examples and error responses, and run schema generation in CI to catch accidental breaking changes. Treat the schema as the contract.
Putting it together
These patterns matter most in systems that grow, like the CRM described in our post on building a CRM from scratch. Establish the conventions early: one error envelope, one pagination style per resource type, URL versioning, and signed webhooks. If you need an API designed, built, or audited, our API integration service covers both sides of the contract.
Related reading: API Integration Patterns for Django Applications | SaaS Architecture in Django: Billing, Tenancy, Scale | Building a CRM from Scratch: Architecture Decisions
Need a clean, well-documented API for your business application? Explore my API integration service or get in touch for a free consultation.



Frequently Asked Questions
Should I use JWT or session authentication for my Django API?
Use session authentication for same-domain web frontends and JWT or tokens for mobile apps and third-party clients. JWT is stateless but harder to revoke, so keep access tokens short-lived and use refresh tokens.
How should I version a REST API?
Include the version in the URL, such as /api/v1/, and only release a new major version for breaking changes. Announce deprecations early and use Sunset headers to give clients a timeline.
How do I make webhooks reliable?
Sign payloads with HMAC, deliver them asynchronously through a queue, retry with exponential backoff, include unique event IDs for deduplication, and log every delivery attempt.
Full-stack разработчик, специализирующийся на Django, ИИ-автоматизации и управлении Google Ads. Создаю production SaaS платформы и кастомные веб-приложения для бизнеса по всей территории США.