pythonnotion-api

Notion API: Insert quote- block into a page of a database


With this code I try to insert a quote into an existing Notion page, but I get the following error: "Invalid request URL" which surprises me, because I have the url from the Notion website. I actually just call the url and pass the new block: quote. Fetching the Notion Page works without problems, only creating the block and adding it leads to an error, as this is output with "Error creating the block" from the print statement almost at the end

import requests
import json

# Notion API access token
token = "................."
database_id = "............."

# API endpoint to retrieve pages in the database
get_pages_url = f'https://api.notion.com/v1/databases/{database_id}/query'

# API request to retrieve pages in the database
headers = {
    "Authorization": "Bearer " + token,
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28",
}

response = requests.post(get_pages_url, headers=headers)

if response.status_code == 200:
    data = response.json()

    # Select the first page in the database
    if len(data['results']) > 0:
        page_id = data['results'][0]['id']

        # API endpoint to create a new block
        create_block_url = f'https://api.notion.com/v1/blocks/{page_id}/children'

        # JSON payload for the new quote block
        block_payload = {
            'children': [
                {
                    'object': 'block',
                    'type': 'quote',
                    'quote': {
                        'text': [
                            {
                                'type': 'text',
                                'text': {
                                    'content': 'This is a quote.'
                                }
                            }
                        ]
                    }
                }
            ]
        }

        # API request to create the block
        response = requests.post(create_block_url, headers=headers, data=json.dumps(block_payload))

        # Check the response
        if response.status_code == 200:
            print('New quote block successfully added to the page in the database.')
        else:
            print('Error creating the block:', response.status_code, response.text)
    else:
        print('The database contains no pages.')
else:
    print('Error retrieving pages from the database:', response.status_code, response.text)

Solution

  • I have noticed that you are using POST method for that API endpoint. As I know it is a PATCH method. Can you try suing PATCH for that and if error keeps occurring let me know.