Sunday, 19 May 2019

django 36 rest framework class based apiview put delete

get details from http://127.0.0.1:8000/api/album_detail/33/

post send put request to http://127.0.0.1:8000/api/album_detail/33/ to change genre to 'rock' 

get details from http://127.0.0.1:8000/api/album_detail/33/ genre is changed to 'rock'

postman send delete requent to http://127.0.0.1:8000/api/album_detail/33/

album no longer exist

#music/api/apiview

from music.models import Album
from music.api.serializers import MusicSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404

class AlbumList(APIView):
    def get(self, request, format=None):
        albums = Album.objects.all()
        serializer = MusicSerializer(albums, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = MusicSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class AlbumDetail(APIView):
    def get_object(self, pk):
        try:
            return Album.objects.get(pk=pk)
        except Album.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        album = self.get_object(pk)
        serializer = MusicSerializer(album)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        album = self.get_object(pk)
        serializer = MusicSerializer(album, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        album = self.get_object(pk)
        album.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

-----------------------------------------------
#music/api/urls

from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from music.api import apiview

app_name = 'musicAPI'

urlpatterns = [
    path('album_list', apiview.AlbumList.as_view(), name='AlbumList'),
    path('album_detail/<int:pk>/', apiview.AlbumDetail.as_view(), name='AlbumDetail'),
]

urlpatterns = format_suffix_patterns(urlpatterns)

reference:

No comments:

Post a Comment