Skip to content

notion-dotnet/notion-sdk-net

Repository files navigation

Notion SDK for .Net

A simple and easy to use client for the Notion API


GitHub release (latest SemVer) GitHub

Build Status Build artifacts Publish Code CodeQL

GitHub last commit GitHub commit activity GitHub commit activity GitHub commit activity

GitHub repo size Lines of code

Provides the following packages:

Package Downloads Nuget
Notion.Net Nuget Nuget Nuget (with prereleases)

Installation

.Net CLI

dotnet add package Notion.Net

Note: Default Notion-Version used by NuGet package versions

Package version Notion-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 to create an integration and find the token. You can learn more about authorization here.

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

var client = NotionClientFactory.Create(new ClientOptions
{
    AuthToken = "<Token>"
});

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

var usersList = await client.Users.ListAsync();

Dependency Injection

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

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

Then inject INotionClient into your services:

public class MyService
{
    private readonly INotionClient _notionClient;
    
    public MyService(INotionClient notionClient)
    {
        _notionClient = notionClient;
    }
    
    public async Task<Database> GetDatabaseAsync(string databaseId)
    {
        return await _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"
var dateFilter = new DateFilter("When", onOrAfter: DateTime.Now);

var queryParams = new DatabasesQueryParameters { Filter = dateFilter };
var pages = await client.Databases.QueryAsync(databaseId, queryParams);

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

var filter = new TextFilter("Name", startsWith: "Mr", contains: "John"); // WRONG FILTER USAGE

To use complex filters, use class CompoundFilter. 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:

var selectFilter = new SelectFilter("Urgency", equal: "High");
var assigneeFilter = new PeopleFilter("Assignee", contains: "some-uuid");
var dateFilter = new DateFilter("Due", pastMonth: new Dictionary<string, object>());

var orGroup = new List<Filter> { assigneeFilter, selectFilter };
var complexFiler = new CompoundFilter(
    and: new List<Filter> { dateFilter, new CompoundFilter(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 of ILoggerFactory interface exposed by Microsoft.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 instance
NotionClientLogging.ConfigureLogger(logger);

You can set the LogLevel in config file.

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

You can also refer to the examples/list-users example.

Error Handling

The SDK provides specific exception types for common API errors:

try
{
    var page = await client.Pages.RetrieveAsync(pageId);
}
catch (NotionApiRateLimitException rateLimitEx)
{
    // Handle rate limit - check rateLimitEx.RetryAfter for when to retry
    Console.WriteLine($"Rate limited. Retry after: {rateLimitEx.RetryAfter}");
}
catch (NotionApiException apiEx)
{
    // Handle other API errors
    Console.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

var newPage = await client.Pages.CreateAsync(new PagesCreateParameters
{
    Parent = new DatabaseParentInput { DatabaseId = databaseId },
    Properties = new Dictionary<string, PropertyValue>
    {
        {
            "Title", new TitlePropertyValue
            {
                Title = new List<RichTextBase>
                {
                    new RichTextText { Text = new Text { Content = "My New Page" } }
                }
            }
        }
    }
});

Working with Blocks

// Append a paragraph block to a page
var appendResponse = await client.Blocks.AppendChildrenAsync(new BlockAppendChildrenRequest
{
    BlockId = pageId,
    Children = new List<ICreateBlock>
    {
        new ParagraphBlock
        {
            Paragraph = new ParagraphBlock.ParagraphData
            {
                RichText = new List<RichTextBase>
                {
                    new RichTextText
                    {
                        Text = new Text { Content = "This is a new paragraph!" }
                    }
                }
            }
        }
    }
});

File Upload

// Create file upload
var fileUpload = await client.FileUploads.CreateAsync(new CreateFileUploadRequest
{
    Name = "example.pdf",
    FileType = FileType.Pdf,
    FileSize = fileSize,
    ExpiresTime = DateTime.UtcNow.AddHours(1)
});

// Send the file
var sendResponse = await client.FileUploads.SendAsync(new SendFileUploadRequest
{
    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 detailed Contribution Guideline defined here - we will continue to improve it.