Building  A REST API Using Django Rest Framework

Twitter @PabloVallejo_

GitHub /PabloVallejo





Gillie


Fun

What is a Web API?




"Programmatic interface to a defined request-response message system"


Benefits of an API




  • Abstract the way data is managed 

  • Standardize data access

  • Access data from multiple devices

  • Separate presentation from logic  




Data Types


JSON
{
  "title": "First Todo",
  "completed": "false"
}


XML
<title>First Todo</title>
<completed>false</completed>

Architectures



SOAP

XML Based. Standardized responses.

REST
Representation State Transfer

What is REST?


Representation State Transfer


GET Retrieve data
POST Create a resource
PUT Update a resource
DELETE Delete a resource


Get all users
GET /users/

Create a new user

POST /users/

Update a user
PUT /users/1

Delete a user
DELETE /users/1

The Framework




Serializers

Prepare Django data to be returned in a HTTP response.

from rest_framework import serializers
from task.models import Task

class TaskSerializer( serializers.ModelSerializer ):
    """
    Serializer to parse Task data
    """

    class Meta:
		model = Task
		fields = ( 'title', 'completed', 'id' )

Views
Useful classes to remove boilerplate

class TaskMixin(object):
    """
    Mixin to inherit from.
    Here we're setting the query set and the serializer
    """
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

class TaskList(TaskMixin, ListCreateAPIView):
    """
    Return a list of all the tasks, or
    create new ones
    """
    pass

class TaskDetail(TaskMixin, RetrieveUpdateDestroyAPIView):
    """
    Return a specific task, update it, or delete it.
    """
    pass

Generic Views



CreateAPIView

ListAPIView

RetrieveAPIView

DestroyAPIView

UpdateAPIView

ListCreateAPIView

RetrieveUpdateAPIView

RetrieveDestroyAPIView

RetrieveUpdateDestroyAPIView

Browseable API


Documentation


Resources

Demo!


Todo's app on GitHub

Repository
https://github.com/AxiaCore/todomvc-django

Clone URL
https://github.com/AxiaCore/todomvc-django.git

Building A Restful API

By pablovallejo

Building A Restful API

Building a Restful API using Django Rest Framework is a presentation covering the basics of creating an API using Django.

  • 4,626