Django REST framework: migrating from 0.x to 2.x¶
We used Django REST framework for a while now. Nothing spectacular yet. In most cases we’re only returning a bit of JSON. We chose Django REST framework over Piston because that one was effectively unmaintained at the time. We chose it over tastypie because of the great way in which Django REST framework presents your API in the browser (the “browseable API” they call it), which is very helpful if you want others to actually use your API!
And… Django REST framework uses Django’s class based views, which we’re using a lot. So it matches the style we want to work with. This was a second thing that gave it an edge over tastypie for us.
Well, anyway, most of our Django REST framework 0.3.3 (or 0.4 or whatever) views looked like this:
from djangorestframework.views import View as JsonView
class SomeView(JsonView):
def get(self, request):
return {'some': 'dictionary',
'or': ['a', 'list']}
JsonView would take care of converting everything that came in/out of the
get() or post() between JSON and whatever Python data structure it
represents. Handy.
Since 30 october, version 2.0 is out. Lots of improvements and, from what I read, a better fit for many projects. But, boy, is it backward incompatible. I thought to do a quick migration…
All the imports have changed from
import djangorestframeworktoimport rest_framework. Well, that’s a sure fire way to make absolutely sure nobody accidentally uses the wrong version.Hey, my
JsonViewis gone! You cannot just spit out a dict or list anymore in your.get()and get it converted automatically. You must wrap it in a specialResponseobject. This is probably needed, but it doesn’t look as nice.
Here’s what the first example looks like in version 2.0:
from rest_framework.views import APIView
from rest_framework.response import Response as RestResponse
class SomeView(APIView):
def get(self, request):
return RestResponse({'some': 'dictionary',
'or': ['a', 'list']})
It works fine, but it lost a bit of its friendliness, at least for such an
utterly simple example. I looked at the documentation, though, and everything
is as simple as JsonView used to be if you work with models. Just two or
three lines of code for basic cases and you’re done.
I’ll have to go through some other apps we made, as everything that uses Django REST framework has to change at the same time. Every single app. There’s no in-between. I’m afraid it’ll be quite a headache…