Listing Notion Workspaces

April 5, 2025

Listing Notion Workspaces

Notion API

Testing the API with a single page of results. This will help in understanding the pagination process.

const response = await fetch("https://api.notion.com/v1/search", {
    method: "POST",
    headers: {
        "Authorization": "Bearer '$NOTION_API_KEY'",
        "Notion-Version": "2022-06-28",
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        "page_size": 1, // MAXIMUM ALLOWED VALUE IS 100, BUT SETTING IT TO 1 FOR TESTING
        "filter": {
            "property": "object",
            "value": "database"
        }
    })
})

Response:

{
  "object": "list",
  "results": [
    {
      "object": "database", // or "database"
      "id": "database-id-string",
      "created_time": "2023-01-01T00:00:00.000Z",
      "last_edited_time": "2023-01-02T00:00:00.000Z",
      "parent": {
        "type": "workspace_id",
        "workspace_id": "workspace-id-string"
      },
      "properties": {
        // PROPERTIES OF THE PAGE OR DATABASE
      }
    }
  ],
  "next_cursor": "cursor-string-or-null",
  "has_more": true // OR FALSE
}

Since I need the complete list of workspaces, I need to paginate through the results

const fetchNotionWorkspaces = async () => {
    const workspaces = []
    let has_more = true
    let start_cursor = undefined
    while ( has_more ) {
        const response = await fetch("https://api.notion.com/v1/search", {
            method: "POST",
            headers: {
                "Authorization": "Bearer '$NOTION_API_KEY'",
                "Notion-Version": "2022-06-28",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                "filter": {
                    "property": "object",
                    "value": "database"
                },
                "page_size": 100, // MAXIMUM ALLOWED VALUE
                "start_cursor": start_cursor
            })
        })
        const data = await response.json()
        workspaces = workspaces.concat(data.results);
        has_more = data.has_more
        start_cursor = data.next_cursor
    }
    return workspaces
}