• Stars
    star
    111
  • Rank 314,510 (Top 7 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 4 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Ruby client for the Notion API

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'

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.

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.

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 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.

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 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.

More Repositories

1

orbit-model

A framework for building high gravity communities πŸͺ
CSS
984
star
2

awesome-dot-dev

A list of awesome developer resources on the .dev TLD
178
star
3

orbit-web

The old website for https://orbit.love
Nunjucks
69
star
4

github-actions-templates

Starter GitHub Actions templates to get you up and running with community built integrations
51
star
5

devrel-kpis

A community-sourced resource of metrics and methods for proving ROI through data + story. Advice from around the DevRel and Community world.
JavaScript
50
star
6

orbit-browser-extension

The Orbit extension: all your community data, right at your fingertips.
JavaScript
43
star
7

panoramica

Explore conversational landscapes with AI - built with Next.js, LangChain, Memgraph, and Orbit
JavaScript
21
star
8

community-js-youtube-orbit

Add YouTube interactions into Orbit workspaces
JavaScript
12
star
9

community-ruby-linkedin-orbit

Integrate LinkedIn interactions into Orbit workspaces
Ruby
10
star
10

community-js-stackoverflow-orbit

Add Stack Overflow interactions into Orbit workspaces
JavaScript
6
star
11

community-ruby-dev-orbit

A community project to integrate DEV interactions into Orbit workspaces
Ruby
6
star
12

community-ruby-pipedrive-orbit

Integrate Pipedrive activities into your Orbit workspace
Ruby
6
star
13

community-ruby-notion-orbit

Pull Notion meeting notes into your Orbit workspace
Ruby
4
star
14

community-js-reddit-orbit

Bring subreddit interactions into your Orbit workspace
JavaScript
4
star
15

community-js-producthunt-orbit

Add new upvotes to your Orbit Workspace
JavaScript
4
star
16

orbit-cli

JavaScript
4
star
17

ruby-orbit-activities

Orbit API helper library for Ruby. This client can create, read, update and delete activities in your Orbit workspace.
Ruby
4
star
18

mg-migrations-showcase

Demonstrating our approach to performing migrations on our Memgraph DB. Extracted from Community Search's backend
JavaScript
4
star
19

orbit-generator

Generate fake community data for the Orbit Model
Ruby
3
star
20

community-ruby-meetup-orbit

Integrate Meetup interactions into your Orbit workspace
Ruby
3
star
21

linkedin-auth-app

A Ruby on Rails application to assist in the LinkedIn credentials OAuth 2.0 flow
Ruby
3
star
22

ama

Ask Orbit anything!
2
star
23

community-ruby-planningcenter-orbit

Add interactions from Planning Center into your Orbit workspace
Ruby
2
star
24

test-github-activities

This a public repository only intended to be used for testing Github Activities
1
star
25

panoramica-docs

Panoramica documentation built with Docusaurus
JavaScript
1
star
26

js-orbit-members

Orbit API client for Node.js. API support for member operations.
JavaScript
1
star
27

js-orbit-activities

Orbit API client for Node.js. API support for activity and note operations.
JavaScript
1
star
28

community-ruby-circle-orbit

Integrate Circle interactions into your Orbit workspace
Ruby
1
star
29

ruby-orbit-members

Orbit API helper library for Ruby. This client can create, read, update and delete members and their identities in your Orbit workspace.
Ruby
1
star
30

orbit-community-translations

Community-created translations of Orbit educational content
1
star