Start Your API - django-rest-framework part 1

In this video we start creating our API by learning what it takes to put data in our database, and retrieve it back doing all of our CRUD operations. django-rest-framework makes it very simple to accomplish with a minimal amount of effort.


Command Line

curl http://localhost:9000/api/tasks/
curl -X POST http://localhost:9000/api/tasks/ -d "title=hello world&description=a whole new world"
curl -X PUT http://localhost:9000/api/tasks/1 -d "title=hello world&description=be nice"
curl -X PUT http://localhost:9000/api/tasks/1 -d "title=hello world&description=be nice&completed=True"
curl -X DELETE http://localhost:9000/api/tasks/1


from django.conf.urls import patterns, url

urlpatterns = patterns(
    url(r'^tasks/$', 'task_list', name='task_list'),
    url(r'^tasks/(?P<pk>[0-9]+)$', 'task_detail', name='task_detail'),
from django.db import models

class Task(models.Model):
    completed = models.BooleanField(default=False)
    title = models.CharField(max_length=100)
    description = models.TextField()
from rest_framework import serializers

from task.models import Task

class TaskSerializer(serializers.ModelSerializer):

    class Meta:
        model = Task
        fields = ('title', 'description', 'completed')
from django.conf.urls import patterns, include, url

from django.contrib import admin

urlpatterns = patterns(
    url(r'^api/', include('api.urls')),
    url(r'^admin/', include(,
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from task.models import Task
from api.serializers import TaskSerializer

@api_view(['GET', 'POST'])
def task_list(request):
    List all tasks, or create a new task.
    if request.method == 'GET':
        tasks = Task.objects.all()
        serializer = TaskSerializer(tasks, many=True)
        return Response(

    elif request.method == 'POST':
        serializer = TaskSerializer(data=request.DATA)
        if serializer.is_valid():
            return Response(, status=status.HTTP_201_CREATED)
            return Response(
                serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def task_detail(request, pk):
    Get, udpate, or delete a specific task
        task = Task.objects.get(pk=pk)
    except Task.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = TaskSerializer(task)
        return Response(

    elif request.method == 'PUT':
        serializer = TaskSerializer(task, data=request.DATA)
        if serializer.is_valid():
            return Response(
            return Response(
                serilizer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        return Response(status=status.HTTP_204_NO_CONTENT)
comments powered by Disqus