Creating a Basic Create API with Django REST Framework

Last updated 4 months, 3 weeks ago | 410 views 75     5

Tags:- Python Django DRF

A Create API allows clients to send data to the server to create a new resource in the database. In RESTful terms, this usually maps to a POST request.

In this guide, we’ll walk through how to build a POST /books/ endpoint to create new book entries using Django REST Framework (DRF).


✅ What You'll Learn

  • What a Create API is

  • How to set up a serializer and view for creation

  • Writing the URL routing

  • How to test the Create API

  • Tips and common mistakes


What is a Create API?

A Create API is an endpoint that accepts incoming data and stores it as a new record.

For example:

POST /books/

Request Body:

{
  "title": "Atomic Habits",
  "author": "James Clear"
}

Response:

{
  "id": 1,
  "title": "Atomic Habits",
  "author": "James Clear"
}

Step-by-Step Guide

Let’s build a simple API that allows users to create new books in the database.


1. Define the Model

Make sure you have a model like this:

# books/models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

    def __str__(self):
        return self.title

Migrate if you haven't already:

python manage.py makemigrations
python manage.py migrate

2. Create the Serializer

# books/serializers.py
from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

3. Create the CreateAPIView

# books/views.py
from rest_framework.generics import CreateAPIView
from .models import Book
from .serializers import BookSerializer

class BookCreateView(CreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

CreateAPIView is a DRF generic view for handling POST requests to create new instances.


4. Add the URL Route

# books/urls.py
from django.urls import path
from .views import BookCreateView

urlpatterns = [
    path('books/create/', BookCreateView.as_view(), name='book-create'),
]

Include this in the main urls.py:

# myapi/urls.py
from django.contrib import admin
from django.urls import path, include

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

Testing the Create API

Run the server:

python manage.py runserver

Test with Postman, curl, or DRF’s web interface:

URL: POST http://127.0.0.1:8000/api/books/create/

Headers:

Content-Type: application/json

Body:

{
  "title": "Django for APIs",
  "author": "William Vincent"
}

Response:

{
  "id": 1,
  "title": "Django for APIs",
  "author": "William Vincent"
}

Summary of Key Components

Component Description
Book model Defines the structure of data
BookSerializer Converts between model and JSON
CreateAPIView Handles the POST request
URL pattern Exposes the API via /books/create/

⚠️ Common Pitfalls

Problem Solution
415 Unsupported Media Type Set Content-Type: application/json in headers
No data saved Check if the serializer is valid and save() is called
Missing fields Ensure all required model fields are provided in JSON
Authentication errors Set permissions or disable authentication for testing

Tips

  • Use Django admin or shell to verify new records

  • Add authentication and permissions when moving to production

  • Use CreateModelMixin for custom ViewSets if combining with other actions

  • Validate incoming data using validate_<field> or validate() in serializers


What's Next?

Now that you’ve built a basic Create API, here’s what you could do next:

  • ✅ Create a full CRUD API with List, Retrieve, Update, and Delete views

  • Switch to ModelViewSet and use routers for cleaner URL management

  • Add authentication with TokenAuth or JWT

  • Add validation and error handling for robust APIs