An introduction to the Django REST Framework, given at Djangocon US 2014.
The video for the talk is available here: https://www.youtube.com/watch?v=cqP758k1BaQ
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. Common HTTP Response Codes
200 - OK
201 - Created
401 - Not Authorized
404 - Not Found
500 - Server Error
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.
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. And a ModelSerializer
class TweetSerializer(serializers.ModelSerializer):
user = serializers.Field(source='user')
class Meta:
model = Tweet
fields = ('text', 'user', 'timestamp')
11. The Result
[
{
"text": "Bob is the coolest name EVAR",
"user": "bob",
"timestamp": "2014-08-29T18:51:19Z"
}
]
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
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
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.
22. Responses
DRF Responses are unrendered.
Return DATA, and status code.
Behind the scenes:
serializer = TweetSerializer(tweets, many=True)
return Response(serializer.data)
29. 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 = self.client.post(url, data, format='json')
error_msg = response.data['text'][0]
self.assertEquals(response.status_code, 400)
self.assertEquals(error_msg, 'Text is too short!')
30. When to use it?
New projects.
- You don’t have to code for the framework,
but it’s easier to integrate.
Clean models.
31. 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.
32. Doesn’t mean you shouldn’t go for it it, but
prepare for hurdles.
33. Next Steps
pip install djangorestframework
Also, the documentation rocks.
http://www.django-rest-framework.org/