Django Rest Framework Setup

Requirements

I assume that you have followed the 2 tutorials Docker Compose for Django and Django Tutorial User Input with Forms.

Goals

By the end of this tutorial you will learn about Django Frameworks and set up an API using the data_entry app we have been building.

Steps

  • Modify the requirements.txt file and add the following packages:
djangorestframework
markdown
django-filter
  • add rest_framework into the INSTALLED_APPS variable in the project's settings.py file.
  • Add the following into the urlpatterns variable inside the root urls.py file:
url(r'^route/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
  • Next add the following variable into the project's settings.py file:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES':[
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
  • We are ready to build our API but first we need to add some more classes into the root urls.py file. Below are the additional lines of code required to complete the tutorial:
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model=User
fields = ('url', 'username', 'email', 'is_staff')

class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class=UserSerializer

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

..Same content as before ..
  • You can now view your API in your browser by navigating to your docker-machine's ip address at port 8000 with path /route. eg. <docker-machine ip>:8000/route

Conclusion

Checkout my next tutorial, Django Rest Framework Serialization Tutorial, to learn how to extend the app further and serialize and deserialze data.

Subscribe to our mailing list

* indicates required