Skip to main content

Helps build a RESTful API on top of WebSockets using channels.

Project description

Channels API

https://travis-ci.org/linuxlewis/channels-api.svg?branch=master

Channels API exposes a RESTful Streaming API over WebSockets using channels. It provides a ResourceBinding which is comparable to Django Rest Framework’s ModelViewSet. It is based on DRF serializer classes.

It requires Python 3, Channels >0.17.3, Django >1.8, and Django Rest Framework 3.0

Table of Contents

How does it work?

The API builds on top of channels’ WebsocketBinding class. It works by having the client send a stream and payload parameters. This allows us to route messages to different streams (or resources) for a particular action. So POST /user would have a message that looks like the following

var msg = {
  stream: "users",
  payload: {
    action: "create",
    data: {
      email: "test@example.com",
      password: "password",
    }
  }
}

ws.send(JSON.stringify(msg))

Why?

You’re already using Django Rest Framework and want to expose similar logic over WebSockets.

WebSockets can publish updates to clients without a request. This is helpful when a resource can be edited by multiple users across many platforms.

Getting Started

This tutorial assumes you’re familiar with channels and have completed the Getting Started

  • Add channels_api to requirements.txt

pip install channels_api
  • Add channels_api to INSTALLED_APPS

INSTALLED_APPS = (
    'rest_framework',
    'channels',
    'channels_api'
)
  • Add your first resource binding

# polls/bindings.py

from channels_api.bindings import ResourceBinding

from .models import Question
from .serializers import QuestionSerializer

class QuestionBinding(ResourceBinding):

    model = Question
    stream = "questions"
    serializer_class = QuestionSerializer
    queryset = Question.objects.all()
  • Add a WebsocketDemultiplexer to your channel_routing

# proj/routing.py


from channels.generic.websockets import WebsocketDemultiplexer
from channels.routing import route_class

from polls.bindings import QuestionBinding

class APIDemultiplexer(WebsocketDemultiplexer):

    consumers = {
      'questions': QuestionBinding.consumer
    }

channel_routing = [
    route_class(APIDemultiplexer)
]

That’s it. You can now make REST WebSocket requests to the server.

var ws = new WebSocket("ws://" + window.location.host + "/")

ws.onmessage = function(e){
    console.log(e.data)
}

var msg = {
  stream: "questions",
  payload: {
    action: "create",
    data: {
      question_text: "What is your favorite python package?"
    },
    request_id: "some-guid"
  }
}
ws.send(JSON.stringify(msg))
// response
{
  stream: "questions",
  payload: {
    action: "create",
    data: {
      id: "1",
      question_text: "What is your favorite python package"
    }
    errors: [],
    response_status: 200
    request_id: "some-guid"
  }
}
  • Add the channels debugger page (Optional)

This page is helpful to debug API requests from the browser and see the response. It is only designed to be used when DEBUG=TRUE.

# proj/urls.py

from django.conf.urls import include

    urlpatterns = [
        url(r'^channels-api/', include('channels_api.urls'))
    ]

ResourceBinding

By default the ResourceBinding implements the following REST methods:

  • create

  • retrieve

  • update

  • list

  • delete

  • subscribe

See the test suite for usage examples for each method.

List Pagination

Pagination is handled by django.core.paginator.Paginator

You can configure the DEFAULT_PAGE_SIZE by overriding the settings.

# settings.py

CHANNELS_API = {
  'DEFAULT_PAGE_SIZE': 25
}

Subscriptions

Subscriptions are a way to programmatically receive updates from the server whenever a resource is created, updated, or deleted

By default channels-api has implemented the following subscriptions

  • create a Resource

  • update any Resource

  • update this Resource

  • delete any Resource

  • delete this Resource

To subscribe to a particular event just use the subscribe action with the parameters to filter

// get an event when any question is updated

var msg = {
  stream: "questions",
  payload: {
    action: "subscribe",
    data: {
      action: "update"
    }
  }
}

// get an event when question(1) is updated
var msg = {
  stream: "questions",
  payload: {
    action: "subscribe"
    data: {
      action: "update",
      pk: "1"
    }
  }
}

Roadmap

  • 0.4
    • Permissions

    • Custom Methods

    • Test Project

Project details


Download files

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

Source Distribution

channels_api-0.3.0.tar.gz (9.0 kB view details)

Uploaded Source

Built Distribution

channels_api-0.3.0-py3-none-any.whl (13.4 kB view details)

Uploaded Python 3

File details

Details for the file channels_api-0.3.0.tar.gz.

File metadata

File hashes

Hashes for channels_api-0.3.0.tar.gz
Algorithm Hash digest
SHA256 124a2e9dae4398c2b3e1b0316ea8e4a4abd712e4086ec87a193b85ee411d1d46
MD5 4c0eb173f348a988fbbd4e31ec44a30a
BLAKE2b-256 df8bd196561c9d5c34cb2b09452e3496d6400e59f6e8f882474e7857c67ac001

See more details on using hashes here.

File details

Details for the file channels_api-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for channels_api-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0fde3f2e9ac89dae201ea51f7665762fb10102bec0a781953a1e9c300c874103
MD5 c5b6f90ac17d12bcb858e8683064a6fd
BLAKE2b-256 22ce9452ad8ef5583e236719184e1af389d75e9a57d8c688e3f5de55c961c2ee

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page