Skip to content

DRF Setup#

Installation#

pip install djangorestframework

Settings#

# myproject/settings.py
INSTALLED_APPS = [
    # ...
    'rest_framework',
]

# Optional: DRF configuration
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20,
}

Basic Project Structure#

myproject/
├── myapp/
│   ├── models.py
│   ├── serializers.py      # Create this
│   ├── views.py
│   ├── urls.py
│   └── permissions.py      # Optional
└── myproject/
    └── urls.py

Quick Example#

# myapp/serializers.py
from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

# myapp/views.py
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

# myapp/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import PostViewSet

router = DefaultRouter()
router.register(r'posts', PostViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
]

Test API#

# Run server
python manage.py runserver

# Access API
# GET http://localhost:8000/api/posts/
# POST http://localhost:8000/api/posts/
# GET http://localhost:8000/api/posts/1/
# PUT http://localhost:8000/api/posts/1/
# DELETE http://localhost:8000/api/posts/1/

Next: Serializers