[파이썬] Django REST framework란

지원 버전 (2022-03-28 기준)

  • Python (3.6, 3.7, 3.8, 3.9, 3.10)
  • Django (2.2, 3.0, 3.1, 3.2, 4.0)

추천 패키지

  • PyYAML, uritemplate (5.1+, 3.0.0+) - Schema generation support.
  • Markdown (3.0.0+) - Markdown support for the browsable API.
  • Pygments (2.4.0+) - Add syntax highlighting to Markdown processing.
  • django-filter (1.0.1+) - Filtering support.
  • django-guardian (1.1.1+) - Object level permissions support.
pip install PyYAML
pip install uritemplate
pip install Markdown
pip install Pygments
pip install django-filter
pip install django-guardian

설치

pip install djangorestframework

버전 확인

python -c "import rest_framework; print(rest_framework.VERSION)"

초기 셋팅

settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

urls.py

  • If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views ``` from django.urls import path, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets

Serializers define the API representation.

class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'is_staff']

ViewSets define the view behavior.

class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer

Routers provide an easy way of automatically determining the URL conf.

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

Wire up our API using automatic URL routing.

Additionally, we include login URLs for the browsable API.

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

links

social