• Stars
    star
    134
  • Rank 270,967 (Top 6 %)
  • Language
    Kotlin
  • License
    MIT License
  • Created over 3 years ago
  • Updated 4 months ago

Reviews

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

Repository Details

A Notion SDK for Any JVM Language

Notion SDK for Any JVM Language

A simple and easy to use client for the Notion API


Maven Central CI Build

Here is a Notion API SDK for any JVM language users 👋

This project aims to provide a Notion API client for any JVM language developers without hurdles. To realize the goal, its code is written in Kotlin with a nice consideration for Java compatibility.

This SDK works on Android runtime and any distributions based on OpenJDK. With regard to programming languages, this project provides out-of-the-box supports for Java (of course!) and Kotlin. We don't have nice wrappers for some other JVM languages such as Scala, Groovy, and Clojure, but your code using this library should work in the languages too.

Getting Started

You can start using this library just by adding notion-sdk-jvm-core dependency to your project.

For Gradle users:

ext.notionSdkVersion = "1.8.0"
dependencies {
  // This dependency is at least required
  implementation("com.github.seratch:notion-sdk-jvm-core:${notionSdkVersion}")
}

For Maven users:

<properties>
  <notion-sdk.version>1.8.0</notion-sdk.version>
</properties>

<dependencies>
  <dependency>
    <groupId>com.github.seratch</groupId>
    <artifactId>notion-sdk-jvm-core</artifactId>
    <version>${notion-sdk.version}</version>
  </dependency>
</dependencies>

As this library is in Kotlin, using in the same language is the smoothest :) Let's start with the following code, which manipulates Notion pages 👋

import notion.api.v1.NotionClient
import notion.api.v1.model.common.ObjectType
import notion.api.v1.model.pages.PageParent
import notion.api.v1.request.search.SearchRequest
import notion.api.v1.model.pages.PageProperty

fun main() {
  NotionClient(token = System.getenv("NOTION_TOKEN")).use { client ->
    // Find the "Test Database" from the list
    val database = client
      .search(
        query = "Test Database",
        filter = SearchRequest.SearchFilter("database", property = "object")
      )
      .results
      .find { it.asDatabase().properties.containsKey("Severity") }
      ?.asDatabase()
      ?: error("Create a database named 'Test Database' and invite this app's user!")
    // Alternatively if you know the UUID of the Database, use `val database = client.retrieveDatabase("...")`.

    // All the options for "Severity" property (select type)
    val severityOptions = database.properties["Severity"]!!.select!!.options!!
    // All the options for "Tags" property (multi_select type)
    val tagOptions = database.properties["Tags"]!!.multiSelect!!.options!!
    // A user object for "Assignee" property (people type)
    val assignee = client.listUsers().results.first() // Just picking a random user.

    // Create a new page in the database
    val newPage = client.createPage(
      // Use the "Test Database" as this page's parent
      parent = PageParent.database(database.id),
      // Set values to the page's properties
      // (Values of referenced options, people, and relations must be pre-defined before this API call!)
      properties = mapOf(
        "Title" to PageProperty(title = "Fix a bug".asRichText()),
        "Severity" to PageProperty(select = severityOptions.single { it.name == "High" }),
        "Tags" to PageProperty(multiSelect = listOf("Tag1", "Tag2").map { tag -> tagOptions.single { it.name == tag } }),
        "Due" to PageProperty(date = PageProperty.Date(start = "2021-05-13", end = "2021-12-31")),
        "Velocity Points" to PageProperty(number = 3),
        "Assignee" to PageProperty(people = listOf(assignee)),
        "Done" to PageProperty(checkbox = true),
        "Link" to PageProperty(url = "https://www.example.com"),
        "Contact" to PageProperty(email = "[email protected]"),
      )
    )
    
    // Properties can be addressed by their ID too.
    val severityId = newPage.properties["Severity"]!!.id

    // Update properties in the page
    val updatedPage = client.updatePage(
        pageId = newPage.id,
        // Update only "Severity" property
        properties = mapOf(
          severityId to PageProperty(select = severityOptions.single { it.name == "Medium" }),
        )
      )

    // Fetch the latest data of the page
    val retrievedPage = client.retrievePage(newPage.id)
  }
}

