Base64
Python
decode
data encoding
Python programming

How do you decode Base64 data in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Base64 decoding in Python is straightforward once you know whether you want raw bytes or decoded text. The standard library already handles the common cases, including web-safe Base64 and validation of malformed input. Most mistakes come from mixing bytes and strings or from assuming every Base64 payload is UTF-8 text.

Decode Standard Base64 to Bytes

Use the built-in base64 module. b64decode returns bytes, which is exactly what you want if the original content was binary.

python
1import base64
2
3encoded = "SGVsbG8sIFB5dGhvbiE="
4decoded_bytes = base64.b64decode(encoded)
5
6print(decoded_bytes)
7print(type(decoded_bytes))

The result is bytes, not str. That is correct behavior because Base64 encodes arbitrary binary data, not just text.

Convert Decoded Bytes to Text

If the original data was text, decode the bytes with the proper character encoding, usually UTF-8.

python
1import base64
2
3encoded = "SGVsbG8sIFB5dGhvbiE="
4decoded_text = base64.b64decode(encoded).decode("utf-8")
5
6print(decoded_text)

This two-step pattern is the normal approach:

  • Base64 decode to bytes
  • text decode from bytes to string

Keeping those steps separate makes bugs easier to diagnose.

Decode Bytes Input as Well as String Input

The base64 module accepts either a string or bytes.

python
1import base64
2
3encoded = b"UHl0aG9u"
4decoded = base64.b64decode(encoded)
5
6print(decoded.decode("utf-8"))

That is useful when the payload comes directly from a network response or file read operation.

Decode URL-Safe Base64

Some systems use URL-safe Base64, where - and _ replace the standard + and / characters. Python supports that with urlsafe_b64decode.

python
1import base64
2
3encoded = "SGVsbG8td29ybGQ_"
4decoded = base64.urlsafe_b64decode(encoded + "=")
5
6print(decoded)

Padding can be missing in web contexts such as tokens. If the input length is not divisible by four, you may need to restore padding before decoding.

python
1def decode_urlsafe_base64(data: str) -> bytes:
2    padding = "=" * (-len(data) % 4)
3    return base64.urlsafe_b64decode(data + padding)
4
5print(decode_urlsafe_base64("SGVsbG8td29ybGQ_"))

Decode Base64 from a File

If a file contains Base64 text, read it as text and decode the contents.

python
1import base64
2
3with open("payload.b64", "r", encoding="utf-8") as f:
4    encoded = f.read().strip()
5
6binary_data = base64.b64decode(encoded)
7
8with open("output.bin", "wb") as f:
9    f.write(binary_data)

This is a common pattern when reconstructing images, PDFs, or binary attachments.

Validate Input When Data Quality Matters

By default, some malformed data can slip through more quietly than you expect. Use validation when decoding untrusted input.

python
1import base64
2import binascii
3
4try:
5    data = base64.b64decode("not-valid-base64!!!", validate=True)
6except binascii.Error as exc:
7    print(f"Invalid Base64: {exc}")

Validation is worth using in APIs and data pipelines, where silent corruption is harder to debug later.

Example: Decode an Image and Write It Back

This is a realistic end-to-end example using binary output.

python
1import base64
2
3with open("image.b64", "r", encoding="utf-8") as f:
4    encoded = f.read().strip()
5
6image_bytes = base64.b64decode(encoded)
7
8with open("restored.png", "wb") as f:
9    f.write(image_bytes)

If the restored file does not open, check whether the input was actually Base64, whether padding is missing, and whether the output extension matches the real file type.

Common Pitfalls

The most common mistake is calling .decode("utf-8") on data that was never text in the first place. Images and PDFs should stay as bytes and be written in binary mode.

Another issue is forgetting about missing padding in URL-safe payloads. Web-generated Base64 often drops trailing = characters.

Malformed input is also easy to miss if validation is turned off. If correctness matters, use validate=True and catch binascii.Error.

Summary

  • Use base64.b64decode to turn Base64 into raw bytes.
  • Decode those bytes to text only if the original payload was textual.
  • Use urlsafe_b64decode for web-safe Base64 variants.
  • Restore padding when token-like inputs omit trailing =.
  • Validate untrusted input so malformed Base64 fails early and clearly.

Course illustration
Course illustration

All Rights Reserved.