728x90

Django REST Framework는 라우터, 인증/권한, 데이터 규격화 (시리얼라이저), 필터/페이지네이션, 캐시, 쓰로틀, 렌더러, 테스트 등의 기능을 제공하며, 대체로 django 에서 제공하는 기능을 감싼 wrapper 형태로 되어있다.

 

https://www.django-rest-framework.org/

 

Home - Django REST framework

 

www.django-rest-framework.org

Home 에서 예시로 나온 코드를 복사하여 붙여넣기하면 기본적인 장고 REST 프레임웍이 동작되는 걸 확인할 수 있다.

 

다음 단계로 python manage.py startapp api 를 하고 나서

아래 그림처럼 파일을 각각 분리하여 serializers.py, views.py, urls.py 로 분리하여 넣는다.

 

프로젝트 수준의 urls.py

from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('api.urls')),
    # path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
 

 

api/serializers.py

Serializer 는 queryset 과 model instance 를 쉽게 JSON 또는 XML 의 데이터 형태로 렌더링 할 수 있게 해준다.

 
# Serializers define the API representation.
from django.contrib.auth.models import User
from rest_framework import serializers
 
 
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url''username''email''is_staff']
 

 

api/views.py

# ViewSets define the view behavior.
from django.contrib.auth.models import User
from rest_framework import viewsets
 
from api.serializers import UserSerializer
 
 
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
 

 

api/urls.py

# Routers provide an easy way of automatically determining the URL conf.
from django.urls import path, include
from rest_framework import routers
 
from api.views import UserViewSet
 
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
 
urlpatterns = [
    path('', include(router.urls)),
]

 

 

 

 

블로그 이미지

Link2Me

,