How to use Django REST framework



Image not found!!

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:

1. Install Django REST Framework

Make sure you have Django installed. You can install Django REST Framework using pip:

bash
pip install djangorestframework

2. Add DRF to your Django project

Add 'rest_framework' to the INSTALLED_APPS list in your Django project's settings:

python
# settings.py INSTALLED_APPS = [ # ... 'rest_framework', # ... ]

3. Create a Serializer

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__'

4. Create a ViewSet

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

5. Wire up the URLs

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

6. Run migrations

Make sure to run migrations to create the necessary database tables for your models:

bash
python manage.py makemigrations python manage.py migrate

7. Run the development server

bash
python 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.