private fun String.asRichText(): List<PageProperty.RichText> =
  listOf(PageProperty.RichText(text = PageProperty.RichText.Text(content = this)))

Using in Java

Even when you use this SDK in Java and other languages, all the classes/methods should be accessible. If you find issues, please let us know the issue in this project's issue tracker.

package integration_tests;

import notion.api.v1.NotionClient;
import notion.api.v1.model.search.SearchResults;
import org.junit.Assert;

public class Readme {
  public static void main(String[] args) {
    NotionClient client = new NotionClient(System.getenv("NOTION_TOKEN"));
    try {
      SearchResults results = client.search("Test Database");
      Assert.assertNotNull(results);
    } finally {
      client.close();
    }
  }
}

OAuth Support

The Notion app installation via the OAuth flow is also supported. To learn how to implement it, please check an example app built with Ktor web framework in the core library project.

Plugins

By default, the NotionClient utilizes only JDK's java.net.HttpURLConnection and Gson library for JSON serialization.

For HTTP communications and logging, you can easily switch to other implementations.

Pluggable HTTP Client

As some may know, java.net.HttpURLConnection does not support PATCH request method 😢. Thus, the default httpClient has to make an "illegal reflective access" to overcome the limitation for perfoming PATCH method requests (see this class for details).

The PATCH method workaround does not work with OpenJDK 19 or newer. Thus, if you use PATCH method API calls such as PATCH https://api.notion.com/v1/pages/{page_id}, we recommend other httpClient implementations listed below. If you don't use PATCH method APIs at all and don't want to add any extra dependencies, the default httpClient works fine for you.

// Add this if you use java.net.http.HttpClient in JDK 11+
// Please note that this module does not work on Android runtime
implementation("com.github.seratch:notion-sdk-jvm-httpclient:${notionSdkVersion}")

// Add this if you use OkHttp 5.x (still alpha)
// If you have other dependencies relying on okhttp 5.x (e.g., Retrofit)
implementation("com.github.seratch:notion-sdk-jvm-okhttp5:${notionSdkVersion}")

// Add this if you use OkHttp 4.x
// Although the package name is `okhttp3`, the latest version is 4.x
implementation("com.github.seratch:notion-sdk-jvm-okhttp4:${notionSdkVersion}")

// Add this if you use OkHttp 3.x
// If you have other dependencies relying on okhttp 3.x (e.g., Retrofit)
implementation("com.github.seratch:notion-sdk-jvm-okhttp3:${notionSdkVersion}")

You can switch the httpClient in either of the following ways:

import notion.api.v1.NotionClient
import notion.api.v1.http.JavaNetHttpClient

val client = NotionClient(
    token = System.getenv("NOTION_TOKEN"),
    httpClient = JavaNetHttpClient(),
)

or

import notion.api.v1.NotionClient
import notion.api.v1.http.OkHttp3Client

val client = NotionClient(token = System.getenv("NOTION_TOKEN"))
client.httpClient = OkHttp3Client()

Pluggable Logging

You can change the logger property of a NotionClient instances Currently, this library supports its own stdout logger (default), java.util.logging, and slf4j-api based ones. Here are the steps to switch to an slf4j-api logger. Add the following optional module along with your favorite implementation (e.g., logback-classic, slf4j-simple).

implementation("com.github.seratch:notion-sdk-jvm-slf4j:${notionSdkVersion}") // slf4j-api 1.7
implementation("org.slf4j:slf4j-simple:1.7.36")

Now you can switch to your slf4j logger. As with the httpClient example, you can use the setter method too.

import notion.api.v1.NotionClient
import notion.api.v1.http.JavaNetHttpClient
import notion.api.v1.logging.Slf4jLogger

// for slf4j-simple
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug")

val client = NotionClient(
    token = System.getenv("NOTION_TOKEN"),
    httpClient = JavaNetHttpClient(),
    logger = Slf4jLogger(),
)

If you desire to use slf4j-api v2 instead, you can use the module for the major version as below:

