Skip to content

The products API ​

The need: the back office must be able to list, create, update and delete products, and the API must refuse a negative price or stock, whatever the client.

Related rules: Products · Errors and validation · Database

1. The model ​

api/products/models.py:

python
from django.db import models
from django.core.validators import MinValueValidator


class Product(models.Model):
    name = models.CharField(max_length=120)
    description = models.TextField(blank=True)
    price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        validators=[MinValueValidator(0)],
    )
    stock = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

Each attribute is a column. The business rules are in the model:

LineRule
6max_length=120: name of at most 120 characters
7blank=True: the description may be empty
8-12DecimalField + MinValueValidator(0): an exact price, never negative
13PositiveIntegerField(default=0): integer stock, zero or positive
14-15auto_now_add / auto_now: dates are filled by Django

Why DecimalField and not FloatField?

A float cannot represent 0.10 exactly. For money, rounding errors add up. DecimalField stores the exact value, and DRF sends it as text ("2.50") so JSON does not degrade it.

Why put the rules in the model?

They then apply everywhere: the API, the Django admin, and the database itself for PositiveIntegerField (a CHECK constraint in PostgreSQL). One source of truth.

2. The serializer ​

api/products/serializers.py:

python
from rest_framework import serializers

from .models import Product


class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = (
            'id',
            'name',
            'description',
            'price',
            'stock',
            'created_at',
            'updated_at',
        )
        read_only_fields = ('id', 'created_at', 'updated_at')

A ModelSerializer reads the model and derives the fields and their rules. We only specify:

  • fields: the exact list of exposed fields. A field added to the model does not show up in the API on its own.
  • read_only_fields: id and the dates are sent to the client, but ignored if it sends them back.

3. The view ​

api/products/views.py:

python
from rest_framework import viewsets

from .models import Product
from .serializers import ProductSerializer


class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all().order_by('id')
    serializer_class = ProductSerializer

Two lines are enough. ModelViewSet provides list, retrieve, create, update, partial_update and destroy.

Why order_by('id')?

Without an explicit order, a database does not guarantee row order: the list could change order between calls. And DRF warns when paginating an unordered list.

4. The addresses ​

api/trinity_api/urls.py, from line 17:

python
from django.contrib import admin
from django.http import JsonResponse
from django.urls import include, path
from rest_framework.routers import DefaultRouter

from products.views import ProductViewSet

router = DefaultRouter()
router.register('products', ProductViewSet, basename='product')


def health_check(request):
    return JsonResponse({"status": "ok"}, status=200)


urlpatterns = [
    path('admin/', admin.site.urls),
    path('health', health_check, name='health_check'),
    path('api/', include(router.urls)),
]
  • DefaultRouter creates products/ and products/<id>/ from the ViewSet.
  • path('api/', include(router.urls)) prefixes everything with /api/.
  • health_check answers {"status": "ok"} without touching the database.

Why doesn't /health check the database?

The health check tells Docker and Swarm whether this container answers. If the database goes down, restarting the API would not fix it: better keep the API up and return explicit 500s.

5. The tests ​

api/products/tests.py holds 7 tests:

TestChecks
test_health_returns_ok/health → 200 + {"status": "ok"}
test_list_productsthe list contains the created product
test_retrieve_productreading a product by id
test_create_productPOST → 201, one more product
test_update_productPATCH of the stock → 200, value changed in the database
test_delete_productDELETE → 204, product gone
test_reject_negative_priceprice -1.00 → 400
python
    def test_reject_negative_price(self):
        response = self.client.post(
            '/api/products/',
            {'name': 'Invalid', 'price': '-1.00', 'stock': 0},
            format='json',
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

Pitfalls ​

A new model field is not exposed on its own

You must also add it to fields in the serializer, then write the migration.

No authentication

ModelViewSet uses DRF's default permissions: anyone can write. Acceptable for a sample, not for a real back office. See Limits.

What to remember ​

  • The rules are in the model; the serializer and the view reuse them.
  • ModelViewSet + DefaultRouter = a full CRUD in a few lines.
  • /health answers without the database, on purpose.