Django REST Framework Tutorial: A Real Shop Orders API
Quick answer
Django REST Framework, usually called DRF, is the standard way to turn Django models into a JSON API: you write a serializer that describes the shape of the data, and a viewset that wires up list, create, retrieve, update, and delete. This post builds a real one for a small Karachi clothing shop: orders go in with curl, come back with a computed rupee total, and bad data gets a 400.
A small clothing shop in Karachi takes orders over WhatsApp. The owner reads each message, copies the items into a notebook, and works out the total on a calculator. It works until it does not: one order copied with the wrong quantity, one total added up wrong, one customer asking whether her order went through while nobody can answer. The shop does not need a bigger notebook, just one place where an order is recorded once, checked as it arrives, and read back the same way every time. That is a small API, and DRF is a good fit for it.
What I would check before using it
My first check is whether Django is already in the picture. DRF is an add-on to Django, not a standalone framework, so it pays off fastest when the project already runs Django. Starting from zero, a lighter Python API framework may be quicker, and the FastAPI Explained: Python APIs at Full Speed post covers that choice.
My second check is how much of the API is plain create, read, update, and delete. A ModelViewSet hands you all five endpoints from one class, so this post's whole API is a handful of lines. When most endpoints are custom logic rather than CRUD, that shortcut saves little.
My third check is who calls the API and how they prove who they are. Out of the box, these endpoints are open to anyone on the network, fine on a laptop and wrong anywhere else. Before it goes near real customers, add permission classes and token or session authentication; the JWT Authentication: Verify a Token Without a Database post shows how token checks work.
My fourth check is where validation lives. The serializer in this post refuses a zero quantity before anything touches the database, and the total is computed, never stored, so a price change cannot leave stale totals behind. Complicated rules, like stock checks across two tables, belong in the model or a service layer, not the serializer.
My verdict, as judgement: adopt DRF when you already run Django and the API is mostly CRUD with clear validation rules. It flips when the project has no Django, or the endpoints are so custom the shortcut saves nothing.
A Karachi clothing shop, served by an API
The demo is the Karachi clothing shop from the intro: an order arrives as JSON, gets validated and saved, and comes back with a total the server computed.
Install Django and DRF, then start the project:
$ pip install Django djangorestframework
$ django-admin startproject shopapi .
$ python manage.py startapp ordersTwo models: an order with a customer, a city, and a status, and items that each carry a price in rupees and a quantity, both at least 1:
from django.core.validators import MinValueValidator
from django.db import models
class Order(models.Model):
customer = models.CharField(max_length=120)
city = models.CharField(max_length=80, default="Karachi")
status = models.CharField(max_length=20, default="recorded")
created_at = models.DateTimeField(auto_now_add=True)
def total_rs(self):
return sum(item.price_rs * item.qty for item in self.items.all())
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE)
name = models.CharField(max_length=120)
price_rs = models.PositiveIntegerField(validators=[MinValueValidator(1)])
qty = models.PositiveIntegerField(validators=[MinValueValidator(1)])The serializer is where DRF earns its keep: it nests the items inside the order, exposes a computed total, and creates the nested rows:
from rest_framework import serializers
from .models import Order, OrderItem
class OrderItemSerializer(serializers.ModelSerializer):
class Meta:
model = OrderItem
fields = ["id", "name", "price_rs", "qty"]
class OrderSerializer(serializers.ModelSerializer):
items = OrderItemSerializer(many=True)
total_rs = serializers.SerializerMethodField()
class Meta:
model = Order
fields = ["id", "customer", "city", "status", "created_at", "items", "total_rs"]
read_only_fields = ["status", "created_at"]
def get_total_rs(self, obj):
return obj.total_rs()
def create(self, validated_data):
items_data = validated_data.pop("items")
order = Order.objects.create(**validated_data)
for item_data in items_data:
OrderItem.objects.create(order=order, **item_data)
return orderOne viewset and one router give the API its five endpoints, after adding rest_framework and orders to INSTALLED_APPS:
from rest_framework import viewsets
from .models import Order
from .serializers import OrderSerializer
class OrderViewSet(viewsets.ModelViewSet):
queryset = Order.objects.all().order_by("-created_at")
serializer_class = OrderSerializerfrom django.urls import include, path
from rest_framework import routers
from orders.views import OrderViewSet
router = routers.DefaultRouter()
router.register(r"orders", OrderViewSet)
urlpatterns = [
path("api/", include(router.urls)),
]Migrate and start the server:
$ python manage.py check
System check identified no issues (0 silenced).
$ python manage.py makemigrations orders
$ python manage.py migrate
$ python manage.py runserver 127.0.0.1:8000My first call went to the wrong URL. I typed /api/order/, singular, and Django answered with a 404 page listing every route it knew, noting the current path matched none of them:
$ curl -X POST http://127.0.0.1:8000/api/order/ \
-H 'Content-Type: application/json' \
-d '{"customer":"Ayesha Khan","city":"Karachi","items":[{"name":"White Cotton Kurta","price_rs":2450,"qty":1},{"name":"Pastel Lawn Kurta","price_rs":1950,"qty":2}]}'
HTTP 404The router registers the plural orders, and the trailing slash matters:
$ curl -X POST http://127.0.0.1:8000/api/orders/ \
-H 'Content-Type: application/json' \
-d '{"customer":"Ayesha Khan","city":"Karachi","items":[{"name":"White Cotton Kurta","price_rs":2450,"qty":1},{"name":"Pastel Lawn Kurta","price_rs":1950,"qty":2}]}'
{"id":1,"customer":"Ayesha Khan","city":"Karachi","status":"recorded","created_at":"2026-12-02T03:04:18.707335Z","items":[{"id":1,"name":"White Cotton Kurta","price_rs":2450,"qty":1},{"id":2,"name":"Pastel Lawn Kurta","price_rs":1950,"qty":2}],"total_rs":6350}
HTTP 201Rs 2,450 once plus Rs 1,950 twice is Rs 6,350, worked out by the server. Reading it back is a plain GET:
$ curl http://127.0.0.1:8000/api/orders/1/
{"id":1,"customer":"Ayesha Khan","city":"Karachi","status":"recorded","created_at":"2026-12-02T03:04:18.707335Z","items":[{"id":1,"name":"White Cotton Kurta","price_rs":2450,"qty":1},{"id":2,"name":"Pastel Lawn Kurta","price_rs":1950,"qty":2}],"total_rs":6350}
HTTP 200Bad data never reaches the database: a quantity of zero gets a 400 naming the exact rule that failed:
$ curl -X POST http://127.0.0.1:8000/api/orders/ \
-H 'Content-Type: application/json' \
-d '{"customer":"Bilal Ahmed","city":"Karachi","items":[{"name":"Embroidered Lawn Suit","price_rs":3200,"qty":0}]}'
{"items":{"0":{"qty":["Ensure this value is greater than or equal to 1."]}}}
HTTP 400A second order for Sana Malik, three men kurtas at Rs 1,800 each, came back with Rs 5,400, and the list then showed both orders, newest first.

