Hiding the IDs

The API looks great, except for the security risk of exposing the user model's primary key publicly. Thankfully, the serializers can be changed to add fields that are not present in the model, as the following code demonstrates:

class PostSerializer(serializers.ModelSerializer): 
    posted_by = serializers.SerializerMethodField() 
 
    def get_posted_by(self, obj): 
        return obj.posted_by.username 
 
    class Meta: 
        model = models.Post 
        fields = ("posted_by", "message",) 

The SerializerMethodField is a read-only field that gets its value from a class method. By default, this is the method named get_<field_name>.

Now, the API returns posts with the usernames instead of the user's primary key, as the following screenshot shows:

If you are a REST purist, you might point out that instead of a username, we can use hyperlinks to the User resource. You may want to implement this if your users are comfortable with sharing their details on a public API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.87.152