'How can I encrypt url in Django Rest Framework?

I found a documentation since it is not working with python updated version so I am having this problem. I want to prevent scrapping from my application. There are some api where I am passing sensitive data and my api endpoing is like localhost:8000/api/products/1 but I want this url to be like localhost:8000/api/products/dheudhuehdeidiwf4yfg4gfy4yf4f4fu4f84j4i this. So which procedure should I follow here?



Solution 1:[1]

You can use uuid as another unique key in your model.

import uuid


class Product(models.Model):
    uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
    # other fields ...

For the serializers, you'll have to manually set them like:

class ProductSerializer(serializers.Serializer):
    uuid = serializers.UUIDField(format="hex", read_only=True)
    # other fields ...

    class Meta:
        model = Product
        fields = [
            "uuid",
            # other fields ...
        ]

For the views, I'm assuming you are using ModelViewSet, so you can set the uuid as the lookup field like:

class ProductViewSet(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    lookup_field = "uuid"

Solution 2:[2]

One way to go about making your sensitive ids urlsafe would be to use urlsafe_base64_encode from django.utils.http. You could return encrypted ids along with your response to the frontend using:

uidb64 = urlsafe_base64_encode(force_bytes(model_name.pk))

the frontend can then persist the encrypted ids and when request are made to your endpoints using those ids, you then decrypt them using smart_str from django.utils.encoding like this:

model_name_pk = smart_str(urlsafe_base64_decode(uidb64))

assuming your endpoints looks something like this 'api/an-interesting-route/<uidb64>'

This approach is more useful with GET endpoints that do not just return the model directly but include some amount of processing of the id before a response is returned.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kyell
Solution 2 Dharman