Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs in Django applications. It provides a set of tools and conventions to simplify the creation of RESTful APIs. Here's a basic guide to getting started with Django REST Framework:
Make sure you have Django installed. You can install Django REST Framework using pip:
bashpip install djangorestframework
Add 'rest_framework'
to the INSTALLED_APPS
list in your Django project's settings:
python# settings.py
INSTALLED_APPS = [
# ...
'rest_framework',
# ...
]
Serializers are used to convert complex data types, such as Django models, into Python data types that can be easily rendered into JSON.
python# serializers.py
from rest_framework import serializers
from .models import YourModel
class YourModelSerializer(serializers.ModelSerializer):
class Meta:
model = YourModel
fields = '__all__'
ViewSets define the view behavior. They encapsulate the logic for handling HTTP methods (GET, POST, etc.) for different endpoints.
python# views.py
from rest_framework import viewsets
from .models import YourModel
from .serializers import YourModelSerializer
class YourModelViewSet(viewsets.ModelViewSet):
queryset = YourModel.objects.all()
serializer_class = YourModelSerializer
Connect the ViewSet to URLs in your urls.py
:
python# urls.py
from rest_framework.routers import DefaultRouter
from .views import YourModelViewSet
router = DefaultRouter()
router.register(r'your-model', YourModelViewSet, basename='your-model')
urlpatterns = router.urls
Make sure to run migrations to create the necessary database tables for your models:
bashpython manage.py makemigrations python manage.py migrate
bashpython manage.py runserver
Now, you can access your API endpoints. DRF will provide a browsable API that makes it easy to explore and interact with your API using a web browser.
This is a basic setup, and there's a lot more you can do with Django REST Framework, including authentication, permissions, pagination, and more. Refer to the official documentation for more advanced features: Django REST Framework Documentation.