ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Django] APIView로 api 만들기
    파이썬/Django 2023. 1. 13. 15:10
    728x90
    반응형

    생성할 api

    [GET] [POST] /amenities

    [GET] [PUT] [DELETE] /amenities/1

     

    amenities는 room 앱(App)안에 있는 모델(model)이기 때문에 room/views.py에 코드를 작성해준다.

     

    코드작성이 필요한 파일은 총 세개

    • room/views.py
    • room/urls.py
    • room/serializers.py (생성해야함)

    api 구현할 클래스 생성하기

    📁 room/views.py

     

    api/v1/amenities 를 구현할 클래스 Amenites(APIView)

    - 전체 어메니티 내역 확인

    class Amenities(APIView):
        def get(self, request):
            pass
    
        def post(self, request):
            pass

     

    api/v1/amenities/1 를 구현할 클래스 AmenityDetail(APIView)

    - 각각의 어메니티 개별적으로 확인

    class AmenityDetail(APIView):
        def get(self, request, pk):
            pass
    
        def put(self, request, pk):
            pass
    
        def delete(self, request, pk):
            pass

     


    AmenitySerializer 생성하기

    📁 room/serializers.py

    from rest_framework.serializers import ModelSerializer
    from .models import Amenity
    
    
    class AmenitySerializer(ModelSerializer):
        class Meta:
            model = Amenity
            fields = "__all__"

    api url 설정하기

    📁 room/urls.py

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path("amenities/", views.Amenities.as_view()),
        path("amenities/<int:pk>", views.AmenityDetail.as_view()),
    ]

     


    모든 어메니티 [GET][POST] 하기

    class Amenities(APIView):
        def get(self, request):
            all_amenities = Amenity.objects.all()
            serializer = AmenitySerializer(all_amenities, many=True)
            return Response(serializer.data)
    
        def post(self, request):
            serializer = AmenitySerializer(data=request.data)
            if serializer.is_valid():
                amenity = serializer.save()
                return Response(
                    AmenitySerializer(amenity).data,
                )
            else:
                return Response(serializer.errors)

     

    개별 어메니티 [GET][PUT][DELETE] 하기

    class AmenityDetail(APIView):
        def get_object(self, pk):
            try:
                return Amenity.objects.get(pk=pk)
            except Amenity.DoesNotExist:
                raise NotFound
            
        def get(self, request, pk):
            amenity = self.get_object(pk)
            serializer = AmenitySerializer(amenity)
            return Response(serializer.data)
    
        def put(self, request, pk):
            amenity = self.get_object(pk)
            serializer = AmenitySerializer(
                amenity,
                data=request.data,
                partial=True,
            )
            if serializer.is_valid():
                updated_amenity = serializer.save()
                return Response(
                    AmenitySerializer(updated_amenity).data,
                )
            else:
                return Response(serializer.errors)
    
        def delete(self, request, pk):
            amenity = self.get_object(pk)
            amenity.delete()
            return Response(status=HTTP_204_NO_CONTENT)
    LIST
Designed by Tistory.