Skip to content

Commit f60bc5d

Browse files
authored
feat(examples): add examples (#57)
1 parent 7bbb2d5 commit f60bc5d

44 files changed

Lines changed: 6076 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,20 @@ The `Client` supports the following options on initialization. These options can
113113
| `baseUrl` | `"https://api.notion.com"` | `string` | The root URL for sending API requests. This can be changed to test with a mock server. |
114114
| `httpClient` | Default Http Client | `Psr\Http\Client\ClientInterface` | The Http Client used to make request on the Notion API. This can be change to customize the base Http Client or replace with a mocked Http Client. |
115115

116+
## Examples
117+
118+
The `examples/` directory contains a comprehensive set of usage examples that demonstrate how to use the SDK for various tasks, from basic API calls to complex integrations:
119+
120+
- **[01-intro-to-notion-api](examples/01-intro-to-notion-api/)** - Basic database queries and page creation
121+
- **[02-parse-text-from-any-block](examples/02-parse-text-from-any-block/)** - Extract text content from all block types
122+
- **[03-web-form](examples/03-web-form/)** - Web form to Notion page integration
123+
- **[04-generate-random-data](examples/04-generate-random-data/)** - Populate databases with sample data
124+
- **[05-notify-on-update](examples/05-notify-on-update/)** - Email notifications for database changes
125+
- **[06-notion-github-sync](examples/06-notion-github-sync/)** - GitHub issues synchronization
126+
- **[07-oauth-flow](examples/07-oauth-flow/)** - Complete OAuth 2.0 implementation
127+
128+
Each example is self-contained with its own dependencies, documentation, and setup instructions.
129+
116130
## Contributing
117131

118132
Contributions are welcome! To contribute, please familiarize yourself with
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Your Notion integration token.
2+
NOTION_TOKEN=
3+
4+
# The ID of the database you want this script to interact with.
5+
# The database must be shared with your integration.
6+
NOTION_DATABASE_ID=
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/vendor/
2+
.env
3+
composer.lock
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Introduction to the Notion API with PHP
2+
3+
This example demonstrates the basics of using the `notion-sdk-php` library. It's a simple command-line script that:
4+
5+
1. Connects to the Notion API
6+
2. Queries an existing database and lists its pages
7+
3. Adds a new page to that database
8+
9+
## Prerequisites
10+
11+
- PHP 7.4 or higher
12+
- Composer
13+
- Notion Integration Token
14+
- Notion Database shared with your integration
15+
16+
## Setup
17+
18+
### 1. Install Dependencies
19+
20+
Navigate to this directory and install the required packages using Composer:
21+
22+
```bash
23+
cd examples/01-intro-to-notion-api
24+
composer install
25+
```
26+
27+
### 2. Environment Configuration
28+
29+
Create a `.env` file by copying the example file:
30+
31+
```bash
32+
cp .env.example .env
33+
```
34+
35+
Open the `.env` file and add your Notion integration token and database ID:
36+
37+
```dotenv
38+
NOTION_TOKEN="secret_..."
39+
NOTION_DATABASE_ID="..."
40+
```
41+
42+
## Usage
43+
44+
Execute the script from your terminal:
45+
46+
```bash
47+
php index.php
48+
```
49+
50+
The script will:
51+
- Connect to your Notion workspace
52+
- List existing pages in the specified database
53+
- Create a new page with a timestamped title
54+
- Display the URL of the newly created page
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"name": "brd6/notion-sdk-php-example-intro",
3+
"description": "A basic example demonstrating how to query a database and create a page with the Notion SDK for PHP.",
4+
"license": "MIT",
5+
"type": "project",
6+
"keywords": [
7+
"notion",
8+
"notion-sdk",
9+
"notion-api",
10+
"php",
11+
"example"
12+
],
13+
"require": {
14+
"php": "^7.4 || ^8",
15+
"brd6/notion-sdk-php": "dev-main",
16+
"nyholm/psr7": "^1.5",
17+
"symfony/http-client": "^5.4",
18+
"vlucas/phpdotenv": "^5.4"
19+
},
20+
"config": {
21+
"sort-packages": true
22+
},
23+
"scripts": {
24+
"start": "php index.php"
25+
}
26+
}
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
require_once __DIR__ . '/vendor/autoload.php';
6+
7+
use Brd6\NotionSdkPhp\Client;
8+
use Brd6\NotionSdkPhp\ClientOptions;
9+
use Brd6\NotionSdkPhp\Exception\ApiResponseException;
10+
use Brd6\NotionSdkPhp\Resource\Page;
11+
use Brd6\NotionSdkPhp\Resource\Page\Parent\DatabaseIdParent;
12+
use Brd6\NotionSdkPhp\Resource\Page\PropertyValue\TitlePropertyValue;
13+
use Brd6\NotionSdkPhp\Resource\RichText\Text;
14+
use Dotenv\Dotenv;
15+
16+
function loadEnvironmentVariables(): void
17+
{
18+
if (!file_exists(__DIR__ . '/.env')) {
19+
echo "Error: .env file not found!\n";
20+
echo "Please create a .env file by copying env.example:\n";
21+
echo " cp .env.example .env\n";
22+
echo "Then add your Notion token and database ID to the .env file.\n";
23+
exit(1);
24+
}
25+
26+
$dotenv = Dotenv::createImmutable(__DIR__);
27+
$dotenv->load();
28+
}
29+
30+
function validateRequiredEnvironmentVariables(): void
31+
{
32+
$requiredVars = ['NOTION_TOKEN', 'NOTION_DATABASE_ID'];
33+
34+
foreach ($requiredVars as $var) {
35+
if (empty($_ENV[$var])) {
36+
echo "Error: Environment variable $var is required but not set.\n";
37+
echo "Please check your .env file and ensure all variables are configured.\n";
38+
exit(1);
39+
}
40+
}
41+
}
42+
43+
function createNotionClient(): Client
44+
{
45+
$options = (new ClientOptions())->setAuth($_ENV['NOTION_TOKEN']);
46+
return new Client($options);
47+
}
48+
49+
function listDatabasePages(Client $notion, string $databaseId): void
50+
{
51+
echo "Fetching pages from your database...\n\n";
52+
53+
$results = $notion->databases()->query($databaseId);
54+
$pages = $results->getResults();
55+
56+
if (empty($pages)) {
57+
echo "No pages found in the database.\n";
58+
return;
59+
}
60+
61+
echo "Found " . count($pages) . " page(s):\n";
62+
foreach ($pages as $page) {
63+
$properties = $page->getProperties();
64+
$title = 'Untitled';
65+
66+
foreach ($properties as $propertyName => $property) {
67+
if ($property instanceof TitlePropertyValue) {
68+
$titleRichTexts = $property->getTitle();
69+
if (!empty($titleRichTexts)) {
70+
$title = $titleRichTexts[0]->getText()?->getContent() ?? 'Untitled';
71+
}
72+
break;
73+
}
74+
}
75+
76+
echo " - $title\n";
77+
}
78+
79+
echo "\n";
80+
}
81+
82+
function getTitlePropertyName(Client $notion, string $databaseId): ?string
83+
{
84+
$database = $notion->databases()->retrieve($databaseId);
85+
$properties = $database->getProperties();
86+
87+
foreach ($properties as $propertyName => $property) {
88+
if ($property->getType() === 'title') {
89+
return $propertyName;
90+
}
91+
}
92+
93+
return null;
94+
}
95+
96+
function createNewPage(Client $notion, string $databaseId): void
97+
{
98+
echo "Creating a new page in your database...\n";
99+
100+
$titlePropertyName = getTitlePropertyName($notion, $databaseId);
101+
102+
if ($titlePropertyName === null) {
103+
echo "Error: No title property found in the database.\n";
104+
return;
105+
}
106+
107+
$page = new Page();
108+
109+
$parent = (new DatabaseIdParent())->setDatabaseId($databaseId);
110+
$page->setParent($parent);
111+
112+
$titleContent = 'New Entry from PHP SDK - ' . date('Y-m-d H:i:s');
113+
$titleProperty = (new TitlePropertyValue())->setTitle([Text::fromContent($titleContent)]);
114+
115+
$page->setProperties([$titlePropertyName => $titleProperty]);
116+
117+
$createdPage = $notion->pages()->create($page);
118+
119+
echo "Successfully created new page!\n";
120+
echo "Title: $titleContent\n";
121+
echo "Page URL: " . $createdPage->getUrl() . "\n";
122+
}
123+
124+
function main(): void
125+
{
126+
try {
127+
echo "Notion SDK PHP - Basic Example\n";
128+
echo "===============================\n\n";
129+
130+
loadEnvironmentVariables();
131+
validateRequiredEnvironmentVariables();
132+
133+
$notion = createNotionClient();
134+
$databaseId = $_ENV['NOTION_DATABASE_ID'];
135+
136+
listDatabasePages($notion, $databaseId);
137+
createNewPage($notion, $databaseId);
138+
139+
echo "\nExample completed successfully!\n";
140+
141+
} catch (ApiResponseException $e) {
142+
echo "Notion API Error: " . $e->getMessage() . "\n";
143+
echo "Please check your token and database ID, and ensure the database is shared with your integration.\n";
144+
exit(1);
145+
} catch (Exception $e) {
146+
echo "Error: " . $e->getMessage() . "\n";
147+
exit(1);
148+
}
149+
}
150+
151+
main();
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Your Notion integration token.
2+
NOTION_TOKEN=
3+
4+
# The ID of the page you want this script to parse.
5+
# The page must be shared with your integration.
6+
NOTION_PAGE_ID=
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/vendor/
2+
.env
3+
composer.lock
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Parse Text from Any Block Type
2+
3+
This example demonstrates how to use the `notion-sdk-php` to recursively fetch all blocks on a page and extract their complete text content. This is useful for tasks like indexing page content for search.
4+
5+
The script handles pagination and nested blocks (like toggles or columns) to ensure all text is extracted.
6+
7+
## Prerequisites
8+
9+
- PHP 7.4 or higher
10+
- Composer
11+
- Notion Integration Token
12+
- Notion Page shared with your integration
13+
14+
## Setup
15+
16+
### 1. Install Dependencies
17+
18+
Navigate to this directory and install the required packages using Composer:
19+
20+
```bash
21+
cd examples/02-parse-text-from-any-block
22+
composer install
23+
```
24+
25+
### 2. Environment Configuration
26+
27+
Create a `.env` file by copying the example file:
28+
29+
```bash
30+
cp .env.example .env
31+
```
32+
33+
Open the `.env` file and add your Notion integration token and page ID:
34+
35+
```dotenv
36+
NOTION_TOKEN="secret_..."
37+
NOTION_PAGE_ID="..."
38+
```
39+
40+
## Usage
41+
42+
Execute the script from your terminal:
43+
44+
```bash
45+
php index.php
46+
```
47+
48+
The script will:
49+
- Connect to your Notion workspace
50+
- Recursively fetch all blocks from the specified page
51+
- Extract text content from each block type
52+
- Handle nested blocks (toggles, columns, etc.)
53+
- Output the complete concatenated text content
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"name": "brd6/notion-sdk-php-example-parse-text",
3+
"description": "An example script that recursively fetches all blocks on a page and extracts the text content.",
4+
"license": "MIT",
5+
"type": "project",
6+
"keywords": [
7+
"notion",
8+
"notion-sdk",
9+
"notion-api",
10+
"php",
11+
"example",
12+
"text-extraction"
13+
],
14+
"require": {
15+
"php": "^7.4 || ^8",
16+
"brd6/notion-sdk-php": "dev-main",
17+
"nyholm/psr7": "^1.5",
18+
"symfony/http-client": "^5.4",
19+
"vlucas/phpdotenv": "^5.4"
20+
},
21+
"config": {
22+
"sort-packages": true
23+
},
24+
"scripts": {
25+
"start": "php index.php"
26+
}
27+
}

0 commit comments

Comments
 (0)