Base64
string encoding
byte conversion
Python programming
encoding explanation

Why do I need 'b' to encode a string with Base64?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Python 3, Base64 functions operate on bytes, not on Unicode strings, which is why examples often use the b prefix. This design prevents silent encoding assumptions and makes binary transformations explicit. Once the bytes model is clear, Base64 usage becomes straightforward and predictable.

Why Base64 APIs Expect Bytes

Base64 is an encoding for binary data. Python therefore expects bytes input for base64.b64encode and returns bytes output.

python
1import base64
2
3raw = b"hello"
4encoded = base64.b64encode(raw)
5print(encoded)           # b'aGVsbG8='
6print(type(encoded))

If you pass a normal string directly, Python raises a type error because text and binary are separate types.

Converting str to bytes Correctly

Encode text first using an explicit character encoding, usually UTF-8.

python
1import base64
2
3text = "hello"
4raw_bytes = text.encode("utf-8")
5encoded_bytes = base64.b64encode(raw_bytes)
6encoded_text = encoded_bytes.decode("ascii")
7
8print(encoded_text)

The reverse path is decode Base64 to bytes, then decode bytes to string.

python
decoded_bytes = base64.b64decode(encoded_text)
decoded_text = decoded_bytes.decode("utf-8")
print(decoded_text)

What the b Prefix Means

The b prefix creates a bytes literal at source level.

python
1a = "hello"   # str
2b = b"hello"  # bytes
3
4print(type(a), type(b))

It does not perform encoding magically. It simply says literal content should be bytes.

Real-World Example: JSON APIs

Many APIs carry Base64 payloads as JSON strings. Typical flow:

  • app text or binary data to bytes
  • bytes to Base64 bytes
  • Base64 bytes to ASCII string for JSON transport
python
1import base64
2import json
3
4payload = {"message": "hello world"}
5raw = json.dumps(payload).encode("utf-8")
6encoded = base64.b64encode(raw).decode("ascii")
7
8wire = {"data": encoded}
9print(wire)
10
11decoded_raw = base64.b64decode(wire["data"])
12decoded_payload = json.loads(decoded_raw.decode("utf-8"))
13print(decoded_payload)

Handling Binary Files

For files, skip text decoding unless needed.

python
1import base64
2
3with open("image.png", "rb") as f:
4    raw = f.read()
5
6encoded = base64.b64encode(raw)
7
8with open("image.b64", "wb") as f:
9    f.write(encoded)

This keeps binary data intact without accidental character transformations.

URL-Safe Base64 and Validation

Some protocols require URL-safe Base64 where plus and slash characters are replaced. Python includes dedicated helpers for this format.

python
1import base64
2
3data = b"token:abc123"
4url_safe = base64.urlsafe_b64encode(data)
5print(url_safe)
6
7decoded = base64.urlsafe_b64decode(url_safe)
8print(decoded)

When decoding data from untrusted input, validate and handle exceptions carefully.

python
1import binascii
2
3try:
4    value = base64.b64decode("invalid***", validate=True)
5except binascii.Error as exc:
6    print("invalid base64:", exc)

Explicit validation protects APIs from malformed payloads and improves error responses.

A reliable rule is to convert text to bytes at system boundaries, perform Base64 operations only on bytes, and convert back to text only when the transport format requires it.

For interoperability, also note whether padding characters are preserved. Some systems strip trailing equals signs, so decoding logic should handle expected format consistently.

Write small helper functions for encode and decode paths to keep conversions consistent across your codebase.

Common Pitfalls

  • Passing str directly to Base64 functions that require bytes.
  • Forgetting to decode Base64 output when a text string is required for JSON.
  • Mixing UTF-8 and other encodings inconsistently across systems.
  • Assuming b"text" and "text" are interchangeable in Python 3.
  • Decoding arbitrary binary payloads as UTF-8 without checking content type.

Summary

  • Base64 APIs in Python use bytes by design.
  • Use .encode to convert text to bytes before Base64 encoding.
  • Use .decode to convert Base64 bytes to text when needed.
  • The b prefix creates bytes literals and clarifies intent.
  • Keep text and binary conversion steps explicit to avoid data corruption.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.