implementation("com.github.seratch:notion-sdk-jvm-slf4j2:${notionSdkVersion}") // slf4j-api 2.0
implementation("org.slf4j:slf4j-simple:2.0.0")

Why isn't JSON serialization pluggable?

We don't support other JSON libraries yet. There are two reasons:

Necessity of polymorphic serializers for list objects

In the early development stage of this SDK, we started with kotlinx.serialization. It worked well except for the Search API responses. The results returned by the API requires polymorphic serializers for properties: List<DatabaseProperty | PageProperty> (this is a pseudo-code illustrating the property is a list of union type). We could not find a way to handle the pattern with the library at that time.

Easily enabling camelCased property names

We know a few novel Kotlin libraries do not support the conversions between snake_cased keys and camelCased keys. Although we do respect the opinion and see the benefit, we still prefer consistent field naming in the Java world. This is another major reason why we did not go with either of kotlinx.serialization and Moshi.

Supported Java Runtimes

  • OpenJDK 8 or higher
  • All Android runtime versions supported by Kotlin 1.5

As notion-sdk-jvm-httpclient utilizes java.net.http.HttpClient, the module works with JDK 11 and higher versions.

License

The MIT License

More Repositories

1

AWScala

Using AWS SDK on the Scala REPL
Scala
737
star
2

ChatGPT-in-Slack

Swift demonstration of how to build a Slack app that enables end-users to interact with a ChatGPT bot
Python
428
star
3

gistub

Sharing code snippets in-house
Ruby
242
star
4

kotliquery

A handy Database access library in Kotlin
Kotlin
193
star
5

deepl-for-slack

Slack app for DeepL Translate API users
TypeScript
145
star
6

rspec-kickstarter

RSpec 3 code generator toward existing Ruby code.
Ruby
128
star
7

slack-edge

Slack app development framework for edge functions with streamlined TypeScript support
TypeScript
72
star
8

notion-translator

CLI tool to translate Notion pages into a different language
JavaScript
69
star
9

slack-cloudflare-workers

Slack app development framework for Cloudflare Workers
TypeScript
68
star
10

slack-app-examples

A collection of Slack App examples
TypeScript
59
star
11

bolt-starter

A Bolt ⚡️ app template with useful settings for easier development
JavaScript
52
star
12

chatgpt-on-deno

ChatGPT on Slack's next-gen modular platform
TypeScript
51
star
13

scalikesolr

Apache Solr Client for Scala/Java
Scala
51
star
14

serverless-slack-bolt-aws

Read this issue first - https://github.com/slackapi/bolt/issues/361
JavaScript
43
star
15

bigquery4s

A handy Scala wrapper of Google BigQuery API 's Java Client Library.
Scala
34
star
16

slack-bolt-extensions

Collection of bolt-js InstallationStore/Receiver implementations + Next.js support module
TypeScript
33
star
17

apriori.js

Apriori Algorithm implementation in TypeScript|JavaScript
JavaScript
30
star
18

junithelper

JUnit testing without dull routine
Java
30
star
19

slack-web-api-client

Streamlined Slack Web API client for TypeScript
TypeScript
29
star
20

apriori4j

Apriori Algorithm Implementation in Java, Scala
Java
26
star
21

bolt-on-cloud-functions-for-firebase

Read this issue first - https://github.com/slackapi/bolt/issues/361
JavaScript
24
star
22

finagle-cluster-demo

Finagle Hack-a-thon at Twitter Japan @yakitori
JavaScript
22
star
23

slack-timesheet

Timesheet, a Slack automation platform app for managing work hours
TypeScript
21
star
24

bit-valley-2020-slack-bolt-app

これは BIT VALLEY 2020 でのプレゼンテーション用のデモアプリです。インタラクティブな機能を使ったサンプルとして是非参考にしてみてください! https://git.io/BV_2020_Slack
JavaScript
20
star
25

bolt-on-heroku

Bolt example app in TypeScript on Heroku
TypeScript
16
star
26

slack_learning_app_ja

Slack プラットフォームの機能を学習するためのチュートリアルアプリ
Python
16
star
27

run-on-slack-template

