Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Official Notion JavaScript Client

License

NotificationsYou must be signed in to change notification settings

LogicCrafterIO/notion-sdk-js

 
 

Repository files navigation

A simple and easy to use client for theNotion API


Build statusnpm version

Installation

npm install @notionhq/client

Usage

Use Notion'sGetting Started Guide to get set up to use Notion's API.

Import and initialize a client using anintegration token or an OAuthaccess token.

const{ Client}=require("@notionhq/client")// Initializing a clientconstnotion=newClient({auth:process.env.NOTION_TOKEN,})

Make a request to any Notion API endpoint.

See the complete list of endpoints in theAPI reference.

;(async()=>{constlistUsersResponse=awaitnotion.users.list({})})()

Each method returns aPromise which resolves the response.

console.log(listUsersResponse)
{  results: [    {      object: 'user',      id: 'd40e767c-d7af-4b18-a86d-55c61f1e39a4',      type: 'person',      person: {        email: 'avo@example.org',      },      name: 'Avocado Lovelace',      avatar_url: 'https://secure.notion-static.com/e6a352a8-8381-44d0-a1dc-9ed80e62b53d.jpg',    },    ...  ]}

Endpoint parameters are grouped into a single object. You don't need to remember which parameters go in the path, query, or body.

constmyPage=awaitnotion.databases.query({database_id:"897e5a76-ae52-4b48-9fdf-e71f5945d1af",filter:{property:"Landmark",rich_text:{contains:"Bridge",},},})

Handling errors

If the API returns an unsuccessful response, the returnedPromise rejects with aAPIResponseError.

The error contains properties from the response, and the most helpful iscode. You can comparecode to the values in theAPIErrorCode object to avoid misspelling error codes.

const{ Client, APIErrorCode}=require("@notionhq/client")try{constnotion=newClient({auth:process.env.NOTION_TOKEN})constmyPage=awaitnotion.databases.query({database_id:databaseId,filter:{property:"Landmark",rich_text:{contains:"Bridge",},},})}catch(error){if(error.code===APIErrorCode.ObjectNotFound){//// For example: handle by asking the user to select a different database//}else{// Other error handling codeconsole.error(error)}}

Logging

The client emits useful information to a logger. By default, it only emits warnings and errors.

If you're debugging an application, and would like the client to log response bodies, set thelogLevel option toLogLevel.DEBUG.

const{ Client, LogLevel}=require("@notionhq/client")constnotion=newClient({auth:process.env.NOTION_TOKEN,logLevel:LogLevel.DEBUG,})

You may also set a customlogger to emit logs to a destination other thanstdout. A custom logger is a function which is called with 3 parameters:logLevel,message, andextraInfo. The custom logger should not return a value.

Client options

TheClient supports the following options on initialization. These options are all keys in the single constructor parameter.

OptionDefault valueTypeDescription
authundefinedstringBearer token for authentication. If left undefined, theauth parameter should be set on each request.
logLevelLogLevel.WARNLogLevelVerbosity of logs the instance will produce. By default, logs are written tostdout.
timeoutMs60_000numberNumber of milliseconds to wait before emitting aRequestTimeoutError
baseUrl"https://api.notion.com"stringThe root URL for sending API requests. This can be changed to test with a mock server.
loggerLog to consoleLoggerA custom logging function. This function is only called when the client emits a log that is equal or greater severity thanlogLevel.
agentDefault node agenthttp.AgentUsed to control creation of TCP sockets. A common use is to proxy requests withhttps-proxy-agent

TypeScript

This package contains type definitions for all request parameters and responses,as well as some useful sub-objects from those entities.

Because errors in TypeScript start with typeany orunknown, you should usetheisNotionClientError type guard to handle them in a type-safe way. EachNotionClientError type is uniquely identified by itserror.code. Codes intheAPIErrorCode enum are returned from the server. Codes in theClientErrorCode enum are produced on the client.

try{constresponse=awaitnotion.databases.query({/* ... */})}catch(error:unknown){if(isNotionClientError(error)){// error is now strongly typed to NotionClientErrorswitch(error.code){caseClientErrorCode.RequestTimeout:// ...breakcaseAPIErrorCode.ObjectNotFound:// ...breakcaseAPIErrorCode.Unauthorized:// ...break// ...default:// you could even take advantage of exhaustiveness checkingassertNever(error.code)}}}

Type guards

There are severaltype guardsprovided to distinguish between full and partial API responses.

Type guard functionPurpose
isFullPageDetermine whether an object is a fullPageObjectResponse
isFullBlockDetermine whether an object is a fullBlockObjectResponse
isFullDatabaseDetermine whether an object is a fullDatabaseObjectResponse
isFullPageOrDatabaseDetermine whether an object is a fullPageObjectResponse orDatabaseObjectResponse
isFullUserDetermine whether an object is a fullUserObjectResponse
isFullCommentDetermine whether an object is a fullCommentObjectResponse

Here is an example of using a type guard:

constfullOrPartialPages=awaitnotion.databases.query({database_id:"897e5a76-ae52-4b48-9fdf-e71f5945d1af",})for(constpageoffullOrPartialPages.results){if(!isFullPageOrDatabase(page)){continue}// The page variable has been narrowed from//      PageObjectResponse | PartialPageObjectResponse | DatabaseObjectResponse | PartialDatabaseObjectResponse// to//      PageObjectResponse | DatabaseObjectResponse.console.log("Created at:",page.created_time)}

Utility functions

This package also exports a few utility functions that are helpful for dealing withany of our paginated APIs.

iteratePaginatedAPI(listFn, firstPageArgs)

This utility turns any paginated API into an async iterator.

Parameters:

  • listFn: Any function on the Notion client that represents a paginated API (i.e. acceptsstart_cursor.) Example:notion.blocks.children.list.
  • firstPageArgs: Arguments that should be passed to the API on the first and subsequent callsto the API, for example ablock_id.

Returns:

Anasync iteratorover results from the API.

Example:

forawait(constblockofiteratePaginatedAPI(notion.blocks.children.list,{block_id:parentBlockId,})){// Do something with block.}

collectPaginatedAPI(listFn, firstPageArgs)

This utility accepts the same arguments asiteratePaginatedAPI, but collectsthe results into an in-memory array.

Before using this utility, check that the data you are dealing with issmall enough to fit in memory.

Parameters:

  • listFn: Any function on the Notion client that represents a paginated API (i.e. acceptsstart_cursor.) Example:notion.blocks.children.list.
  • firstPageArgs: Arguments that should be passed to the API on the first and subsequent callsto the API, for example ablock_id.

Returns:

An array with results from the API.

Example:

constblocks=awaitcollectPaginatedAPI(notion.blocks.children.list,{block_id:parentBlockId,})// Do something with blocks.

Requirements

This package supports the following minimum versions:

  • Runtime:node >= 12
  • Type definitions (optional):typescript >= 4.5

Earlier versions may still work, but we encourage people building new applications to upgrade to the current stable.

Getting help

If you want to submit a feature request for Notion's API, or are experiencing any issues with the API platform, please email us atdevelopers@makenotion.com.

To report issues with the SDK, it is possible tosubmit an issue to this repo. However, we don't monitor these issues very closely. We recommend you reach out to us atdevelopers@makenotion.com instead.

About

Official Notion JavaScript Client

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript99.2%
  • Other0.8%

[8]ページ先頭

©2009-2025 Movatter.jp