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

A Notion SDK for .Net

License

NotificationsYou must be signed in to change notification settings

notion-dotnet/notion-sdk-net

Repository files navigation

A simple and easy to use client for theNotion API


GitHub release (latest SemVer)GitHub

Build StatusBuild artifactsPublish CodeCodeQL

GitHub last commitGitHub commit activityGitHub commit activityGitHub commit activity

GitHub repo sizeLines of code

Provides the following packages:

PackageDownloadsNuget
Notion.NetNugetNugetNuget (with prereleases)

Installation

.Net CLI

dotnet add package Notion.Net

Note: Default Notion-Version used by NuGet package versions

Package versionNotion-Version
4.4.0+2022-06-28
4.3.0+2022-06-28
4.0.0+2022-06-28
3.0.0+2022-02-22
2.0.0+2021-08-16
1.0.0+2021-05-13

Usage

Before getting started, you need tocreate an integration and find the token. You can learn more about authorizationhere.

Import and initialize the client using the integration token created above.

varclient=NotionClientFactory.Create(newClientOptions{AuthToken="<Token>"});

Make A request to any Endpoint. For example you can call below to fetch the paginated list of users.

varusersList=awaitclient.Users.ListAsync();

Dependency Injection

The library provides an extension method to register NotionClient with Microsoft dependency injection.

services.AddNotionClient(options=>{options.AuthToken="<Token>";});

Then injectINotionClient into your services:

publicclassMyService{privatereadonlyINotionClient_notionClient;publicMyService(INotionClientnotionClient){_notionClient=notionClient;}publicasyncTask<Database>GetDatabaseAsync(stringdatabaseId){returnawait_notionClient.Databases.RetrieveAsync(databaseId);}}

Querying a database

After you initialized your client and got an id of a database, you can query it for any contained pages. You can add filters and sorts to your request. Here is a simple example:

// Date filter for page property called "When"vardateFilter=newDateFilter("When",onOrAfter:DateTime.Now);varqueryParams=newDatabasesQueryParameters{Filter=dateFilter};varpages=awaitclient.Databases.QueryAsync(databaseId,queryParams);

Filters constructors contain all possible filter conditions, but you need to choose only condition per filter, all other should benull. So, for example this code would not filter by 2 conditions as one might expect:

varfilter=newTextFilter("Name",startsWith:"Mr",contains:"John");// WRONG FILTER USAGE

To use complex filters, use classCompoundFilter. It allows adding many filters and even nesting compound filters into each other (it works as filter group in Notion interface). Here is an example of filter that would return pages that were due in past month AND either had a certain assignee OR had high urgency:

varselectFilter=newSelectFilter("Urgency",equal:"High");varassigneeFilter=newPeopleFilter("Assignee",contains:"some-uuid");vardateFilter=newDateFilter("Due",pastMonth:newDictionary<string,object>());varorGroup=newList<Filter>{assigneeFilter,selectFilter};varcomplexFiler=newCompoundFilter(and:newList<Filter>{dateFilter,newCompoundFilter(or:orGroup)});

Supported Endpoints

  • Authentication
    • Create access token
    • Revoke access token
    • Introspect token (get token status and details)
    • Refresh access token
  • Databases
    • Retrieve a database
    • Query a database
    • Create a database
    • Update a database
  • Pages
    • Retrieve a page
    • Create a page
    • Update page properties
    • Retrieve page property item
  • Blocks
    • Retrieve a block
    • Update a block
    • Retrieve block children
    • Append block children
    • Delete a block
  • Comments
    • Retrieve comments
    • Create comment
  • Users
    • Retrieve a user
    • List all users
    • Retrieve your token's bot user (me)
  • Search
    • Search across pages and databases
  • File Uploads
    • Create file upload
    • Send file upload
    • Complete file upload (for multi-part uploads)
    • List file uploads
    • Retrieve file upload

Enable internal logs

The library make use ofILoggerFactory interface exposed byMicrosoft.Extensions.Logging. Which allow you to have ability to enable the internal logs when developing application to get additional information.

To enable logging you need to add the below code at startup of the application.

// pass the ILoggerFactory instanceNotionClientLogging.ConfigureLogger(logger);

You can set the LogLevel in config file.

{"Logging": {"LogLevel": {"Notion.Client":"Trace"    }  }}

You can also refer to theexamples/list-users example.

Error Handling

The SDK provides specific exception types for common API errors:

try{varpage=awaitclient.Pages.RetrieveAsync(pageId);}catch(NotionApiRateLimitExceptionrateLimitEx){// Handle rate limit - check rateLimitEx.RetryAfter for when to retryConsole.WriteLine($"Rate limited. Retry after:{rateLimitEx.RetryAfter}");}catch(NotionApiExceptionapiEx){// Handle other API errorsConsole.WriteLine($"API Error:{apiEx.NotionAPIErrorCode} -{apiEx.Message}");}

Examples

The repository includes several example projects to help you get started:

More Code Examples

Creating a Page

varnewPage=awaitclient.Pages.CreateAsync(newPagesCreateParameters{Parent=newDatabaseParentInput{DatabaseId=databaseId},Properties=newDictionary<string,PropertyValue>{{"Title",newTitlePropertyValue{Title=newList<RichTextBase>{newRichTextText{Text=newText{Content="My New Page"}}}}}}});

Working with Blocks

// Append a paragraph block to a pagevarappendResponse=awaitclient.Blocks.AppendChildrenAsync(newBlockAppendChildrenRequest{BlockId=pageId,Children=newList<ICreateBlock>{newParagraphBlock{Paragraph=newParagraphBlock.ParagraphData{RichText=newList<RichTextBase>{newRichTextText{Text=newText{Content="This is a new paragraph!"}}}}}}});

File Upload

// Create file uploadvarfileUpload=awaitclient.FileUploads.CreateAsync(newCreateFileUploadRequest{Name="example.pdf",FileType=FileType.Pdf,FileSize=fileSize,ExpiresTime=DateTime.UtcNow.AddHours(1)});// Send the filevarsendResponse=awaitclient.FileUploads.SendAsync(newSendFileUploadRequest{FileUploadId=fileUpload.Id,FileContent=fileBytes});

Contributors

This project exists thanks to all the people who contribute.

contributor image

Contribution Guideline

Hello! Thank you for choosing to help contribute to this open source library. There are many ways you can contribute and help is always welcome. You can read the detailedContribution Guideline defined here - we will continue to improve it.


[8]ページ先頭

©2009-2025 Movatter.jp