Common mistakes and how to fix them
First, posting to the singular URL. The symptom is a 404, and with debug on, a page listing every route the project knows. The fix is the plural path with a trailing slash: /api/orders/.
Second, sending a quantity of zero or a negative price. The symptom is a 400 with "Ensure this value is greater than or equal to 1." The fix is MinValueValidator(1) on the model fields, so the serializer enforces the rule for free.
Third, sending a quantity as a word instead of a number. The symptom is a 400 with "A valid integer is required." The fix is at the sender: send numbers as numbers, "qty": 2, not "qty": "two".
Fourth, leaving the items field out entirely. The symptom is a 400 with "This field is required." The fix is to always send the items array.
Fifth, storing the total instead of computing it. The symptom is orders whose saved total no longer matches their items after a price changes. The fix is a SerializerMethodField that adds the total up on every read.
Frequently Asked Questions
Do I need to know Django before learning DRF? Yes, DRF sits on top of Django, so models and migrations should feel familiar first. The Django Explained: Python's Batteries-Included Framework post covers the base framework.
Can I test the endpoints without curl? Yes. DRF ships a browsable API, so opening http://127.0.0.1:8000/api/orders/ in a browser shows a form you can post from. For saved collections, the Postman Explained: Testing APIs Before the Frontend Exists post covers that tool.
How do I add login to these endpoints? Add a permission class to the viewset and an authentication backend, such as token authentication. The JWT Authentication: Verify a Token Without a Database post shows how token checks work.
Is SQLite enough for a real shop? For a laptop demo and a small shop, yes. When orders grow, switch the DATABASES setting to PostgreSQL and run the same migrations.
What to remember
- A serializer turns a model into JSON and back, and holds the validation.
- A ModelViewSet gives you list, create, retrieve, update, and delete from one class.
- The router decides the URL: plural, with a trailing slash.
- Compute totals on read, never store them, or they drift.
- A 400 from DRF names the field and the rule, so read it first.
Where this leaves you
One model, one serializer, one viewset, and a Karachi clothing shop now has an API that records an order once, checks it as it arrives, and reads it back with a total it computed: order 1, Rs 6,350, recorded. The 404 was the useful part, a reminder that the router owns the URL and the client has to match it. Take an order flow of your own, the kind still living in a notebook, and give it a serializer before you give it a frontend.
Further reading
- Django REST Framework documentation
- Django REST Framework quickstart tutorial
- Serializers
- ViewSets
- Django Explained: Python's Batteries-Included Framework
- FastAPI Explained: Python APIs at Full Speed
- Build Your First REST API With Node.js and Express
- Postman Explained: Testing APIs Before the Frontend Exists
- JWT Authentication: Verify a Token Without a Database
- SQLAlchemy: Turn Your Python Classes Into Database Tables
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Comments
Post a Comment