Thursday, 16 May 2019

django 35 rest framework class based apiview get post

get request to http://127.0.0.1:8000/api/album_list, last id = 32

postman post request to http://127.0.0.1:8000/api/album_list, new id = 33

verify data posted to server

#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

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)

------------------------------------------------
#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'),
]

urlpatterns = format_suffix_patterns(urlpatterns)

-------------------------------------
#project1/urls

urlpatterns = [
    ...
    path('api/', include('music.api.urls')),
]

-------------------------------------
#music/api/serializers

from rest_framework import serializers
from music.models import Album

class MusicSerializer(serializers.ModelSerializer):
    class Meta:
        model = Album
        fields = ('id', 'artist', 'album_title', 'genre', 'album_logo', 'date_posted', 'author')

reference:
http://chuanshuoge2.blogspot.com/2019/05/django-34-restful-api.html

No comments:

Post a Comment