📜 ⬆️ ⬇️

Web API using the Django REST framework

Web service (English web service) - a software system that is identified by a web address with standardized interfaces. Web services can communicate with each other and with third-party applications through messages based on specific protocols (XML, JSON, etc.). A web service is a unit of modularity when using a service-oriented application architecture.

One of the approaches to create a web service is rest.
Rest (abbreviated English. Representational State Transfer, “transfer of the state of representation”) is the style of building the architecture of a distributed application. Data in REST should be transmitted in the form of a small number of standard formats (for example, HTML, XML, JSON). The network protocol (like HTTP) should support caching, should not depend on the network layer, and should not store state information between request-response pairs. It is argued that such an approach ensures the scalability of the system and allows it to evolve with new requirements.


Django REST framework is a handy tool for working with rest based on the ideology of the Django framework.
')
Environmental Requirements:
Python (2.6, 2.7)
Django (1.3, 1.4, 1.5)

Optional:
Markdown
Pyyaml
django-filter

Installation

You can install the usual command for us pip:
pip install djangorestframework 

And you can put additional packages:
 pip install markdown pip install pyyaml pip install django-filter 


Or do a clone project with Github:
 git clone git@github.com:tomchristie/django-rest-framework.git cd django-rest-framework pip install -r requirements.txt pip install -r optionals.txt 


Do not forget to register the application in INSTALLED_APPS:
 INSTALLED_APPS = ( ... 'rest_framework', ) 


And also add an entry to urls.py:
 urlpatterns = patterns('', ... url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ) 

You can set any URL to your taste, the main thing is to connect the rest framework (rest_framework.urls) URL file.

Usage example

Create an API to work with users and their groups.

First we need to define some Serializers that we will use

 from django.contrib.auth.models import User, Group, Permission from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): permissions = serializers.ManySlugRelatedField( slug_field='codename', queryset=Permission.objects.all() ) class Meta: model = Group fields = ('url', 'name', 'permissions') 


Prescribe views.py

 from django.contrib.auth.models import User, Group from rest_framework import generics from rest_framework.decorators import api_view from rest_framework.reverse import reverse from rest_framework.response import Response from quickstart.serializers import UserSerializer, GroupSerializer @api_view(['GET']) def api_root(request, format=None): """ The entry endpoint of our API. """ return Response({ 'users': reverse('user-list', request=request), 'groups': reverse('group-list', request=request), }) class UserList(generics.ListCreateAPIView): """ API endpoint that represents a list of users. """ model = User serializer_class = UserSerializer class UserDetail(generics.RetrieveUpdateDestroyAPIView): """ API endpoint that represents a single user. """ model = User serializer_class = UserSerializer class GroupList(generics.ListCreateAPIView): """ API endpoint that represents a list of groups. """ model = Group serializer_class = GroupSerializer class GroupDetail(generics.RetrieveUpdateDestroyAPIView): """ API endpoint that represents a single group. """ model = Group serializer_class = GroupSerializer 

We have created the api_root function, which will be the starting point for our API. And four classes, to communicate with the models and indicate which serializers should be used.

Add links to urls.py

 from django.conf.urls import patterns, url, include from rest_framework.urlpatterns import format_suffix_patterns from quickstart.views import UserList, UserDetail, GroupList, GroupDetail urlpatterns = patterns('quickstart.views', url(r'^$', 'api_root'), url(r'^users/$', UserList.as_view(), name='user-list'), url(r'^users/(?P<pk>\d+)/$', UserDetail.as_view(), name='user-detail'), url(r'^groups/$', GroupList.as_view(), name='group-list'), url(r'^groups/(?P<pk>\d+)/$', GroupDetail.as_view(), name='group-detail'), ) # Format suffixes urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api']) # Default login/logout views urlpatterns += patterns('', url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ) 

The important point is the use of user-detail and group-detail. For correct communication with views.py, you need to use the naming of the form {modelname} -detail.
In format_suffix_patterns we specified the suffix for our urls.

Settings

 INSTALLED_APPS = ( ... 'rest_framework', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), 'PAGINATE_BY': 10 } 


Result

Using curl in the console, let's test what happened:
 bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ { "count": 2, "next": null, "previous": null, "results": [ { "email": "admin@example.com", "groups": [], "url": "http://127.0.0.1:8000/users/1/", "username": "admin" }, { "email": "tom@example.com", "groups": [ ], "url": "http://127.0.0.1:8000/users/2/", "username": "tom" } ] } 


In the browser you can see something like this:


References:
Project site
Github

PS To work with rest in django there is one more not bad application called as django-piston . If you wish, you can write about it, although in use it is not quite complicated.

Source: https://habr.com/ru/post/160117/


All Articles