Django REST framework with function based view

Setup

  1. Install Django and Django REST framework:
    pip install django djangorestframework
    
  2. Create a new Django project:
    django-admin startproject myproject
    cd myproject
    
  3. Create a new Django app:
    python manage.py startapp myapp
    
  4. Add the app and DRF to INSTALLED_APPS in myproject/settings.py:
    INSTALLED_APPS = [
        ...
        'rest_framework',
        'myapp',
    ]
    

Models

Let’s define a simple model in myapp/models.py:

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

Run migrations to create the database table:

python manage.py makemigrations
python manage.py migrate

Serializers

Create a serializer for the Item model in myapp/serializers.py:

from rest_framework import serializers
from .models import Item

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

Views

Create function-based views in myapp/views.py:

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Item
from .serializers import ItemSerializer

@api_view(['GET', 'POST'])
def item_list(request):
    if request.method == 'GET':
        items = Item.objects.all()
        serializer = ItemSerializer(items, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ItemSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def item_detail(request, pk):
    try:
        item = Item.objects.get(pk=pk)
    except Item.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ItemSerializer(item)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = ItemSerializer(item, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

URLs

Define the API endpoints in myapp/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('items/', views.item_list),
    path('items/<int:pk>/', views.item_detail),
]

Include the app’s URLs in the project’s urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]

Testing the API

Run the development server:

python manage.py runserver

You can now test your API using tools like curl, Postman, or a web browser:

  • GET all items: http://127.0.0.1:8000/api/items/
  • POST a new item: http://127.0.0.1:8000/api/items/ (with JSON data)
  • GET a single item: http://127.0.0.1:8000/api/items/<id>/
  • PUT to update an item: http://127.0.0.1:8000/api/items/<id>/ (with JSON data)
  • DELETE an item: http://127.0.0.1:8000/api/items/<id>/