Build and Audit a Token-Protected Favorites REST API with Django REST Framework
Customer wishlists and favorite-product endpoints look simple on paper: store customers, store products, and connect them through a join table.
In practice, small REST services accumulate subtle sharp edges around token issuance, duplicate prevention, HTTP verb choices, and dependency drift that make older APIs tricky to boot or reuse safely.
paladini/luizalabs-code-challenge is a compact, MIT-licensed Python and Django REST Framework service written in November 2020 as an API design exercise. Across roughly a dozen files, it implements token-authenticated endpoints for customers, products, and per-customer favorite product lists backed by PostgreSQL and seeded JSON fixtures.
Because the repository preserves both an unpinned requirements.txt and a pinned requirements-lock.txt alongside three sequential schema migrations, it serves two practical goals: running a minimal token-protected favorites API and auditing how a 2020 Django 3.1 codebase behaves under modern packaging and ORM inspection.
TL;DR
- Inspect commit
9a27825onmaster(the repository has no tagged releases). - Install from
requirements-lock.txt(Django==3.1.3,djangorestframework==3.12.2) on Python 3.9 withsetuptools<66rather than unpinnedrequirements.txton Python 3.12+. - Run migrations, load
favorites_list/fixtures/initial_data.json, authenticate via/api/v1/auth/login/, and passAuthorization: Token <key>to query/api/v1/products/and/api/v1/clients/. - Audit the migration and routing layer before reusing the design:
FavoriteListsetsmanaged = Falseafter droppingunique_together, and favorite mutations run onGETroutes.
Prerequisites
The repository documents docker-compose up with PostgreSQL, or you can verify the entire Django service locally without PostgreSQL using Python 3.9 and a one-file SQLite settings wrapper:
- Git to check out commit
9a2782577143ccb1a0681533322a4e65c680a3b5(no release tags exist in this repository). - Python 3.9 (
uv,pyenv, or a container) for lockfile compatibility, or Docker Compose if you update theDockerfileto pin Python 3.9 andrequirements-lock.txt. - Familiarity with HTTP headers and JSON APIs.
Minimal Working Path
Running docker-compose build unmodified today pulls a current python:3 image and installs unpinned django from requirements.txt. Django 4.0+ removed django.conf.urls.url, which breaks LuizaLabs/urls.py on startup.
Meanwhile, django-allauth==0.43.0 in requirements-lock.txt imports convert_path from setuptools, which fails on setuptools>=66.
To reproduce the 2020 stack without modifying the repository, create a Python 3.9 virtual environment, pin setuptools<66, and install the locked packages plus the four extra packages declared in requirements.txt:
git clone https://github.com/paladini/luizalabs-code-challenge.git
cd luizalabs-code-challenge
git checkout 9a2782577143ccb1a0681533322a4e65c680a3b5
uv venv --python 3.9 .venv
python -m ensurepip --upgrade
python -m pip install "setuptools<66" wheel
grep -v "^psycopg2-binary==" requirements-lock.txt > /tmp/reqs-local.txt
printf "drf-nested-routers==0.92.1\ncoreapi==2.3.3\nmarkdown==3.3.3\nPygments==2.7.2\n" >> /tmp/reqs-local.txt
python -m pip install --no-build-isolation -r /tmp/reqs-local.txt
On Windows PowerShell, use .venv\Scripts\python.exe and Where-Object { $_ -notmatch '^psycopg2-binary==' } when testing with SQLite. If you run PostgreSQL via docker-compose.yml, keep psycopg2-binary==2.8.6 inside a python:3.9-slim container.
Next, place a local_smoke_settings.py file outside the repository on PYTHONPATH to point Django at a local SQLite database:
from LuizaLabs.settings import *
DATABASES = { "default" : { "ENGINE" : "django.db.backends.sqlite3" , "NAME" : "smoke.sqlite3" , } }
Expected Result and Reproducible Verification
Run the script below in the Python 3.9 environment. It applies migrations, loads initial_data.json, verifies 401 enforcement on unauthenticated calls, logs in to retrieve a DRF token, and calls the favorite endpoints twice to confirm idempotency:
import json
import os
import django
os.environ["DJANGO_SETTINGS_MODULE"] = "local_smoke_settings"
django.setup()
from django.contrib.auth import get_user_model
from django.core.management import call_command
from rest_framework.test import APIClient
call_command("migrate", verbosity=0)
call_command("loaddata", "initial_data.json", verbosity=0)
User = get_user_model()
User.objects.filter(username="apiadmin").delete()
User.objects.create_user(username="apiadmin", email="a****@example.com", password="StrongPassword123!",)
client = APIClient()
print("Unauthenticated:", client.get("/api/v1/clients/").status_code)
login_resp = client.post("/api/v1/auth/login/", {"username": "apiadmin", "password": "StrongPassword123!"} , format="json",)
token_value = login_resp.json()["key"]
client.credentials(HTTP_AUTHORIZATION=f"Token {token_value}")
products = client.get("/api/v1/products/").json()
print("Products count:", products["count"])
client.get("/api/v1/clients/1/favorites/2/")
dup_add = json.loads(client.get("/api/v1/clients/1/favorites/2/").content)
print("Favorites after double add:", [p["id"] for p in dup_add["favorites"]])
client.get("/api/v1/clients/1/favorites/2/remove")
after_remove = json.loads(client.get("/api/v1/clients/1/favorites/2/remove").content)
print("Favorites after double remove:", [p["id"] for p in after_remove["favorites"]])
Executing the script produces this verified output (along with DRF's UnorderedObjectListWarning):
Unauthenticated: 401
Products count: 4
Favorites after double add: [4, 2]
Favorites after double remove: [4]
Client 1 begins with seeded product 4 (Pureza), gains product 2 (Fanta Laranja (2L)) once across two consecutive add requests, and returns to [4] cleanly across two remove requests.
Why It Works
Three small pieces connect the workflow:
Signal-backed token auth. LuizaLabs/settings.py configures TokenAuthentication and PageNumberPagination (PAGE_SIZE = 100), while every viewset in favorites_list/views.py enforces IsAuthenticated. A post_save signal in favorites_list/models.py creates a Token whenever a user is saved, which /api/v1/auth/login/ returns as key.
Explicit join model and nested read serializer. Client declares ManyToManyField(Product, through='FavoriteList', related_name='favorited_by'). In favorites_list/serializers.py, ClientSerializer nests ProductSerializer(many=True, read_only=True), returning complete product payloads inside each client response.
ORM-level idempotency. add_favorite calls FavoriteList.objects.get_or_create(product=product, client=client), and remove_favorite ignores FavoriteList.DoesNotExist, preventing duplicate entries during sequential requests.
Failure Modes, Limitations, and Security Boundaries
Inspecting the source and migrations highlights five caveats to fix before adapting this code beyond local study:
- Unmanaged join table and dropped database uniqueness. Migration
0001_initial.pycreatesfavorites_listwithunique_together = {('product', 'client')}, but0002_auto_20201110_0200.pyclearsunique_togethertoset()and0003_auto_20201110_0204.pysetsmanaged = False. Even thoughmodels.pystill declaresunique_together, Django skips schema migrations for unmanaged models, so concurrent writes can bypassget_or_createand insert duplicates. - State-mutating GET endpoints.
favorites_list/urls.pybinds bothclients/<int:id>/favorites/<int:product_id>/and.../removeto HTTPGET. Mutating state overGETexposes endpoints to accidental prefetching or retries; preferPOSTandDELETE. Also note@action(methods=['get, delete'], detail=True)inviews.py, which passes a single comma-joined string instead of['get', 'delete']. - Missing 404 handling and queryset ordering.
Client.objects.get(...)andProduct.objects.get(...)raise unhandled 500 errors on unknown IDs instead of returning 404, and missingMeta.orderingtriggersUnorderedObjectListWarningduring pagination. - Default SMTP dependency on registration. Because
ACCOUNT_EMAIL_VERIFICATIONis commented out insettings.py, posting to/api/v1/auth/registration/tries to connect tolocalhost:25and raisesConnectionRefusedErrorunless an SMTP server or console email backend is configured. Provisioning users withcreatesuperuserand calling/api/v1/auth/login/avoids SMTP. - Development-only settings. As documented in the Portuguese
readme.md, this repository is an interview MVP. It commits a developmentSECRET_KEY,DEBUG = True,ALLOWED_HOSTS = ['*'], defaultpostgrescredentials on port5432, and global token permissions without per-client ownership checks. Never expose it to a public network without externalizing secrets, disablingDEBUG, and scoping object-level permissions.
FAQ
Does the project ship with automated tests? No. favorites_list/tests.py holds only Django's default placeholder comment, and the README lists unit and integration tests as future work.
Why is price serialized as a string while review_score is decimal? Product.price uses CharField(max_length=50) whereas review_score uses DecimalField(decimal_places=2, max_digits=10). Real catalog APIs should store monetary values as DecimalField or integer minor units.
Where are the interactive API docs mounted? LuizaLabs/urls.py serves CoreAPI docs at /api/docs alongside DRF's browsable views at /api/v1/products/ and /api/v1/clients/.
Takeaway
Inspecting a compact API together with its lockfile and migration chain reveals details that code reading alone can miss. Explicit through models, nested read serializers, and token signals provide a clean Django REST Framework baseline, while database-enforced UniqueConstraint rules, proper POST / DELETE verbs, ordered querysets, and pinned container runtimes keep that baseline dependable over time.
Disclosure: This tutorial was researched and drafted with AI assistance. All file links, migration details, dependency versions, and verification outputs were verified directly against commit 9a2782577143ccb1a0681533322a4e65c680a3b5 of paladini/luizalabs-code-challenge and executed locally in Python 3.9 before publication.
When you audit or revive an older Django REST service, what breaks first in your experience: unpinned packaging files or ORM models that drifted away from their migrations?
Comments
No comments yet. Start the discussion.