Skip to main content

Django AWS API Gateway WebSockets

CI Build Status Coverage PyPI Read the Docs Python Django License

Django AWS API Gateway WebSockets lets Django projects use AWS API Gateway WebSocket APIs without running a dedicated WebSocket server.

AWS API Gateway manages the WebSocket connection. Django receives API Gateway events as normal HTTP requests and can send messages back to connected clients through the AWS API Gateway Management API.

This project is designed for Django applications that want WebSocket-style features while keeping a traditional Django request/response deployment model.

Documentation

Full documentation is available on Read the Docs:

https://django-aws-api-gateway-websockets.readthedocs.io/

Useful starting points:

Features

  • Handle AWS API Gateway WebSocket events with Django class-based views.
  • Track WebSocket connections in the Django database.
  • Associate connections with Django users where available.
  • Group connections using channels.
  • Send messages to:
    • one connection;
    • all connections for a user;
    • all connections in a channel;
    • all connected clients.
  • Create and manage API Gateway resources from Django Admin or management commands.
  • Add custom API Gateway routes for different Django views.
  • Use WebSocket tokens for authenticated connection protection.
  • Rate limit WebSocket connection attempts.
  • Restrict handlers using Django permissions.
  • Use mixins to add WebSocket connection details to template context.

When to use this package

Use this package if you want:

  • AWS API Gateway to manage WebSocket connections;
  • Django to receive WebSocket events as HTTP requests;
  • to avoid running a dedicated ASGI WebSocket server;
  • to send messages from Django to connected browser clients;
  • to group connections into channels for multicast messaging;
  • to integrate WebSocket behaviour with existing Django models, views, admin, permissions, and management commands.

This package is not a replacement for Django Channels. Django Channels is a better fit if you want Django itself to run an ASGI WebSocket server.

Requirements

  • Python 3.10+
  • Django 5.2+
  • AWS account with API Gateway permissions
  • Boto3-compatible AWS credentials or IAM role

See the installation guide and AWS IAM setup guide for details.

Installation

Install from PyPI:

pip install django-aws-api-gateway-websockets

Add the app to INSTALLED_APPS:

INSTALLED_APPS += ["django-aws-api-gateway-websockets"]

Run migrations:

python manage.py migrate

See the full quickstart for a working example.

Minimal example

Add a Django URL route with a route slug:

from django.urls import path

from .views import ExampleWebSocketView

urlpatterns = [
    path(
        "ws/<slug:route>",
        ExampleWebSocketView.as_view(),
        name="example_websocket",
    ),
]

Create a WebSocket view:

from django.http import JsonResponse
from django_aws_api_gateway_websockets.views import WebSocketView


class ExampleWebSocketView(WebSocketView):
    def default(self, request, *args, **kwargs):
        self.websocket_session.send_message({})
        return JsonResponse({"ok": True})

Create a WebSocket view:

from django.http import JsonResponse

from django_aws_api_gateway_websockets.views import WebSocketView


class ExampleWebSocketView(WebSocketView):
    def default(self, request, *args, **kwargs):
        self.websocket_session.send_message(
            {
                "type": "reply",
                "message": "Hello from Django",
            }
        )

        return JsonResponse({"ok": True})

Connect from the browser:

const socket = new WebSocket("wss://ws.example.com?channel=example");

socket.onmessage = function (event) {
    const message = JSON.parse(event.data);
    console.log("Received:", message);
};

socket.onopen = function () {
    socket.send(JSON.stringify({
        action: "default",
        message: "Hello from the browser"
    }));
};

For production usage, read the documentation on WebSocket tokens and security.

AWS setup

The package can create and configure API Gateway WebSocket resources using Django Admin actions or management commands. Typical setup steps:

  1. Configure AWS credentials or an IAM role.
  2. Create an record. ApiGateway
  3. Create the AWS API Gateway.
  4. Optionally create a custom domain.
  5. Configure DNS.
  6. Connect from your frontend client.

See the full API Gateway setup guide.

Management commands

The package includes management commands for API Gateway setup and cleanup.

python manage.py createApiGateway --pk=<api_gateway_pk>
python manage.py createCustomDomain --pk=<api_gateway_pk>
python manage.py clearWebSocketSessions
python manage.py cleanupWebSocketTokens

See the management commands documentation for details.

Security

Version 3.0.0 introduced significant security improvements, including:

  • WebSocket token protection;
  • single-use session-bound connection tokens;
  • connection attempt rate limiting;
  • handler whitelisting;
  • Django permission checks;
  • stricter input validation;
  • channel name validation;
  • message size validation;
  • safer debug output;
  • audit logging for admin actions.

For authenticated production WebSocket endpoints, read:

To report a vulnerability, see SECURITY.md.

Development

Clone the repository:

git clone https://github.com/StevenMapes/django-aws-api-gateway-websockets.git
cd django-aws-api-gateway-websockets

Install development requirements into your virtual environment. Run tests:

pip install pytest-django
coverage erase
python -W error::DeprecationWarning -W error::PendingDeprecationWarning -m coverage run --parallel -m pytest --ds tests.settings
coverage combine
coverage report

Build the documentation locally:

cd docs
pip install -r requirements.txt
make html

See the contributing guide for more information.

Changelog

See the changelog for release history.

License

This project is licensed under the MIT License. See LICENSE.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_aws_api_gateway_websockets-4.0.0.tar.gz (168.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

File details

Details for the file django_aws_api_gateway_websockets-4.0.0.tar.gz.

File metadata

File hashes

Hashes for django_aws_api_gateway_websockets-4.0.0.tar.gz
Algorithm Hash digest
SHA256 edbd198807fdb3ac01909141af7f4e7e55101dc3bdfee9e0a27f4075d692247d
MD5 7d36e5e85b572de5fa841f95a15a68cd
BLAKE2b-256 263a93d27fc36ad17f63b452d832e5c826af107023c7012fb8755e80788baadb

See more details on using hashes here.

File details

Details for the file django_aws_api_gateway_websockets-4.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_aws_api_gateway_websockets-4.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8f0b0fdcf40cc023cb46168b947b11131b56840cbeb961f9d0c55eb4246afd39
MD5 d147cc7619c82fcdf2a25dcfdd231c55
BLAKE2b-256 2dce13bb64911951d056af9b67d5d49f60c06047bf60e9b5f974fd53e5a61d00

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

4.0.0 This release

2 files

3.1.1

2 files

3.1.0

2 files

3.0.4

2 files

3.0.3

2 files

3.0.2

2 files

3.0.1

2 files

3.0.0

2 files

2.2.2

1 file

2.2.1

1 file

2.2.0

1 file

2.1.1

1 file

2.1.0

1 file

2.0.2

1 file

2.0.1

1 file

2.0.0

1 file

1.4.1

1 file

1.4.0

1 file

1.3.0

1 file

1.2.1

1 file

1.2.0

1 file

1.1.3

1 file

1.1.2

1 file

1.1.1

1 file

1.1.0

1 file

1.0.22

1 file

1.0.21

1 file

1.0.20

1 file

1.0.19

1 file

1.0.18

1 file

1.0.17

1 file

1.0.16

1 file

1.0.15

1 file

1.0.14

1 file

1.0.13

2 files

1.0.12

1 file

1.0.11

1 file

1.0.10

1 file

1.0.9

1 file

1.0.8

1 file

1.0.7

1 file

1.0.6

1 file

1.0.5

1 file

1.0.4

1 file

1.0.3

1 file

1.0.2

1 file

0.2.2

1 file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page