1pub 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#[derive(Debug, Clone)]
39pub struct NotionApi {
40 base_path: String,
41 client: reqwest::Client,
42}
43
44impl 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}