Writing API Views and URLs
Follow the below steps to write the API views and URLs:
Step 1: Creating views
- Head to views.py and write the following code. The below views are to handle different requests and produce desired output to our API, here we are using function-based views with api_view decorator. The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to.
- To send the output we are using Response(), Unlike regular HttpResponse objects, you do not instantiate Response objects with rendered content. Instead, you pass in unrendered data, which may consist of any Python primitives.
Python3
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Task from .serializers import TaskSerializer @api_view ([ 'GET' ]) def get_all_tasks(request): tasks = Task.objects. all ().order_by( "-task_time" ) serializer = TaskSerializer(tasks, many = True ) return Response(serializer.data, status = status.HTTP_200_OK) @api_view ([ 'GET' ]) def get_task_details(request, pk): task = Task.objects.get( id = pk) serializer = TaskSerializer(task, many = False ) return Response(serializer.data, status = status.HTTP_200_OK) |
- Here we imported the required modules and wrote the first view to get a list of created tasks, first we get tasks using the Task model then we serializer data and return a response with data and 200 status codes.
- Then we created a view to get details of a single task using its id.
Python3
@api_view ([ 'POST' ]) def create_task(request): serializer = TaskSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(status = status.HTTP_400_BAD_REQUEST) |
Above is a view for creating a new task first we need to get data from the request and serialize it if serialized data is valid then simply save the serializer and return desired response.
Python3
@api_view ([ 'PUT' ]) def update_task(request, pk): task = Task.objects.get( id = pk) serializer = TaskSerializer(instance = task, data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(status = status.HTTP_400_BAD_REQUEST) @api_view ([ 'DELETE' ]) def delete_task(request, pk): task = Task.objects.get( id = pk) task.delete() return Response( 'Deleted successfully' ,status = status.HTTP_202_ACCEPTED) |
- Next is an update and delete a task in update accept id of the task to be updated then check the validity of serializer and return a response, same with delete view get task object id from request and delete the task and return response.
Here we are completed with writing views.
Step 2: Configuring URL’s.
- Goto urls.py in API app if there’s isn’t one create urls.py and include the following code:
Python3
from django.urls import path from . import views urlpatterns = [ path( 'get/' , views.get_all_tasks, name = "get" ), path( 'create/' , views.create_task, name = "create" ), path( 'update/<int:pk>' , views.update_task, name = "update" ), path( 'delete/<int:pk>' , views.delete_task, name = "delete" ), path( 'details/<int:pk>' , views.get_task_details, name = "details" ) ] |
Above are different URL patterns to make requests to different views and get a response.
- Also, goto urls.py in the main project folder app goto urls.py and in URL patterns add:
Python3
urlpatterns = [ path( 'admin/' , admin.site.urls), path( 'api/' , include( 'api.urls' )) ] |
Here if any URL starts from api/ then transfer control to api.urls.
Python Django – Test Driven Development of Web API using DRF & Docker
We are going to create a to-do list web API using Django rest framework, docker and also going to write different tests for different functionalities in our code using test-driven development, but let’s first see what are prerequisites for this project.
Prerequisites :
- Docker Installed on your local system
- Basic knowledge of python 3.0
- Basic knowledge of Django 3.0
Now we are ready to go, let’s learn more about docker and Test-driven development (TDD) and why should we use them.
Docker :
Docker is an open-source containerization platform for automating the deployment of applications as portable, self-sufficient containers that can run on the cloud or on-premises.
Consider a situation where a software engineer writes a code and sends it for testing but that code won’t run on the tester’s local environment because all dependencies are not fulfilled, this problem can be eliminated simply by using docker.
Test-Driven Development (TDD):
Test-Driven Development is a software development practice where the focus is on writing unit tests before writing actual code, it is an iterative approach that combines programming, the creation of unit tests, and refactoring.
Unit Test: Unit tests are the test for testing different functionalities in our code
Three key steps for writing tests:
- Setup: creating sample functions that will be used in different test
- Execution: Calling the code which is being tested
- Assertion: comparing the results with expected results.
Now let’s move to the actual building part.