Skip to content

phacks/notion-ruby-client

Repository files navigation

Notion Ruby Client

Gem Version CI workflow badge

A Ruby client for the Notion API.

Table of Contents

Installation

Add to Gemfile.

gem 'notion-ruby-client'

Runbundle install.

Usage

Create a New Integration

📘Before you start

Make sure you are anAdminuser 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 theNotion 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.configuredo|config|
config.token=ENV['NOTION_API_TOKEN']
end

For Rails projects, the snippet above would go toconfig/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 supportscursor paginationfor methods that allow it, such asusers_list.Supply a block and the client will make repeated requests adjusting the value ofstart_cursorwith every response. The default page size is set to 100 (Notion’s current default and maximum) and can be adjusted viaNotion::Client.config.default_page_sizeor 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 intoNotion rate limiting.(It will pause for 10 seconds before retrying the request, a value that can be overriden withNotion::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 viaNotion::Client.config.default_max_retriesor by passing it directly into the method asmax_retries.

You can also proactively avoid rate limiting by adding a pause between every paginated request with thesleep_intervalparameter, 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 ofPageobjects 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)

SeePaginationfor details about how to iterate through the list.

See the full endpoint documentation onNotion 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 onNotion 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 onNotion Developers.

Retrieve a database

Retrieves aDatabase objectusing the ID specified.

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

See the full endpoint documentation onNotion Developers.

Pages

Retrieve a page

Retrieves aPage objectusing the ID specified.

📘 Responses contains pageproperties,not page content. To fetch page content, use theretrieve block childrenendpoint.

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

See the full endpoint documentation onNotion 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, theproperty valuesof the new page in the properties parameter must conform to the parentdatabase's property schema.

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

The new page may include page content, described asblocksin the children parameter.

The following example creates a new page within the specified database:

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
)

This example creates a new page as a child of an existing page.

properties={
title:[
{
"type":"text",
"text":{
"content":"My favorite food",
"link":null
}
}
]
}
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:{page_id:'feb1cdfaab6a43cea4ecbc9e8de63ef7'},
properties:properties,
children:children
)

See the full endpoint documentation onNotion Developers.

Update page

Updatespage property valuesfor the specified page. Properties that are not set via thepropertiesparameter will remain unchanged.

If the parent is a database, the newproperty valuesin thepropertiesparameter must conform to the parentdatabase'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 onNotion Developers.

Retrieve a page property item

Retrieves aproperty_itemobject for a givenpage_idandproperty_id.Depending on the property type, the object returned will either be a value or apaginatedlist of property item values. SeeProperty item objectsfor specifics.

To obtainproperty_id's, use theRetrieve a database endpoint.

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

See the full endpoint documentation onNotion Developers.

Blocks

Retrieve a block

Retrieves aBlock objectusing the ID specified.

📘 If a block contains the keyhas_children: true,use theRetrieve block childrenendpoint to get the list of children

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

See the full endpoint documentation onNotion 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 (seeBlock objectfor available fields and the expected input for each field).

NoteThe 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 onNotion Developers.

Delete a block

Sets aBlock 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 theUpdate a blockorUpdate pagerespectively.

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

See the full endpoint documentation onNotion Developers.

Retrieve block children

Returns a paginated array of childblock objectscontained 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

SeePaginationfor details about how to iterate through the list.

See the full endpoint documentation onNotion Developers.

Append block children

Creates and appends new children blocks to the parent block specified byblock_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 onNotion Developers.

Comments

Retrieve comments from a page or block by id

client.retrieve_comments(block_id:'1a2f70ab26154dc7a838536a3f430af4')

Create a comment on a page

options={
parent:{page_id:'3e4bc91d36c74de595113b31c6fdb82c'},
rich_text:[
{
text:{
content:'Hello world'
}
}
]
}
client.create_comment(options)

Create a comment on a discussion

options={
discussion_id:'ea116af4839c410bb4ac242a18dc4392',
rich_text:[
{
text:{
content:'Hello world'
}
}
]
}
client.create_comment(options)

See the full endpoint documention onNotion Developers.

Users

Retrieve your token's bot user

Retrieves the botUserassociated with the API token provided in the authorization header. The bot will have anownerfield with information about the person who authorized the integration.

client.me

See the full endpoint documentation onNotion Developers.

Retrieve a user

Retrieves aUserusing the ID specified.

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

See the full endpoint documentation onNotion Developers.

List all users

Returns a paginated list ofUsersfor the workspace.

client.users_list# retrieves the first page

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

client.users_listdo|page|
# paginate through all users
end

SeePaginationfor details about how to iterate through the list.

See the full endpoint documentation onNotion 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.searchdo|page|
# paginate through all search pages
end

SeePaginationfor details about how to iterate through the list.

See the full endpoint documentation onNotion Developers.

Acknowledgements

The code, specs and documentation of this gem are an adaptation of the fantasticSlack Ruby Clientgem. Many thanks to its author and maintainer@dblockandcontributors.