Encode and shorten UUIDs in URLs

302 views
Skip to first unread message

thibault...@adaptive-channel.com

unread,
Aug 23, 2018, 9:58:29 AM8/23/18
to Django REST framework
We are building an api which exposes uuids instead of pks to access objects.

As a way to shorten the urls and make them friendlier, we thought we could encode the uuids in a higher base than the default base16 (we chose base58 for readability if you're curious, but that doesn't matter).

What's the best approach to decode and encode uuids seemlessly in urls, as they go in and out of our api?

Also, we would of course like for reverse() to yield urls with encoded uuids.

After skimming through Django rest framework's source code, I've tried customizing serializers, middleware, views, etc. without success and I'm a bit lost now.

Chris Foresman

unread,
Aug 24, 2018, 9:13:56 AM8/24/18
to Django REST framework
It almost sounds like you'd need to patch Django's URL resolver to look for capture groups that might be a primary key, and then base58 decode the value before passing it as a value to the view method being called. Then you would need to write your own function, `my_reverse`, which would look for kwargs that would be primary keys, and base58 encode them before passing them on to reverse and then returning that.

gordon

unread,
Aug 24, 2018, 9:17:51 AM8/24/18
to django-res...@googlegroups.com
You could also make a custom uuid field that handles this.  Use a uuid subclass that uses base 58 for string conversion. And then convert to correct database representation in the field methods

On Fri, Aug 24, 2018, 9:13 AM Chris Foresman <fore...@gmail.com> wrote:
It almost sounds like you'd need to patch Django's URL resolver to look for capture groups that might be a primary key, and then base58 decode the value before passing it as a value to the view method being called. Then you would need to write your own function, `my_reverse`, which would look for kwargs that would be primary keys, and base58 encode them before passing them on to reverse and then returning that.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Chris Foresman

unread,
Aug 24, 2018, 9:21:03 AM8/24/18
to django-res...@googlegroups.com
Yes, this is a better idea than mine. 

You received this message because you are subscribed to a topic in the Google Groups "Django REST framework" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-rest-framework/ePEfWaamnxA/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-rest-fram...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages