REST framework

Django REST framework ๊ณต์‹๋ฌธ์„œ์™€ ์ผ๋ถ€ ๊ธ€๋“ค์„ ๋ณด๊ณ  ์ •๋ฆฌํ•œ ๋‚ด์šฉ์ด๋‹ค.

front-end์™€ back-end์˜ ์ž‘์—… ํšจ์œจ์„ฑ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด์„œ๋Š” ๊ฐœ๋ฐœ์˜์—ญ์„ ์™„์ „ํžˆ ๊ตฌ๋ณ„๋˜๋Š” ๊ฒƒ์ด ์ด์ƒ์ ์ด๋ฉฐ, ๊ทธ๋Ÿฌ๊ธฐ ์œ„ํ•ด์„œ๋Š” REST API๊ฐ€ ํ•„์š”ํ•˜๋ฉฐ, ์žฌํ™œ์šฉ์„ฑ๋„ ๋†’์•„์ง„๋‹ค.

์—ฌ๊ธฐ์„œ๋Š” ๊ณต์‹๋ฌธ์„œ tutorial์„ ๋ณด๊ณ  ๋”ฐ๋ผํ•ด๋ณด์•˜์œผ๋ฉฐ, ์ž์„ธํ•œ ์„ค๋ช…์€ ๋’ค์— ๋‚˜์˜จ๋‹ค.

settings

$ pip install djangorestframework
# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]

์„ค์น˜๊ฐ€ ์™„๋ฃŒ๋˜๋ฉด INSTALLED_APPS ์— ์ถ”๊ฐ€ํ•ด์ค€๋‹ค.

ํ”„๋กœ์ ํŠธ ์‹œ์ž‘ํ•˜๊ธฐ

$ django-admin startproject tutorial
$ cd tutorial
$ django-admin startapp quickstart

$ ./manage.py migrate
$ ./manage.py createsuperuser --email admin@example.com --username admin

Serializers tutorial/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']

Views tutorial/quickstart/views.py ํŒŒ์ผ์„ ์—ด์–ด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ˆ˜์ •ํ•œ๋‹ค.

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from quickstart.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

URLs

from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/',include('rest_framework.urls',namespace='rest_framework'))
]

Pagination

๊ฐ ํŽ˜์ด์ง€๋งˆ๋‹ค ๋ช‡๊ฐœ์˜ ๊ฒŒ์‹œ๊ธ€์„ ๋…ธ์ถœํ• ์ง€ ์ง€์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

# tutorial/settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 15
}

tutorial/settings.py ํ•˜๋‹จ์— ์œ„์™€ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•ด์ค€๋‹ค.

$ ./manage.py runserver

์„ ํ•œํ›„ http://localhost:8000 ์œผ๋กœ ๋“ค์–ด๊ฐ€๋ณด๋ฉด ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

Last updated