Skip to content Skip to sidebar Skip to footer

Django Rest Framework Create Rest Api Only For Executions

I'm working on a django project in which I need to build a rest API for some executions, I don't have much concerns about models as I only need to perform executions on the base of

Solution 1:

You will probably want to implement DRFs ModelSerializer and ModelViewSet such that you can easily reuse the Django model you already have.

Your serializer could be like this (e.g. in serializers.py):

from rest_framework import serializers

from .modelsimportDeploymentOnUserclassDeploymentOnUserModelSerializer(serializers.ModelSerializer):
    classMeta:
        model = DeploymentOnUser
        fields = (deployment_name, credentials, )

You should add your own validation here, much like you would do with Django forms.

The viewset could be like this (e.g. in views.py):

from rest_framework import viewsets
from rest_framework.response import Response

from .models import DeploymentOnUserModel
from .serializers import DeploymentOnUserModelSerializer 


classDeploymentOnUserViewSet(viewsets.ModelViewSet):
    queryset = DeploymentOnUserModel.objects.all()
    serializer_class = DeploymentOnUserModelSerializer 

    defcreate(self, request, *args, **kwargs):
        """overwrite this for extra actions"""
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

Depending on your situation, you might even need to overwrite create -- this just shows how you could do it.

The ModelViewSet and ModelSerializer remove much of the boilerplate code. However, if you haven't used DRF before, it doesn't hurt to first go through the tutorial

Don't forget to also register the viewset in urls.py:

from django.conf.urls import url, include

from rest_framework import routers

from .views import DeploymentOnUserViewSet


router = routers.DefaultRouter()
router.register('deployments', DeploymentOnUserViewSet)

urlpatterns = [
    # other patterns also go here
    url('', include(router.urls)),
]

You could then test your API by doing e.g. a POST call on /deployments/.

For unit testing, I mostly use this pattern:

from rest_framework.test import APIRequestFactory

# Create a POST request, at the root
request = APIRequestFactory().post('/')
response = DeploymentOnUserViewSet.as_view({'post': 'create'})(request)
assert response.status_code == 200

Post a Comment for "Django Rest Framework Create Rest Api Only For Executions"