Encode base64 in JavaScript and Decode in Python: Part 1

Learn how to send URL safe base64 encoded data to your Python API.

If you build an API that accepts data as a path parameter or query string, you’ll want to encode this information as base64 to prevent browsers or HTTP clients from messing with special characters like #?, and =.

You can URL encode those special characters but I don’t like to do that because some libraries will often automatically decode them if they’re part of the URL before making the request.

Base64 is efficient and perfect for data consistent.

However, base64 can contain characters like + and /, which carry special meaning in the context of URLs.

That’s why you should make your base64 string URL safe.

Let’s start with an example.

Your want to make a request to https://myapi.com/files/{file_path} where file_path is the parameter your api expects.

The file_path will be something like /Users/data/mystuff.

You can’t send that as part of the URL, so you need to encode it as base64.

First, you need to install the buffer package, which is a polyfill of the NodeJS built-in Buffer for browser environments.

npm i buffer

Now you can encode your data:

import { Buffer } from ‘buffer’;

function b64Encode(s) {
  return Buffer.from(s, 'utf-8').toString('base64');
}

b64Encode('/Users/data/mystuff')

You should get L1VzZXJzL2RhdGEvbXlzdHVmZg== as a result.

Fortunately, this string doesn’t contain any undesired characters like + or /. However, you need to make sure you utility function replaces those characters in case they do exist.

import { Buffer } from ‘buffer’;

function b64Encode(s) {
  return Buffer.from(s, 'utf-8').toString('base64').replaceAll("+", "-").replaceAll("/", "_").split("=")[0]
}

b64Encode('/Users/data/mystuff')

Your function will now return the encoded string with all + characters replaced by -, / characters replaced by _ and no = characters.

In base64, = is used for padding. When the result is not divisible by 4, the encode will pad the remaining space with = characters. According to the base64 specification, removing the = characters is lossless.

You can now safely pass this string to your api like so: https://myapi.com/files/L1VzZXJzL2RhdGEvbXlzdHVmZg

In Part 2 of this post, I’ll show you how you can reassemble this urlsafe base64 encoded string to the actual data it contains from your Python backend.