"run-on-slack" app template
TypeScript
16
star
28

seratch-slack-types

Slack API TypeScript types generated by @seratch
TypeScript
15
star
29

inputvalidator

Scala Input Validator with quite readable DSL
Scala
15
star
30

slack-api-workshop-in-fukuoka-2019

Slack API workshop for Japanese developers
JavaScript
14
star
31

sadamasashi-compiler

さだまさしコンパイラ
Scala
14
star
32

slack-weather-radar-map

Japan Weather Radar Map (雨雲レーダー) on Slack ⛈️
TypeScript
13
star
33

deno-slack-data-mapper

A handy way to manage data in Slack's next-generation platform datastores
TypeScript
12
star
34

nhk4s

"NHK 番組表 API" client library for Scala
Scala
12
star
35

ltsv4s

LTSV parser implementation in Scala
Scala
11
star
36

r2dbc-samples-in-scala

Demonstrates how to use R2DBC - Reactive Relational Database Connectivity in Scala
Scala
11
star
37

new-relic-dashboard-in-slack

Tiny Bolt ⚡️ app demonstrating how to build Slack apps utilizing Slack's new features and New Relic APIs
JavaScript
11
star
38

testgenerator

Scala test generator sbt plugin
Scala
10
star
39

run-on-slack-deepl

A "run-on-slack" translator app powered by DeepL APIs
TypeScript
10
star
40

kenall-for-slack

ケンオール API (kenall.jp) を Slack から使えるようにするアプリ
Python
9
star
41

bolt-starter-ts

TypeScript
9
star
42

apriori-algorithm

Apriori Algorithm Ruby implementation
Ruby
9
star
43

send-it-later-for-slack

Send It Later for Slack users
Python
8
star
44

jslack-maintenance-releases

Maintenance releases for the jSlack library
Java
8
star
45

deepl-document-translator-for-slack

Translate the document files in Slack
Python
8
star
46

send-to-notion-in-slack-oss

Send to Notion in Slack (Simplified OSS Edition)
Python
8
star
47

hackernews4s

HackerNews API Client in Scala
Scala
8
star
48

bolt-aws-lambda-proof-of-concept

This repository was created in the aim of demonstrating the possibilities of proper FaaS (AWS Lambda, Google Cloud Functions etc) environment support by Bolt.
TypeScript
8
star
49

slack-new-emoji-notification

New Slack Emoji Notifications Built with Slack's Automation Platform
TypeScript
8
star
50

deepl-jvm

DeepL Kotlin/JavaVM Library
Kotlin
7
star
51

jp-holidays-for-slack

Slack app notifying national holidays in Japan
Python
7
star
52

spring-jersey-archetype

mvn archetype:generate -DarchetypeCatalog=http://seratch.github.com/mvn-repo/releases
Java
7
star
53

working-sql-in-scala

How to work with SQL queries in Scala - ScalikeJDBC, Slick StaticQuery and Anorm.
Scala
7
star
54

python-slack-scim

slack-scim - Slack SCIM API Client
Python
7
star
55

oauth-server-example

Just an OAuth 1.0a server example in Java
Java
7
star
56

slack-next-generation-platform-tutorials

Complete project examples for https://dev.to/seratch/series/21161
TypeScript
6
star
57

taskun

A simple crond thread on the JVM
Java
6
star
58

slack-cli-gh-actions-demo

Demonstrating Slack CLI Deployment Using GitHub Actions
TypeScript
6
star
59

bolt-kotlin-on-aws-lambda

Building Bolt Java apps on AWS Lambda
Kotlin
6
star
60

scalatra-thymeleaf-support

Scalatra Thymeleaf Support
Scala
6
star
61

dallish

An extended Dalli for memcached 1.4.x
Ruby
6
star
62

scaruby

Scala API in Ruby
Ruby
5
star
63

memcachedweaver

Caching methods result on memcached with AOP
Java
5
star
64

xsbt-scalag-plugin

Scala code/resource Generator Plugin for xsbt
Scala
5
star
65

sqlite3-foreigner

foreigner extension for SQLite3 users
Ruby
5
star
66

spring-boot-swagger-demo

