Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes


Published on

An introduction to the Django REST Framework, given at Djangocon US 2014.

The video for the talk is available here:

Published in: Technology
  • Sex in your area is here: ♥♥♥ ♥♥♥
    Are you sure you want to  Yes  No
    Your message goes here
  • Dating for everyone is here: ♥♥♥ ♥♥♥
    Are you sure you want to  Yes  No
    Your message goes here

Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes

  1. 1. APIS with Django Rest Framework So easy, you can learn it in 25 minutes. (No, seriously)
  2. 2. REST Describes an architecture For the purpose of web apis: - stateless - support common HTTP methods - return internet media type (JSON or XML…)
  3. 3. HTTP Verbs POST, GET, (PUT, PATCH), DELETE Like CRUD… sort of.
  4. 4. What do REST endpoints look like? /api/users/ - GET will return a collection of all users /api/users/<id> - GET will return a single user
  5. 5. Common HTTP Response Codes 200 - OK 201 - Created 401 - Not Authorized 404 - Not Found 500 - Server Error
  6. 6. Idempotency Is a hard to pronounce word. The operation will produce the same result, no matter how many times it is repeated. PUT, DELETE - Idempotent. GET - Safe method. Produces no side effects.
  7. 7. Where DRF Comes in It makes REST API creation easy!
  8. 8. Serializers
  9. 9. A Model class Tweet(models.Model): user = models.ForeignKey(User) text = models.CharField(max_length=140) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-timestamp']
  10. 10. And a ModelSerializer class TweetSerializer(serializers.ModelSerializer): user = serializers.Field(source='user') class Meta: model = Tweet fields = ('text', 'user', 'timestamp')
  11. 11. The Result [ { "text": "Bob is the coolest name EVAR", "user": "bob", "timestamp": "2014-08-29T18:51:19Z" } ]
  12. 12. Validation
  13. 13. Field Validation def validate_text(self, attrs, source): value = attrs[source] if len(value) < 5: raise serializers.ValidationError( "Text is too short!") return attrs
  14. 14. Permissions
  15. 15. Permissions IsAuthenticated - Only allow authenticated Users IsAdminUser - user.is_staff is True class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.user == request.user
  16. 16. Views
  17. 17. ModelViewSets class TweetViewSet(viewsets.ModelViewSet): queryset = Tweet.objects.all() serializer_class = TweetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly,) def pre_save(self, obj): obj.user = self.request.user
  18. 18. Generic Views APIView is base class. Takes care of routing. Mixins provide common operations, and generic Views provide common combinations of mixins. ex: ListCreateAPIView, UpdateAPIView
  19. 19. Requests
  20. 20. Requests The DRF Request provides many methods we are used to seeing. request.DATA is similar to request.POST It handles data types we specified, and is available on all requests.
  21. 21. Responses
  22. 22. Responses DRF Responses are unrendered. Return DATA, and status code. Behind the scenes: serializer = TweetSerializer(tweets, many=True) return Response(
  23. 23. Routing
  24. 24. ViewSet Routing router = DefaultRouter() router.register(r'tweets', views.TweetViewSet) router.register(r'users', views.UserViewSet) urlpatterns = patterns('', url(r'^api/', include(router.urls)) )
  25. 25. Browsable API
  26. 26. Unit Testing
  27. 27. Does our validation work? def test_create_invalid_tweet(self): self.client = APIClient() self.client.login(username='bob', password='bob') url = reverse('tweet-list') data = {'text': "x" * 4} response =, data, format='json') error_msg =['text'][0] self.assertEquals(response.status_code, 400) self.assertEquals(error_msg, 'Text is too short!')
  28. 28. When to use it? New projects. - You don’t have to code for the framework, but it’s easier to integrate. Clean models.
  29. 29. When to be cautious (IMHO) Complex models, tons of interdependent validation logic, dealing with saving non- model fields on a model Legacy Django… It’s out there.
  30. 30. Doesn’t mean you shouldn’t go for it it, but prepare for hurdles.
  31. 31. Next Steps pip install djangorestframework Also, the documentation rocks.
  32. 32. Bye Everybody! @nnja