Empowering Restaurants through Integration

Overview

We use base64-encoded UUIDs here at Grubhub. The standard, base16 versions are long and aren't URL safe. To fix this problem, we encode our UUIDs. Below you will find example code to perform the UUID to base64-encoding.

For example, a UUID4 of `635bc4e5-b5eb-42fa-a680-c20506a36d10` should convert to
`Y1vE5bXrQvqmgMIFBqNtEA` when properly encoded.

Examples

Java


Java
import org.apache.commons.codec.binary.Base64; import java.nio.ByteBuffer; import java.util.UUID; public class UUIDs { public static String encode(UUID uuid) { ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); return Base64.encodeBase64URLSafeString(buffer.array()); } public static UUID decode(String input) { if (input.length() == 36) { return UUID.fromString(input); } if (input.length() != 22) { throw new IllegalArgumentException("Not a valid Base64 encoded UUID"); } ByteBuffer buffer = ByteBuffer.wrap(Base64.decodeBase64(input)); if (buffer.capacity() != 16) { throw new IllegalArgumentException("Not a valid Base64 encoded UUID"); } return new UUID(buffer.getLong(), buffer.getLong()); } }

Python


import uuid
import base64
def encode_uuid(base16_string):
  return base64.urlsafe_b64encode(uuid.UUID(base16_string).bytes).decode("UTF-8").strip("=")

def decode_uuid(base64_string):
  return str(uuid.UUID(bytes=base64.urlsafe_b64decode(base64_string)))

Ruby


require "base64"

DELIMITER = '-'
FORMAT = 'H8H4H4H4H12'

def decode(str)
  Base64.urlsafe_decode64(str).unpack(FORMAT).join(DELIMITER)
end

def encode(uuid)
  Base64.urlsafe_encode64(uuid.split(DELIMITER).pack(FORMAT), padding: false)
end

JavaScript

Note: atob and btoa are utility functions in the Chrome dev tools


function decodeBase64UUID(str) {
  let urlUnsafe = str.replace(/-/g, '+').replace(/_/g, '/');
  let arr = atob(urlUnsafe).split('').map(c => {
    let char = c.charCodeAt(0);
    return ('0'+char.toString(16)).substr(-2,2);
  });
  arr.splice(4, 0, '-');
  arr.splice(7, 0, '-');
  arr.splice(10, 0, '-');
  arr.splice(13, 0, '-');
  return arr.join('').toLowerCase();
}

function encodeBase64UUID(str) {
  return btoa(str.replace(/-/g, '').match(/\w{2}/g).map(a => {
    return String.fromCharCode(parseInt(a, 16));
  }).join('')).replace(/=*$/, '').replace(/\+/g, '-').replace(/\//g, '_');
}