InterviewSolution
| 1. |
How to Create APIs in Django? |
|
Answer» Django is known for MVC(model, view, controller) web framework, but it can be used to build a backend that is an API. Let us see STEP by step process for creating API 1. Installation Install Django and Django REST Framework by creating a virtual environment.
Now create project tutorial and inside project create an app quickstart. $ django-admin.py startproject tutorial $ cd samplelibrary $ django-admin.py startapp quickstartNow let us create and apply schema migration by executing following - $ python manage.py makemigrations $ python manage.py migrateNow create a user with user name 'admin' and password 'password123' python manage.py createsuperuser --email admin@example.com --username admin 2. Create Serializer Serializers are used to convert data from one format to another. For example to convert formats like JSON, XML to complex data types like querysets and model instances and vice versa. Now create a new module named tutorial/quickstart/serialisers.py for data presentations. //serialisers.py from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name')Here we are USING hyperlinked RELATIONS with HyperlinkedModelSerializer as hyperlinking is good RESTful design. 3. Views Viewsets are classes that provide the functionality of a SET of views. Now create a UserViewSet class based on ModelViewSet in a views.py file of quickstart app. //views.py from django.contrib.auth.models import User, Group from rest_framework import viewsets from tutorial.quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializerRather than WRITING multiple views, here we are grouping together all the common behavior into classes called ViewSets. 4. URLs Let us write up the API URLs. //urls.py from django.urls import include path from rest_framework import routers from tutorial.quickstart import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # for browsable API, we include login URLs. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]Here we are using viewsets instead of views so that we can automatically generate the URL conf for our API by registering viewset with a router class. Also, we are including a default login and logout view for use with browsable API. 5. Pagination Pagination controls how many objects per page to return. Add below lines to settings.py //settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } Settings Now add 'rest_framework' to INSTALLED_APPS in settings module. //settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #app 'quickstart', #rest_framework 'rest_framework', )Let us test the API we have built. start server from the command line. $ python manage.py runserverNow we can access our API from the command-line tool |
|