(base) ~> conda create -n DRF python=3.7
(base) ~> conda activate DRF
(DRF) ~>
(DRF) ~> mkdir DRFtutorial
(DRF) ~> cd DRFtutorial
(DRF) DRFtutorial>
## DRF 패키지 설치 ##
(DRF) DRFtutorial> pip install djangorestframework
## project 생성 ##
(DRF) DRFtutorial> python manage.py startproject DRFtutorial .
## App 생성 ##
(DRF) DRFtutorial> python manage.py startapp quickstart
DRFtutorial/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'quickstart',
]
...
...
## REST_FRAMEWORK 추가 ##
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
django-rest-framework
와 qucikstart
을 INSTALLED_APPS
에 추가한다REST_FRAMEWORK
부분을 추가하는데, pagination
부분을 추가한다## 초기 migrate ##
(DRF) DRFtutorial> python manage.py migrate
## super user 생성 ##
(DRF) DRFtutorial> python manage.py createsuperuser
Email address:
Password:
Password(again):
Superuser created successfully
quickstart/serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
serializer
는 django
가 제공하는 model(모델)인 User
, Group
을 가져와서 framework가 활용가능한 데이터형태로 직렬화 한다serializer
는 model(모델)을 통해 가져온 queryset을 JSON, XML 또는 다른 컨텐츠 유형으로 변환할 수 있는 부분이다.Deserialize
은 queryset으로 돌려주는 역직렬화이다quickstart/views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
UserViewSet
, GroupViewSet
각각 ViewSet을 이용하여 View를 만든다.queryset
으로 만든다.DRFtutorial/urls.py
from django.urls import include, path
from rest_framework import routers
from quickstart.views import UserViewSet, GroupViewSet
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
서버 실행
(DRF) DRFtutorial> python manage.py runserver
API ROOT request
User request
(base) client> http -a admin:password123 http://127.0.0.1:8000/users/
HTTP/1.1 200 OK
...
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"email": "admin@example.com",
"groups": [],
"url": "http://localhost:8000/users/1/",
"username": "paul"
},
{
"email": "tom@example.com",
"groups": [ ],
"url": "http://127.0.0.1:8000/users/2/",
"username": "tom"
}
]
}
User List request
(base) client> http http://127.0.0.1:8000/users/
user detail request
(base) client> http http://127.0.0.1:8000/users/1