본문 바로가기

Python/Django

[Django REST framework] REST란? / Django REST framework의 필요성 / Django REST framework Tutorial

REST란?

  • Architectural style for distributed hypermedia systems
  • Guiding principles of REST
    • Client-sever
    • Stateless
    • Cacheable
    • Uniform interface
    • Layered system
    • Code on demand(optional)
  • uses a resource identifier
  • A truly RESTful API looks like hypertext
  • resource methods
    • HTTP GET/PUT/POST/DELETE 와는 엄밀히 말하면 다르다
    • 딱 이 상황에 이렇게 써야해 라는 표준이 없음
    • 상황에 따라 HTTP method를 사용할 수 있음
    • 단, uniform interface 이기만 하면 됨

https://restfulapi.net/

 

What is REST – Learn to create timeless REST APIs

 

restfulapi.net


Django REST framework의 필요성


Django REST framework Tutorial

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

 

Quickstart - Django REST framework

We're going to create a simple API to allow admin users to view and edit the users and groups in the system. Create a new Django project named tutorial, then start a new app called quickstart. # Create the project directory mkdir tutorial cd tutorial # Cre

www.django-rest-framework.org

Project setup

> mkdir tutorial
> cd tutorial
> python -m venv myvenv
> myvenv\Scripts\activate
> pip install django
> pip install djangorestframework
> django-admin startproject tutorial .
> cd tutorial
> django-admin startapp quickstart
> python manage.py migrate
> python manage.py createsuperuser

* project 안에 app을 넣는 것을 유의하자.

Serializers

Serializers란?

models 인스턴스와 querysets 같은 복잡한 데이터를 native python datatypes로 바꿔서 JSON, XML와 같은 content type으로 쉽게 바꿀 수 있게하는 한다.

 

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, permissions
from .serializers import UserSerializer, GroupSerializer

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]

class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]

* serializer들을 import할 때, 경로를 .serializers로 바꿀 것!(공식문서와 다름)

Urls

tutorial/urls.py

from django.urls import include, path
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'))
]

* views를 import할 때 tutorial.quickstart(공식 tutorial) -> quickstart로 바꿀 것!

 

Pagination

Paginationpage당 몇개의 object가 return 됐는지 통제할 수 있게 한다.

 

tutorial/settings.py

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

Settings

tutorial/settings.py

INSTALLED_APPS = [
    #...
    'rest_framework',
]

기본적인 설정은 모두 끝났다!


Testing our API

> python manage.py runserver

 

bash shell에서 curl을 이용하여 API에 access해보자

$ curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/

밑에 '}'가 짤렸..

 

 

혹은 http://127.0.0.1:8000/users/ 에 접속해보면 된다.

 

로그인해서 컨트롤해보자.

 

끝!