Skip to content

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:

python
class Category(models.Model):
    name = models.CharField(max_length=60, unique=True)

    def __str__(self):
        return self.name

And in Product, an optional link:

python
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 ​

sh
cd api
python manage.py makemigrations
DB_HOST= python manage.py migrate

Read 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:

python
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:

python
class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all().order_by('name')
    serializer_class = CategorySerializer

5. The router ​

In api/trinity_api/urls.py, next to the products line:

python
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:

python
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:

sh
DB_HOST= pytest
flake8 products trinity_api

7. 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 fieldthe migration + the serializer's fields + Database + the display on the web side
a routea test + Reference
an environment variableapi/.env.example + infra/docker-compose.*.yml + Reference; if it is secret, a CI/CD variable (see Secrets)
a libraryrequirements.txt + Reference