Add a route
This tutorial adds a route end to end: the model, the migration, the view, the address, the tests and the docs.
A made-up example
We add a category to products, and a GET /api/categories/ route. It does not exist in the project: it is only an example. Replace it with your real route.
1. The model
In api/products/models.py:
class Category(models.Model):
name = models.CharField(max_length=60, unique=True)
def __str__(self):
return self.nameAnd in Product, an optional link:
category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL)Why null=True? Existing products have no category. A required field would make the migration fail.
2. The migration
cd api
python manage.py makemigrations
DB_HOST= python manage.py migrateRead the generated products/migrations/0002_….py file: it is what will be applied in prod.
Migrations do not roll back
See Database. Add a column first; never drop one in the same release as a code change that still uses it.
3. The serializer
In api/products/serializers.py:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')And add 'category' to ProductSerializer's fields, otherwise the field does not appear in the API.
4. The ViewSet
In api/products/views.py:
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all().order_by('name')
serializer_class = CategorySerializer5. The router
In api/trinity_api/urls.py, next to the products line:
router.register('categories', CategoryViewSet, basename='category')/api/categories/ and /api/categories/{id}/ now exist.
6. The tests
In api/products/tests.py, modelled on ProductAPITests:
class CategoryAPITests(TestCase):
def test_list_categories(self):
Category.objects.create(name='Fruits')
response = APIClient().get('/api/categories/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data[0]['name'], 'Fruits')Before pushing:
DB_HOST= pytest
flake8 products trinity_api7. The docs
In the same merge request:
- Reference: the new row of the endpoints table;
- Database: the new table;
- Products or a new Features page for the rules;
- in French and in English.
8. The merge request
Branch feature/categories, merge request to develop. The pipeline runs api:lint and api:test. Once merged, deploy-dev applies the migration in dev.
Final checklist
| If you add… | Also update… |
|---|---|
| a model field | the migration + the serializer's fields + Database + the display on the web side |
| a route | a test + Reference |
| an environment variable | api/.env.example + infra/docker-compose.*.yml + Reference; if it is secret, a CI/CD variable (see Secrets) |
| a library | requirements.txt + Reference |