Adding Local JPEG Images to Notion Pages via API Using Python

I’m trying to figure out how to add local JPEG images to a Notion page using their API and Python. I’ve already turned the image into base64 but I’m struggling with adding it to a block on an existing page. I know there’s a way to add images from URLs but I want to see if I can do it this way first.

I’m new to working with APIs directly so I’m a bit confused about the correct setup. I’ve tried different API URLs but I’m not sure which one is right. Here’s the part of my code that’s giving me trouble:

image_base64 = base64.b64encode(image_bytes).decode('utf-8')

api_url = 'https://api.notion.com/v1/blocks/page_id_here/children'

headers = {
    'Authorization': 'Bearer your_api_key_here',
    'Content-Type': 'application/json',
    'Notion-Version': '2022-06-28'
}

payload = {
    'parent': {'page_id': 'your_page_id_here'},
    'children': [{
        'type': 'image',
        'image': {
            'type': 'file',
            'file': {'url': f'data:image/jpeg;base64,{image_base64}'}
        }
    }]
}

response = requests.post(api_url, headers=headers, json=payload)
print(response.json())

I’m getting a 400 error saying something about a database_id being undefined. If this base64 method doesn’t work, I might try using a cloud storage service instead. Any ideas on what I’m doing wrong?

hey man, i had the same problem last week. ended up using imgur to host my images instead. its free and easy. just upload ur pics there and use the url in the notion api. worked like a charm for me. good luck!

I’ve dealt with this issue before. The Notion API doesn’t support direct base64 image uploads, so the best solution is to use cloud storage like AWS S3 or Google Cloud Storage. Upload your image to such a service, obtain its public URL, and then incorporate that URL into your API request using the ‘external’ key in your payload instead of ‘file’. Ensure that the API endpoint and identifiers are correct. If local files are preferred, hosting them on your own server can work, though it adds complexity.

I’ve been through this exact struggle before. The Notion API can be a bit tricky when it comes to handling images. Instead of relying on base64 encoding, I set up a simple Flask server on my local machine to serve the images temporarily, which allowed me to generate URLs that could be used in the Notion API request. This method worked well as a workaround when using local files. If setting up Flask seems like too much, you might try using Python’s built-in http.server module for a simpler approach. I hope this helps. Feel free to ask if you need more details.