notion-sdk-patterns
Apply production-ready @notionhq/client SDK patterns for TypeScript and Python. Use when implementing Notion integrations, building database queries with filters and sorts, handling pagination, constructing rich text blocks, or establishing team coding standards for Notion API usage. Trigger with "notion SDK patterns", "notion best practices", "notion code patterns", "idiomatic notion", "notion typescript", "notion python SDK".
What this skill does
# Notion SDK Patterns
## Overview
Production-ready patterns for the official Notion SDK (`@notionhq/client` for TypeScript, `notion-client` for Python) covering client initialization, database queries with filters and sorts, cursor-based pagination, rich text construction, block manipulation, and type-safe error handling using SDK error codes.
## Prerequisites
- **Node.js 18+** with `@notionhq/client` v2.x installed, or **Python 3.9+** with `notion-client`
- A Notion integration token (`NOTION_TOKEN`) from [notion.so/my-integrations](https://www.notion.so/my-integrations)
- Target databases/pages shared with the integration (Share > Invite > select your integration)
- TypeScript 5+ with strict mode enabled (for TypeScript patterns)
## Instructions
### Step 1 — Initialize the Client and Query Databases
Set up the SDK client and execute filtered, sorted database queries.
**TypeScript — Client initialization:**
```typescript
import { Client } from '@notionhq/client';
const notion = new Client({ auth: process.env.NOTION_TOKEN });
```
**Database query with filter and sort:**
```typescript
const response = await notion.databases.query({
database_id,
filter: {
property: 'Status',
select: {
equals: 'Active',
},
},
sorts: [
{
property: 'Created',
direction: 'descending',
},
],
});
```
**Compound filters** combine conditions with `and`/`or`:
```typescript
const response = await notion.databases.query({
database_id,
filter: {
and: [
{ property: 'Status', select: { equals: 'Active' } },
{ property: 'Priority', select: { does_not_equal: 'Low' } },
{ property: 'Assignee', people: { is_not_empty: true } },
],
},
sorts: [
{ property: 'Priority', direction: 'ascending' },
{ property: 'Created', direction: 'descending' },
],
});
```
**Python — Client initialization and query:**
```python
from notion_client import Client
notion = Client(auth=os.environ["NOTION_TOKEN"])
results = notion.databases.query(
database_id=db_id,
filter={
"property": "Status",
"select": {"equals": "Active"},
},
sorts=[{"property": "Created", "direction": "descending"}],
)
```
### Step 2 — Paginate Results and Manipulate Blocks
The Notion API returns at most 100 results per request. Use cursor-based pagination to retrieve all records.
**Cursor-based pagination:**
```typescript
let cursor: string | undefined;
do {
const { results, next_cursor, has_more } = await notion.databases.query({
database_id,
start_cursor: cursor,
});
// Process each page of results
for (const page of results) {
console.log(page.id);
}
cursor = has_more && next_cursor ? next_cursor : undefined;
} while (cursor);
```
**Reusable pagination helper (generic):**
```typescript
type PaginatedFn<T> = (args: { start_cursor?: string }) => Promise<{
results: T[];
has_more: boolean;
next_cursor: string | null;
}>;
async function collectPaginated<T>(fn: PaginatedFn<T>): Promise<T[]> {
const all: T[] = [];
let cursor: string | undefined;
do {
const response = await fn({ start_cursor: cursor });
all.push(...response.results);
cursor = response.has_more && response.next_cursor
? response.next_cursor
: undefined;
} while (cursor);
return all;
}
// Usage — collect all pages from a database
const allPages = await collectPaginated((args) =>
notion.databases.query({ database_id: 'db-id', ...args })
);
```
**Read block children (page content):**
```typescript
const blocks = await notion.blocks.children.list({
block_id: pageId,
});
for (const block of blocks.results) {
if ('type' in block) {
console.log(block.type, block.id);
}
}
```
**Append blocks to a page:**
```typescript
await notion.blocks.children.append({
block_id: pageId,
children: [
{
type: 'paragraph',
paragraph: {
rich_text: [{ text: { content: 'Hello from the SDK' } }],
},
},
{
type: 'heading_2',
heading_2: {
rich_text: [{ text: { content: 'Section Title' } }],
},
},
{
type: 'bulleted_list_item',
bulleted_list_item: {
rich_text: [{ text: { content: 'First item' } }],
},
},
],
});
```
**Rich text with annotations and links:**
```typescript
const richTextBlock = {
type: 'text' as const,
text: {
content: 'Hello',
link: { url: 'https://developers.notion.com' },
},
annotations: {
bold: true,
italic: false,
strikethrough: false,
underline: false,
code: false,
color: 'default' as const,
},
};
```
**Python — block manipulation:**
```python
# List block children
blocks = notion.blocks.children.list(block_id=page_id)
# Append blocks
notion.blocks.children.append(
block_id=page_id,
children=[
{
"type": "paragraph",
"paragraph": {
"rich_text": [{"text": {"content": "Added via Python SDK"}}]
},
}
],
)
```
### Step 3 — Handle Errors with SDK Error Codes
Use the SDK's built-in error type guards instead of catching generic exceptions.
**TypeScript — type-safe error handling:**
```typescript
import {
isNotionClientError,
APIErrorCode,
ClientErrorCode,
} from '@notionhq/client';
try {
const page = await notion.pages.retrieve({ page_id: pageId });
} catch (error) {
if (isNotionClientError(error)) {
switch (error.code) {
case APIErrorCode.ObjectNotFound:
console.error('Page not found — ensure it is shared with the integration');
break;
case APIErrorCode.Unauthorized:
console.error('Invalid token — regenerate at notion.so/my-integrations');
break;
case APIErrorCode.RateLimited:
console.error(`Rate limited — retry after ${error.headers?.['retry-after']}s`);
break;
case APIErrorCode.ValidationError:
console.error(`Invalid request: ${error.message}`);
break;
case APIErrorCode.ConflictError:
console.error('Conflict — resource was modified by another request');
break;
case ClientErrorCode.RequestTimeout:
console.error('Request timed out — increase timeoutMs or check network');
break;
default:
console.error(`Notion error [${error.code}]: ${error.message}`);
}
} else {
throw error; // Re-throw non-Notion errors
}
}
```
**Python — error handling:**
```python
from notion_client import Client, APIResponseError
try:
results = notion.databases.query(database_id=db_id)
except APIResponseError as e:
if e.code == "object_not_found":
print("Database not found or not shared with integration")
elif e.code == "rate_limited":
retry_after = e.headers.get("retry-after", "unknown")
print(f"Rate limited — retry after {retry_after}s")
elif e.code == "unauthorized":
print("Invalid token — regenerate at notion.so/my-integrations")
elif e.code == "validation_error":
print(f"Validation error: {e.message}")
else:
raise
```
**Safe wrapper pattern (Result type):**
```typescript
async function safeNotionCall<T>(
operation: () => Promise<T>,
): Promise<{ data: T; error: null } | { data: null; error: string }> {
try {
const data = await operation();
return { data, error: null };
} catch (error: unknown) {
if (isNotionClientError(error)) {
return { data: null, error: `[${error.code}] ${error.message}` };
}
return { data: null, error: String(error) };
}
}
// Usage
const result = await safeNotionCall(() =>
notion.pages.retrieve({ page_id: pageId })
);
if (result.error) {
console.error(result.error);
} else {
console.log(result.data.id);
}
```
## Output
Applying these patterns produces:
- A configured SDK client connected via `NOTION_TOKEN`
- Database queries with filters, sorts, and compound conditions
- Complete result sets through cursor-based pagination (no missed records)
- Block rRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.