The project is in a healthy, maintained state
Notion API client for Ruby.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
 Dependencies

Development

~> 13
>= 0
~> 0.82.0
~> 1.39.0
>= 0

Runtime

 Project Readme

Notion Ruby Client

Gem Version CI workflow badge

A Ruby client for the Notion API.

Table of Contents

  • Installation
  • Usage
    • Create a New Bot Integration
    • Declare the API token
    • API Client
      • Instantiating a new Notion API client
      • Pagination
  • Endpoints
    • Databases
      • Query a database
      • Create a Database
      • Update a Database
      • Retrieve a database
      • List databases
    • Pages
      • Retrieve a page
      • Create a page
      • Update page
      • Retrieve a page property item
    • Blocks
      • Retrieve a block
      • Update a block
      • Delete a block
      • Retrieve block children
      • Append block children
    • Users
      • Retrieve your token's bot user
      • Retrieve a user
      • List all users
    • Search
  • Acknowledgements

Installation

Add to Gemfile.

gem 'notion-ruby-client'

Run bundle install.

Usage

Create a New Integration

📘 Before you start

Make sure you are an Admin user in your Notion workspace. If you're not an Admin in your current workspace, create a new personal workspace for free.

To create a new integration, follow the steps 1 & 2 outlined in the Notion documentation. The “Internal Integration Token” is what is going to be used to authenticate API calls (referred to here as the “API token”).

📘 Integrations don't have access to any pages (or databases) in the workspace at first. A user must share specific pages with an integration in order for those pages to be accessed using the API.

Declare the API token

Notion.configure do |config|
  config.token = ENV['NOTION_API_TOKEN']
end

For Rails projects, the snippet above would go to config/application.rb.

API Client

Instantiating a new Notion API client

client = Notion::Client.new

You can specify the token or logger on a per-client basis:

client = Notion::Client.new(token: '<secret Notion API token>')

Pagination

The client natively supports cursor pagination for methods that allow it, such as users_list. Supply a block and the client will make repeated requests adjusting the value of start_cursor with every response. The default page size is set to 100 (Notion’s current default and maximum) and can be adjusted via Notion::Client.config.default_page_size or by passing it directly into the API call.

all_users = []
client.users_list(page_size: 25) do |page|
  all_users.concat(page.results)
end
all_users # All users, retrieved 25 at a time

When using cursor pagination the client will automatically pause and then retry the request if it runs into Notion rate limiting. (It will pause for 10 seconds before retrying the request, a value that can be overriden with Notion::Client.config.default_retry_after.) If it receives too many rate-limited responses in a row it will give up and raise an error. The default number of retries is 100 and can be adjusted via Notion::Client.config.default_max_retries or by passing it directly into the method as max_retries.

You can also proactively avoid rate limiting by adding a pause between every paginated request with the sleep_interval parameter, which is given in seconds.

all_users = []
client.users_list(sleep_interval: 5, max_retries: 20) do |page|
  # pauses for 5 seconds between each request
  # gives up after 20 consecutive rate-limited responses
  all_users.concat(page.results)
end
all_users

Endpoints

Databases

Query a database

Gets a paginated array of Page objects contained in the database, filtered and ordered according to the filter conditions and sort criteria provided in the request.

client.database_query(database_id: 'e383bcee-e0d8-4564-9c63-900d307abdb0')  # retrieves the first page

client.database_query(database_id: 'e383bcee-e0d8-4564-9c63-900d307abdb0', start_cursor: 'fe2cc560-036c-44cd-90e8-294d5a74cebc')

client.database_query(database_id: 'e383bcee-e0d8-4564-9c63-900d307abdb0') do |page|
  # paginate through all pages
end

# Filter and sort the database
sorts = [
  {
    'timestamp': 'created_time',
    'direction': 'ascending'
  }
]
filter = {
  'or': [
    {
      'property': 'In stock',
      'checkbox': {
        'equals': true
      }
    },
    {
      'property': 'Cost of next trip',
      'number': {
        'greater_than_or_equal_to': 2
      }
    }
  ]
}
client.database_query(database_id: 'e383bcee-e0d8-4564-9c63-900d307abdb0', sorts: sorts, filter: filter)

See Pagination for details about how to iterate through the list.

See the full endpoint documentation on Notion Developers.

