From b94da2468cdda6b0ad491574d35097d0e336ea7f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 24 Apr 2013 22:40:24 +0100 Subject: Various clean up and lots of docs --- docs/index.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'docs/index.md') diff --git a/docs/index.md b/docs/index.md index d51bbe13..f3abeb6b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -73,6 +73,54 @@ If you're intending to use the browseable API you'll probably also want to add R Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace. +## Example + +Let's take a look at a quick example of using REST framework to build a simple model-backed API. + +We'll create a read-write API for accessing users and groups. + + from django.conf.urls.defaults import url, patterns, include + from django.contrib.auth.models import User, Group + from rest_framework import serializers, viewsets, routers + + + # Serializers control the representations your API exposes. + class UserSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = User + fields = ('url', 'email', 'is_staff', 'groups') + + + class GroupSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = Group + fields = ('url', 'name') + + + # ViewSets define the view behavior. + class UserViewSet(viewsets.ModelViewSet): + queryset = User.objects.all() + serializer_class = UserSerializer + + + class GroupViewSet(viewsets.ModelViewSet): + queryset = Group.objects.all() + serializer_class = GroupSerializer + + + # Routers provide a convienient way of automatically managing your URLs. + router = routers.DefaultRouter() + router.register(r'users', UserViewSet, 'user') + router.register(r'groups', GroupViewSet, 'group') + + + # Wire up our API URLs, letting the router do the hard work. + # Additionally, we include login URLs for the browseable API. + urlpatterns = patterns('', + url(r'^', include(router.urls)), + url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) + ) + ## Quickstart Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework. -- cgit v1.2.3