Search code examples
facebook-graph-apibase64

Why is it a common practice to encode pagination cursors or id values as string?


For example the Facebook Graph API: why are after and before base64 encoded numbers?

{
  "data": [
     ... Endpoint data is here
  ],
  "paging": {
    "cursors": {
      "after": "MTAxNTExOTQ1MjAwNzI5NDE=",
      "before": "NDMyNzQyODI3OTQw"
    },
    "previous": "https://graph.facebook.com/me/albums?limit=25&before=NDMyNzQyODI3OTQw"
    "next": "https://graph.facebook.com/me/albums?limit=25&after=MTAxNTExOTQ1MjAwNzI5NDE="
  }
}

What benefits could it possibly bring in contrast to just plain numbers?

As the following python log shows, the benefits can not be shorter representation of the data or the data containing unsafe characters:

>>> base64.b64decode("MTAxNTExOTQ1MjAwNzI5NDE=")
'10151194520072941'
>>> len('10151194520072941')
17
>>> len("MTAxNTExOTQ1MjAwNzI5NDE=")
24

Solution

  • This is a more general answer towards the "why encode cursors with base64" part of the question and not related to the Facebook Graph API.

    I agree with Rafael Almeida and rodrigomd in that the intention behind the Base64 encoding is to hide implementation details and keep the cursor value compact.

    This is kind of a standard practice.

    The folks at Slack use Base64 encoded cursors because their cursor values(before encoding) look something like this:

    user:W07QCRPA4
    

    Base64 encoding this value keeps it compact and hides the implementation detail.

    This also gives them the flexibility to use this same strategy to convert their offset-based paginated API services into cursor-based by using cursor values as:

    offset:10
    

    Clients won't know the difference because they don't need to.