Create a Database

Creates a database as a subpage in the specified parent page, with the specified properties schema.

title = [
  {
    'type': 'text',
    'text': {
      'content': 'Grocery List',
      'link': nil
    }
  }
]
properties = {
  'Name': {
    'title': {}
  },
  'Description': {
    'rich_text': {}
  },
  'In stock': {
    'checkbox': {}
  },
  'Food group': {
    'select': {
      'options': [
        {
          'name': '🥦Vegetable',
          'color': 'green'
        },
        {
          'name': '🍎Fruit',
          'color': 'red'
        },
        {
          'name': '💪Protein',
          'color': 'yellow'
        }
      ]
    }
  }
}
client.create_database(
  parent: { page_id: '98ad959b-2b6a-4774-80ee-00246fb0ea9b' },
  title: title,
  properties: properties
)

See the full endpoint documentation on Notion Developers.

Update a Database

Updates an existing database as specified by the parameters.

title = [
  {
    'text': {
      'content': 'Orbit 💜 Notion'
    }
  }
]
client.update_database(database_id: 'dd428e9dd3fe4171870da7a1902c748b', title: title)

See the full endpoint documentation on Notion Developers.

Retrieve a database

Retrieves a Database object using the ID specified.

client.database(database_id: 'e383bcee-e0d8-4564-9c63-900d307abdb0')

See the full endpoint documentation on Notion Developers.

List databases

List all Databases shared with the authenticated integration.

client.databases_list # retrieves the first page

client.databases_list(start_cursor: 'fe2cc560-036c-44cd-90e8-294d5a74cebc')

client.databases_list do |page|
  # paginate through all databases
end

See Pagination for details about how to iterate through the list.

See the full endpoint documentation on Notion Developers.

Pages

Retrieve a page

Retrieves a Page object using the ID specified.

📘 Responses contains page properties, not page content. To fetch page content, use the retrieve block children endpoint.

client.page(page_id: 'b55c9c91-384d-452b-81db-d1ef79372b75')

See the full endpoint documentation on Notion Developers.

Create a page

Creates a new page in the specified database or as a child of an existing page.

If the parent is a database, the property values of the new page in the properties parameter must conform to the parent database's property schema.

If the parent is a page, the only valid property is title.

The new page may include page content, described as blocks in the children parameter.

properties = {
  'Name': {
    'title': [
      {
        'text': {
          'content': 'Tuscan Kale'
        }
      }
    ]
  },
  'Description': {
    'rich_text': [
      {
        'text': {
          'content': 'A dark green leafy vegetable'
        }
      }
    ]
  },
  'Food group': {
    'select': {
      'name': '🥦 Vegetable'
    }
  },
  'Price': {
    'number': 2.5
  }
}
children = [
  {
    'object': 'block',
    'type': 'heading_2',
    'heading_2': {
      'rich_text': [{
        'type": 'text',
        'text': { 'content': 'Lacinato kale' }
      }]
    }
  },
  {
    'object': 'block',
    'type": 'paragraph',
    'paragraph': {
      'rich_text': [
        {
          'type': 'text',
          'text': {
            'content': 'Lacinato kale is a variety of kale with a long tradition in Italian cuisine, especially that of Tuscany. It is also known as Tuscan kale, Italian kale, dinosaur kale, kale, flat back kale, palm tree kale, or black Tuscan palm.',
            'link': { 'url': 'https://en.wikipedia.org/wiki/Lacinato_kale' }
          }
        }
      ]
    }
  }
]
client.create_page(
   parent: { database_id: 'e383bcee-e0d8-4564-9c63-900d307abdb0'},
   properties: properties,
   children: children
)

See the full endpoint documentation on Notion Developers.

Update page

Updates page property values for the specified page. Properties that are not set via the properties parameter will remain unchanged.

If the parent is a database, the new property values in the properties parameter must conform to the parent database's property schema.

properties = {
  'In stock': {
    'checkbox': true
  }
}
client.update_page(page_id: 'b55c9c91-384d-452b-81db-d1ef79372b75', properties: properties)

See the full endpoint documentation on Notion Developers.

Retrieve a page property item

Retrieves a property_item object for a given page_id and property_id. Depending on the property type, the object returned will either be a value or a paginated list of property item values. See Property item objects for specifics.

