Home > python > BASE64 as URL parameter

BASE64 as URL parameter

Problem
In a REST API, I wanted to pass a URL as a BASE64-encoded string, e.g. “http://host/api/v2/url/aHR0cHM6...“. It worked well for a while but I got an error for a URL. As it turned out, a BASE64 string can contain the “/” sign, and it caused the problem.

Solution
Replace the “+” and “/” signs with “-” and “_“, respectively. Fortunately, Python has functions for that (see here).

Here are my modified, URL-safe functions:

def base64_to_str(b64):
    return base64.urlsafe_b64decode(b64.encode()).decode()

def str_to_base64(s):
    data = base64.urlsafe_b64encode(s.encode())
    return data.decode()

You can also quote and unquote a URL instead of using BASE64:

>>> url = "https://www.youtube.com/watch?v=V6w24Lg3zTI"
>>>
>>> import urllib.parse
>>>
>>> new = urllib.parse.quote(url)
>>>
>>> new
>>> 'https%3A//www.youtube.com/watch%3Fv%3DV6w24Lg3zTI'    # notice the "/" signs!
>>>
>>> urllib.parse.quote(url, safe='')
>>> 'https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DV6w24Lg3zTI'    # no "/" signs!
>>>
>>> new = urllib.parse.quote(url, safe='')
>>>
>>> urllib.parse.unquote(new)
>>> 'https://www.youtube.com/watch?v=V6w24Lg3zTI'
Advertisements
Categories: python Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: