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 이기만 하면 됨
Django REST framework의 필요성
- The Web browsable API is a huge usability win for your developers.
- Authentication policies including packages for OAuth1a and OAuth2.
- Serialization that supports both ORM and non-ORM data sources.
- Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
- Extensive documentation, and great community support.
- Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.
Django REST framework Tutorial
https://www.django-rest-framework.org/tutorial/quickstart/
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
Pagination은 page당 몇개의 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/ 에 접속해보면 된다.
로그인해서 컨트롤해보자.
끝!