notion_sdk/
lib.rs

1//! [![github]](https://github.com/emo-crab/notion-rs) [![crates-io]](https://crates.io/crates/notion-sdk) [![docs-rs]](crate)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6//!
7//!
8//! UnOfficial Notion SDK mplemented by rust
9//!
10//!
11//! ## Examples
12//! ```rust,no_run
13//! use notion_sdk::NotionApi;
14//! async fn main(){
15//!     let notion = NotionApi::new("token")?;
16//!     let me = notion.users_me().await;
17//!     println!("{:#?}", me);
18//! }
19//!
20//! ```
21pub mod block;
22pub mod comment;
23pub mod common;
24pub mod database;
25pub mod error;
26pub mod pages;
27pub mod pagination;
28pub mod search;
29pub mod user;
30
31use crate::error::Error;
32use crate::pagination::Object;
33use reqwest::{ClientBuilder, RequestBuilder};
34
35const NOTION_API_VERSION: &str = "2022-02-22";
36
37/// Notion Api Client
38#[derive(Debug, Clone)]
39pub struct NotionApi {
40    base_path: String,
41    client: reqwest::Client,
42}
43
44/// new a notion api client with api token
45impl NotionApi {
46    pub fn new<T>(api_token: T) -> Result<Self, Error> where
47        T: Into<String> + std::fmt::Display, {
48        let mut headers = reqwest::header::HeaderMap::new();
49        headers.insert(
50            "Notion-Version",
51            reqwest::header::HeaderValue::from_static(NOTION_API_VERSION),
52        );
53        let mut auth_value = reqwest::header::HeaderValue::from_str(&format!("Bearer {api_token}"))
54            .map_err(|source| Error::InvalidApiToken { source })?;
55        auth_value.set_sensitive(true);
56        headers.insert(reqwest::header::AUTHORIZATION, auth_value);
57        let api_client = ClientBuilder::new()
58            .default_headers(headers)
59            .build()
60            .map_err(|source| Error::ErrorBuildingClient { source })?;
61        Ok(NotionApi {
62            base_path: "https://api.notion.com/v1".to_owned(),
63            client: api_client,
64        })
65    }
66}
67
68impl NotionApi {
69    async fn request(&self, request: RequestBuilder) -> Result<Object, Error> {
70        let request = request.build()?;
71        let json = self
72            .client
73            .execute(request)
74            .await
75            .map_err(|source| Error::RequestFailed { source })?
76            .text()
77            .await
78            .map_err(|source| Error::ResponseIoError { source })?;
79        let result =
80            serde_json::from_str(&json).map_err(|source| Error::JsonParseError { source })?;
81        match result {
82            Object::Error { error } => Err(Error::ApiError { error }),
83            response => Ok(response),
84        }
85    }
86}