To obtain property_id's, use the Retrieve a database endpoint.

client.page_property_item(
  page_id: 'b55c9c91-384d-452b-81db-d1ef79372b75',
  property_id: 'aBcD123'
)

See the full endpoint documentation on Notion Developers.

Blocks

Retrieve a block

Retrieves a Block object using the ID specified.

📘 If a block contains the key has_children: true, use the Retrieve block children endpoint to get the list of children

client.block(block_id: '9bc30ad4-9373-46a5-84ab-0a7845ee52e6')

See the full endpoint documentation on Notion Developers.

Update a block

Updates the content for the specified block_id based on the block type. Supported fields based on the block object type (see Block object for available fields and the expected input for each field).

Note The update replaces the entire value for a given field. If a field is omitted (ex: omitting checked when updating a to_do block), the value will not be changed.

to_do = {
  'rich_text': [{
    'type': 'text',
    'text': { 'content': 'Lacinato kale' }
    }],
  'checked': false
}
client.update_block(block_id: '9bc30ad4-9373-46a5-84ab-0a7845ee52e6', 'to_do' => to_do)

See the full endpoint documentation on Notion Developers.

Delete a block

Sets a Block object, including page blocks, to archived: true using the ID specified. Note: in the Notion UI application, this moves the block to the "Trash" where it can still be accessed and restored.

To restore the block with the API, use the Update a block or Update page respectively.

client.delete_block(block_id: '9bc30ad4-9373-46a5-84ab-0a7845ee52e6')

See the full endpoint documentation on Notion Developers.

Retrieve block children

Returns a paginated array of child block objects contained in the block using the ID specified. In order to receive a complete representation of a block, you may need to recursively retrieve the block children of child blocks.

client.block_children(block_id: 'b55c9c91-384d-452b-81db-d1ef79372b75')

client.block_children(block_id: 'b55c9c91-384d-452b-81db-d1ef79372b75', start_cursor: 'fe2cc560-036c-44cd-90e8-294d5a74cebc')

client.block_children(block_id: 'b55c9c91-384d-452b-81db-d1ef79372b75') do |page|
  # paginate through all children
end

See Pagination for details about how to iterate through the list.

See the full endpoint documentation on Notion Developers.

Append block children

Creates and appends new children blocks to the parent block specified by block_id.

Returns a paginated list of newly created first level children block objects.

children = [
  {
    "object": 'block',
    "type": 'heading_2',
    'heading_2': {
      'rich_text': [{
        'type': 'text',
        'text': { 'content': 'A Second-level Heading' }
      }]
    }
  }
]
client.block_append_children(block_id: 'b55c9c91-384d-452b-81db-d1ef79372b75', children: children)

See the full endpoint documentation on Notion Developers.

Users

Retrieve your token's bot user

Retrieves the bot User associated with the API token provided in the authorization header. The bot will have an owner field with information about the person who authorized the integration.

client.me

See the full endpoint documentation on Notion Developers.

Retrieve a user

Retrieves a User using the ID specified.

client.user(user_id: 'd40e767c-d7af-4b18-a86d-55c61f1e39a4')

See the full endpoint documentation on Notion Developers.

List all users

Returns a paginated list of Users for the workspace.

client.users_list # retrieves the first page

client.users_list(start_cursor: 'fe2cc560-036c-44cd-90e8-294d5a74cebc')

client.users_list do |page|
  # paginate through all users
end

See Pagination for details about how to iterate through the list.

See the full endpoint documentation on Notion Developers.

Search

Searches all pages and child pages that are shared with the integration. The results may include databases.

client.search # search through every available page and database

client.search(query: 'Specific query') # limits which pages are returned by comparing the query to the page title

client.search(filter: { property: 'object', value: 'page' }) # only returns pages

client.search(sort: { direction: 'ascending', timestamp: 'last_edited_time' }) # sorts the results based on the provided criteria.

client.search(start_cursor: 'fe2cc560-036c-44cd-90e8-294d5a74cebc')

client.search do |page|
  # paginate through all search pages
end

See Pagination for details about how to iterate through the list.

See the full endpoint documentation on Notion Developers.

Acknowledgements

The code, specs and documentation of this gem are an adaptation of the fantastic Slack Ruby Client gem. Many thanks to its author and maintainer @dblock and contributors.