carlos de la morena
carlos de la morena

Reputation: 93

How to post a Json with a base64 file using python request?

Right now I am programming an API with python, and I have the following problem: I have to POST the following JSON to an url:

prescription = {
"Name": “file_name", # This is a string
"Body" : "xxx",# (File in base64 format)
"ParentId" : "xxxxxxxxxxxxxxxxxx", # This is a string
"ContentType" : "xxxxx/xxx" # This is a string
}

But when I try to do the following request:

requests.post(url, prescription)

I am getting the following error:

TypeError: Object of type bytes is not JSON serializable

How can I make a request for posting that JSON? Is it even possible?

Thanks for your help.

EDIT: Using

"Body" : "xxx.decode("utf-8")"

worked, thanks for the help

Upvotes: 2

Views: 3156

Answers (1)

Swann_bm
Swann_bm

Reputation: 106

You can do the following:

import base64
import requests

with open("your/file", "rb") as file:
    b64_file_content= base64.b64encode(file.read())

prescription = {
    "Name": "file_name",  # This is a string
    "Body": b64_file_content.decode("ascii"),  # (File in base64 format)
    "ParentId": "xxxxxxxxxxxxxxxxxx",  # This is a string
    "ContentType": "xxxxx/xxx",  # This is a string
}

requests.post("https://somewhere.world", prescription)

Upvotes: 0

Related Questions