Spring Boot example to demonstrate how to integrate Swagger 2.0 and swagger-codegen
Java
5
star
67

deno-daily-notification-workflow

Slack app demonstrating how to build a daily scheduled message notification
TypeScript
5
star
68

gyotaku

Saving complete web pages by using Selenium Web Driver
Scala
5
star
69

bolt-js-aws-lambda

Bolt for JavaScript: AWS Lambda Receiver prototype
TypeScript
5
star
70

slack-mention-reminder

"Mention Reminder" is a custom Slack app that allows you to set up reminders simply by mentioning its bot
TypeScript
5
star
71

signedrequest4j

A Java library supporting OAuth 1.0 signing and verifying
Java
4
star
72

apidays-workshop-2020

Apidays: Slack app workshop
Python
4
star
73

reactive-streams-jdbc

WIP: A sample to show how to work with RDBMS in the Reactive Streams way
Scala
4
star
74

redmine-reverse-scaffold

Rerverse scaffold demo from Redmine database schema
Scala
4
star
75

apache-module-samples

Learning Apache 2.4 module development
C
4
star
76

seratch-slack-app-toolkit

A toolkit to build Slack Apps in TypeScript
TypeScript
4
star
77

cloudflare-ai-translator-in-slack

Swift demonstration of how to utilize Cloudflare Workers AI within Slack's workflows
TypeScript
4
star
78

play-2.5-example

[scalikejdbc-users-group:526]
Scala
4
star
79

kansai-summit-handson

Scala Kansai Summit 2015 【ハンズオン】Skinny Framework 2.0 で試すお手軽 Scala Web アプリ開発
Scala
4
star
80

long-lasting-scala.g8

An sbt project template for long lasting OSS maintainers
Scala
4
star
81

ninja-coffee-example

CoffeeScript, wro4j, WebJars and Ninja Framework
Java
3
star
82

jslack-kotlin-examples

A collection of Slack API examples in Kotlin
Kotlin
3
star
83

scala3-slack-socket-mode-app

Slack Socket Mode App in Scala 3
Scala
3
star
84

deno-slack-data-mapper-starter

deno-slack-data-mapper project template
TypeScript
3
star
85

slack-daily-standup-ja

デイリースクラム(Slack スタンダードワークフロー)
TypeScript
3
star
86

slack-standard-workflow-collection

Collection of Slack's "standard" workflow templates
TypeScript
3
star
87

skinny-engine-example

Skinny Framework 2 has its own engine instead of Scalatra.
Scala
3
star
88

scalikejdbc-play-plugin

DEPRECATED: Moved to https://github.com/scalikejdbc/scalikejdbc-play-support
Scala
3
star
89

new-relic-dashboard-in-slack-kotlin

Tiny Lightning ⚡️ app demonstrating how to build Slack apps utilizing Slack's new features and New Relic APIs
Kotlin
3
star
90

slack-edge-app-template

Slack app project template demonstrating how to manage your slack-edge app using Slack CLI
TypeScript
3
star
91

rpscala-scalatra-example

#rpscala 72 Scalatra Example App
Scala
2
star
92

deno-slack-source-file-resolver

Automatically resolve functions' source_file for Slack's next-generation platform apps
TypeScript
2
star
93

my-tour-of-go

https://tour.golang.org/
Go
2
star
94

slack-remote-functions-on-cloudflare

Build a remote function for Slack's automation platform on Cloudflare Workers
TypeScript
2
star
95

bootstrap-downloader

curl -L http://git.io/bootstrap-downloader | sh
JavaScript
2
star
96

deno-editable-form-submissions

Slack automation platform app demonstrating how to build a workflow that allows a submitter to edit or delete their channel message
TypeScript
2
star
97

go-slack-sdk-experimental

WIP: Experimental Slack SDK in Go
Go
2
star
98

scalatra-with-jsp

A Scalatra demo app which works with legacy jsp files.
Scala
2
star
99

hash-ninja

Hash operations toolkit for Ruby Ninja
Ruby
2
star
100

scalatra-openid-provider-support

Scalatra OpenID Provider Support
Scala
2
star