notion

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 28, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package notion provides a client for the Notion API.

Index

Constants

View Source
const (
	// BaseURL is the Notion API base URL.
	BaseURL = "https://api.notion.com/v1"
	// APIVersion is the Notion API version to use.
	APIVersion = "2022-06-28"
)

Variables

This section is empty.

Functions

func NormalizeID

func NormalizeID(id string) string

NormalizeID removes dashes from a Notion ID.

func PageIDFromContext added in v0.4.0

func PageIDFromContext(ctx context.Context) string

PageIDFromContext extracts the page ID from context, returns empty string if not set.

func ParsePageIDOrURL

func ParsePageIDOrURL(input string) (string, error)

ParsePageIDOrURL extracts a Notion page ID from a URL or returns the ID if already bare. Handles various formats: - https://www.notion.so/Page-Title-abc123def456 - https://notion.so/workspace/Page-abc123def456 - abc123def456 (raw ID without dashes) - abc123-def4-5678-90ab-cdef12345678 (raw ID with dashes).

func ParseRichText

func ParseRichText(richText []RichText) string

ParseRichText converts rich text array to plain string.

func ParseRichTextToMarkdown

func ParseRichTextToMarkdown(richText []RichText) string

ParseRichTextToMarkdown converts rich text array to markdown string.

func WithPageID added in v0.4.0

func WithPageID(ctx context.Context, pageID string) context.Context

WithPageID returns a new context with the page ID stored.

Types

type APIError

type APIError struct {
	Object  string `json:"object"`
	Status  int    `json:"status"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

APIError represents a Notion API error.

func (*APIError) Error

func (e *APIError) Error() string

type Annotations

type Annotations struct {
	Bold          bool   `json:"bold"`
	Italic        bool   `json:"italic"`
	Strikethrough bool   `json:"strikethrough"`
	Underline     bool   `json:"underline"`
	Code          bool   `json:"code"`
	Color         string `json:"color"`
}

Annotations contains text formatting.

type Block

type Block struct {
	Object         string    `json:"object"`
	ID             string    `json:"id"`
	Parent         Parent    `json:"parent"`
	Type           string    `json:"type"`
	CreatedTime    time.Time `json:"created_time"`
	LastEditedTime time.Time `json:"last_edited_time"`
	CreatedBy      User      `json:"created_by"`
	LastEditedBy   User      `json:"last_edited_by"`
	HasChildren    bool      `json:"has_children"`
	Archived       bool      `json:"archived"`
	InTrash        bool      `json:"in_trash"`

	// Block type specific content
	Paragraph        *ParagraphBlock       `json:"paragraph,omitempty"`
	Heading1         *HeadingBlock         `json:"heading_1,omitempty"`
	Heading2         *HeadingBlock         `json:"heading_2,omitempty"`
	Heading3         *HeadingBlock         `json:"heading_3,omitempty"`
	BulletedListItem *ListItemBlock        `json:"bulleted_list_item,omitempty"`
	NumberedListItem *ListItemBlock        `json:"numbered_list_item,omitempty"`
	ToDo             *ToDoBlock            `json:"to_do,omitempty"`
	Toggle           *ToggleBlock          `json:"toggle,omitempty"`
	Code             *CodeBlock            `json:"code,omitempty"`
	Quote            *QuoteBlock           `json:"quote,omitempty"`
	Callout          *CalloutBlock         `json:"callout,omitempty"`
	Divider          *DividerBlock         `json:"divider,omitempty"`
	Image            *FileBlock            `json:"image,omitempty"`
	Video            *FileBlock            `json:"video,omitempty"`
	File             *FileBlock            `json:"file,omitempty"`
	PDF              *FileBlock            `json:"pdf,omitempty"`
	Bookmark         *BookmarkBlock        `json:"bookmark,omitempty"`
	Equation         *EquationBlock        `json:"equation,omitempty"`
	TableOfContents  *TableOfContentsBlock `json:"table_of_contents,omitempty"`
	ChildPage        *ChildPageBlock       `json:"child_page,omitempty"`
	ChildDatabase    *ChildDatabaseBlock   `json:"child_database,omitempty"`
	SyncedBlock      *SyncedBlockBlock     `json:"synced_block,omitempty"`
	Table            *TableBlock           `json:"table,omitempty"`
	TableRow         *TableRowBlock        `json:"table_row,omitempty"`
	ColumnList       *ColumnListBlock      `json:"column_list,omitempty"`
	Column           *ColumnBlock          `json:"column,omitempty"`
	LinkToPage       *LinkToPageBlock      `json:"link_to_page,omitempty"`
	Embed            *EmbedBlock           `json:"embed,omitempty"`

	// Children holds nested blocks (populated by recursive fetch)
	Children []Block `json:"-"`
}

Block represents a Notion block.

type BlockChildrenResponse

type BlockChildrenResponse struct {
	Object     string  `json:"object"`
	Results    []Block `json:"results"`
	NextCursor *string `json:"next_cursor"`
	HasMore    bool    `json:"has_more"`
	Type       string  `json:"type"`
}

BlockChildrenResponse represents the response from block children endpoint.

type BookmarkBlock

type BookmarkBlock struct {
	URL     string     `json:"url"`
	Caption []RichText `json:"caption"`
}

BookmarkBlock contains bookmark content.

type Bot

type Bot struct {
	Object string `json:"object"`
	ID     string `json:"id"`
	Name   string `json:"name"`
	Type   string `json:"type"`
	Bot    struct {
		Owner struct {
			Type      string `json:"type"`
			Workspace bool   `json:"workspace"`
		} `json:"owner"`
		WorkspaceName string `json:"workspace_name"`
	} `json:"bot"`
}

Bot represents the response from /users/me for a bot.

type CalloutBlock

type CalloutBlock struct {
	RichText []RichText `json:"rich_text"`
	Icon     *Icon      `json:"icon"`
	Color    string     `json:"color"`
}

CalloutBlock contains callout content.

type ChildDatabaseBlock

type ChildDatabaseBlock struct {
	Title string `json:"title"`
}

ChildDatabaseBlock references a child database.

type ChildPageBlock

type ChildPageBlock struct {
	Title string `json:"title"`
}

ChildPageBlock references a child page.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a Notion API client with rate limiting.

func NewClient

func NewClient(token string, opts ...ClientOption) *Client

NewClient creates a new Notion API client.

func (*Client) GetAllBlockChildren

func (c *Client) GetAllBlockChildren(ctx context.Context, blockID string, depth int) ([]Block, error)

GetAllBlockChildren retrieves all children of a block recursively.

func (*Client) GetBlock

func (c *Client) GetBlock(ctx context.Context, blockID string) (*Block, error)

GetBlock retrieves a block by ID.

func (*Client) GetBlockChildren

func (c *Client) GetBlockChildren(ctx context.Context, blockID string, cursor string) (*BlockChildrenResponse, error)

GetBlockChildren retrieves children of a block with pagination.

func (*Client) GetDatabase

func (c *Client) GetDatabase(ctx context.Context, databaseID string) (*Database, error)

GetDatabase retrieves a database by ID.

func (*Client) GetMe

func (c *Client) GetMe(ctx context.Context) (*Bot, error)

GetMe retrieves information about the current bot/user.

func (*Client) GetPage

func (c *Client) GetPage(ctx context.Context, pageID string) (*Page, error)

GetPage retrieves a page by ID.

func (*Client) QueryDatabase

func (c *Client) QueryDatabase(ctx context.Context, databaseID string) ([]DatabasePage, error)

QueryDatabase queries a database and returns all pages.

func (*Client) Search

func (c *Client) Search(ctx context.Context, filter SearchFilter) (*SearchResponse, error)

Search searches for pages and databases.

func (*Client) SearchAllPages

func (c *Client) SearchAllPages(ctx context.Context) ([]Page, error)

SearchAllPages retrieves all pages accessible to the integration. The Notion Search API does not support timestamp filtering. All pages are fetched and sorted by last_edited_time (descending = newest first). Callers should filter results by timestamp after retrieval.

func (*Client) SearchAllPagesWithStop

func (c *Client) SearchAllPagesWithStop(ctx context.Context, shouldStop func([]Page) bool) ([]Page, error)

SearchAllPagesWithStop retrieves all pages accessible to the integration with optional early stopping. The shouldStop function is called after each page batch. If it returns true, pagination stops. Pages are sorted by last_edited_time (descending = newest first).

func (*Client) SearchWorkspacePages

func (c *Client) SearchWorkspacePages(ctx context.Context) ([]Page, error)

SearchWorkspacePages retrieves all pages at workspace level (root pages). These are pages whose parent is a workspace or teamspace, not another page. It searches incrementally and logs progress.

type ClientOption

type ClientOption func(*Client)

ClientOption configures the client.

func WithBaseURL

func WithBaseURL(url string) ClientOption

WithBaseURL sets a custom base URL (useful for testing).

func WithHTTPClient

func WithHTTPClient(c *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client.

func WithLogger

func WithLogger(l *slog.Logger) ClientOption

WithLogger sets a custom logger.

type CodeBlock

type CodeBlock struct {
	RichText []RichText `json:"rich_text"`
	Caption  []RichText `json:"caption"`
	Language string     `json:"language"`
}

CodeBlock contains code content.

type ColumnBlock

type ColumnBlock struct{}

ColumnBlock is a container for column content.

type ColumnListBlock

type ColumnListBlock struct{}

ColumnListBlock is a container for columns.

type Database

type Database struct {
	Object         string         `json:"object"`
	ID             string         `json:"id"`
	CreatedTime    time.Time      `json:"created_time"`
	LastEditedTime time.Time      `json:"last_edited_time"`
	CreatedBy      User           `json:"created_by"`
	LastEditedBy   User           `json:"last_edited_by"`
	Title          []RichText     `json:"title"`
	Description    []RichText     `json:"description"`
	Icon           *Icon          `json:"icon"`
	Cover          *FileBlock     `json:"cover"`
	Properties     map[string]any `json:"properties"`
	Parent         Parent         `json:"parent"`
	URL            string         `json:"url"`
	PublicURL      *string        `json:"public_url"`
	Archived       bool           `json:"archived"`
	InTrash        bool           `json:"in_trash"`
	IsInline       bool           `json:"is_inline"`
}

Database represents a Notion database.

func (*Database) GetTitle

func (d *Database) GetTitle() string

GetTitle returns the database title as a string.

type DatabasePage

type DatabasePage struct {
	Object         string                     `json:"object"`
	ID             string                     `json:"id"`
	CreatedTime    time.Time                  `json:"created_time"`
	LastEditedTime time.Time                  `json:"last_edited_time"`
	CreatedBy      User                       `json:"created_by"`
	LastEditedBy   User                       `json:"last_edited_by"`
	Parent         Parent                     `json:"parent"`
	Archived       bool                       `json:"archived"`
	InTrash        bool                       `json:"in_trash"`
	Properties     map[string]json.RawMessage `json:"properties"`
	URL            string                     `json:"url"`
	PublicURL      *string                    `json:"public_url"`
}

DatabasePage represents a page returned from a database query. It has a simpler structure than Page to handle the complex property types.

func (*DatabasePage) Title

func (p *DatabasePage) Title() string

Title extracts the title from database page properties.

func (*DatabasePage) ToPage

func (p *DatabasePage) ToPage() *Page

ToPage converts a DatabasePage to a regular Page.

type DateProperty

type DateProperty struct {
	Start    string  `json:"start"`
	End      *string `json:"end,omitempty"`
	TimeZone *string `json:"time_zone,omitempty"`
}

DateProperty represents a date property value.

type DividerBlock

type DividerBlock struct{}

DividerBlock is an empty struct for dividers.

type EmbedBlock

type EmbedBlock struct {
	URL string `json:"url"`
}

EmbedBlock contains embed URL.

type Equation

type Equation struct {
	Expression string `json:"expression"`
}

Equation represents an inline equation.

type EquationBlock

type EquationBlock struct {
	Expression string `json:"expression"`
}

EquationBlock contains equation content.

type ExternalFile

type ExternalFile struct {
	URL string `json:"url"`
}

ExternalFile represents an external file URL.

type File

type File struct {
	URL        string    `json:"url"`
	ExpiryTime time.Time `json:"expiry_time"`
}

File represents a Notion-hosted file.

type FileBlock

type FileBlock struct {
	Type     string        `json:"type"`
	Caption  []RichText    `json:"caption"`
	External *ExternalFile `json:"external,omitempty"`
	File     *File         `json:"file,omitempty"`
	Name     string        `json:"name,omitempty"`
}

FileBlock contains file/image/video content.

type FileObject

type FileObject struct {
	Name     string        `json:"name"`
	Type     string        `json:"type"`
	File     *File         `json:"file,omitempty"`
	External *ExternalFile `json:"external,omitempty"`
}

FileObject represents a file in a files property.

type FormulaValue

type FormulaValue struct {
	Type    string        `json:"type"`
	String  *string       `json:"string,omitempty"`
	Number  *float64      `json:"number,omitempty"`
	Boolean *bool         `json:"boolean,omitempty"`
	Date    *DateProperty `json:"date,omitempty"`
}

FormulaValue represents a formula property value.

type HeadingBlock

type HeadingBlock struct {
	RichText     []RichText `json:"rich_text"`
	Color        string     `json:"color"`
	IsToggleable bool       `json:"is_toggleable"`
}

HeadingBlock contains heading content.

type Icon

type Icon struct {
	Type     string        `json:"type"`
	Emoji    string        `json:"emoji,omitempty"`
	External *ExternalFile `json:"external,omitempty"`
	File     *File         `json:"file,omitempty"`
}

Icon represents an emoji or external icon.

type Link struct {
	URL string `json:"url"`
}

Link represents a URL link.

type LinkToPageBlock

type LinkToPageBlock struct {
	Type       string `json:"type"`
	PageID     string `json:"page_id,omitempty"`
	DatabaseID string `json:"database_id,omitempty"`
}

LinkToPageBlock references another page.

type ListItemBlock

type ListItemBlock struct {
	RichText []RichText `json:"rich_text"`
	Color    string     `json:"color"`
}

ListItemBlock contains list item content.

type Mention

type Mention struct {
	Type string `json:"type"`
	User *User  `json:"user,omitempty"`
	Page *struct {
		ID string `json:"id"`
	} `json:"page,omitempty"`
	Database *struct {
		ID string `json:"id"`
	} `json:"database,omitempty"`
	Date *struct {
		Start string  `json:"start"`
		End   *string `json:"end"`
	} `json:"date,omitempty"`
	LinkPreview *struct {
		URL string `json:"url"`
	} `json:"link_preview,omitempty"`
}

Mention represents a mention in rich text.

type Page

type Page struct {
	Object         string     `json:"object"`
	ID             string     `json:"id"`
	CreatedTime    time.Time  `json:"created_time"`
	LastEditedTime time.Time  `json:"last_edited_time"`
	CreatedBy      User       `json:"created_by"`
	LastEditedBy   User       `json:"last_edited_by"`
	Parent         Parent     `json:"parent"`
	Archived       bool       `json:"archived"`
	InTrash        bool       `json:"in_trash"`
	Properties     Properties `json:"properties"`
	URL            string     `json:"url"`
	PublicURL      *string    `json:"public_url"`
}

Page represents a Notion page.

func (*Page) Title

func (p *Page) Title() string

Title extracts the title from page properties.

type ParagraphBlock

type ParagraphBlock struct {
	RichText []RichText `json:"rich_text"`
	Color    string     `json:"color"`
}

ParagraphBlock contains paragraph content.

type Parent

type Parent struct {
	Type       string `json:"type"`
	PageID     string `json:"page_id,omitempty"`
	DatabaseID string `json:"database_id,omitempty"`
	BlockID    string `json:"block_id,omitempty"`
	Workspace  bool   `json:"workspace,omitempty"`
	SpaceID    string `json:"space_id,omitempty"` // For teamspaces
}

Parent represents the parent of a page or block.

func (*Parent) ID

func (p *Parent) ID() string

ID returns the parent ID regardless of type (page, database, block, or space).

func (*Parent) IsWorkspaceLevel

func (p *Parent) IsWorkspaceLevel() bool

IsWorkspaceLevel returns true if the parent is at workspace level (private or teamspace).

type Properties

type Properties map[string]Property

Properties is a map of property name to property value.

type Property

type Property struct {
	ID   string `json:"id"`
	Type string `json:"type"`

	// Title property (for title type)
	Title []RichText `json:"title,omitempty"`

	// Rich text property
	RichText []RichText `json:"rich_text,omitempty"`

	// Number property
	Number *float64 `json:"number,omitempty"`

	// Select property
	Select *SelectOption `json:"select,omitempty"`

	// Multi-select property
	MultiSelect []SelectOption `json:"multi_select,omitempty"`

	// Status property
	Status *SelectOption `json:"status,omitempty"`

	// Date property
	Date *DateProperty `json:"date,omitempty"`

	// Checkbox property
	Checkbox bool `json:"checkbox,omitempty"`

	// URL property
	URL *string `json:"url,omitempty"`

	// Email property
	Email *string `json:"email,omitempty"`

	// Phone number property
	PhoneNumber *string `json:"phone_number,omitempty"`

	// Files property
	Files []FileObject `json:"files,omitempty"`

	// People property
	People []User `json:"people,omitempty"`

	// Relation property
	Relation []RelationItem `json:"relation,omitempty"`

	// Rollup property
	Rollup *RollupValue `json:"rollup,omitempty"`

	// Formula property
	Formula *FormulaValue `json:"formula,omitempty"`

	// Created by property
	CreatedBy *User `json:"created_by,omitempty"`

	// Last edited by property
	LastEditedBy *User `json:"last_edited_by,omitempty"`

	// Created time property
	CreatedTime *string `json:"created_time,omitempty"`

	// Last edited time property
	LastEditedTime *string `json:"last_edited_time,omitempty"`

	// Unique ID property
	UniqueID *UniqueIDValue `json:"unique_id,omitempty"`

	// Verification property
	Verification *VerificationValue `json:"verification,omitempty"`
}

Property represents a page property. This handles various property types from both regular pages and database pages.

type QueryDatabaseResponse

type QueryDatabaseResponse struct {
	Object     string         `json:"object"`
	Results    []DatabasePage `json:"results"`
	NextCursor *string        `json:"next_cursor"`
	HasMore    bool           `json:"has_more"`
	Type       string         `json:"type"`
}

QueryDatabaseResponse represents the response from querying a database.

type QuoteBlock

type QuoteBlock struct {
	RichText []RichText `json:"rich_text"`
	Color    string     `json:"color"`
}

QuoteBlock contains quote content.

type RelationItem

type RelationItem struct {
	ID string `json:"id"`
}

RelationItem represents an item in a relation property.

type RichText

type RichText struct {
	Type        string       `json:"type"`
	PlainText   string       `json:"plain_text"`
	Href        *string      `json:"href"`
	Annotations *Annotations `json:"annotations"`
	Text        *TextContent `json:"text,omitempty"`
	Mention     *Mention     `json:"mention,omitempty"`
	Equation    *Equation    `json:"equation,omitempty"`
}

RichText represents formatted text.

type RollupValue

type RollupValue struct {
	Type   string        `json:"type"`
	Number *float64      `json:"number,omitempty"`
	Date   *DateProperty `json:"date,omitempty"`
	Array  []any         `json:"array,omitempty"`
}

RollupValue represents a rollup property value.

type SearchFilter

type SearchFilter struct {
	Query       string
	FilterType  string // "page" or "database"
	StartCursor string
	PageSize    int
	// Sort by last_edited_time (only "ascending" or "descending" for timestamp sorting)
	SortDirection string // "ascending" or "descending"
}

SearchFilter configures the search query.

type SearchResponse

type SearchResponse struct {
	Object     string  `json:"object"`
	Results    []Page  `json:"results"`
	NextCursor *string `json:"next_cursor"`
	HasMore    bool    `json:"has_more"`
	Type       string  `json:"type"`
}

SearchResponse represents the response from the search endpoint.

type SelectOption

type SelectOption struct {
	ID    string `json:"id,omitempty"`
	Name  string `json:"name"`
	Color string `json:"color,omitempty"`
}

SelectOption represents a select/multi-select/status option.

type SyncedBlockBlock

type SyncedBlockBlock struct {
	SyncedFrom *SyncedFrom `json:"synced_from"`
}

SyncedBlockBlock contains synced block reference.

type SyncedFrom

type SyncedFrom struct {
	Type    string `json:"type"`
	BlockID string `json:"block_id"`
}

SyncedFrom references the original synced block.

type TableBlock

type TableBlock struct {
	TableWidth      int  `json:"table_width"`
	HasColumnHeader bool `json:"has_column_header"`
	HasRowHeader    bool `json:"has_row_header"`
}

TableBlock contains table settings.

type TableOfContentsBlock

type TableOfContentsBlock struct {
	Color string `json:"color"`
}

TableOfContentsBlock contains table of contents settings.

type TableRowBlock

type TableRowBlock struct {
	Cells [][]RichText `json:"cells"`
}

TableRowBlock contains table row cells.

type TextContent

type TextContent struct {
	Content string `json:"content"`
	Link    *Link  `json:"link"`
}

TextContent contains text content.

type ToDoBlock

type ToDoBlock struct {
	RichText []RichText `json:"rich_text"`
	Checked  bool       `json:"checked"`
	Color    string     `json:"color"`
}

ToDoBlock contains to-do content.

type ToggleBlock

type ToggleBlock struct {
	RichText []RichText `json:"rich_text"`
	Color    string     `json:"color"`
}

ToggleBlock contains toggle content.

type UniqueIDValue

type UniqueIDValue struct {
	Prefix *string `json:"prefix,omitempty"`
	Number int     `json:"number"`
}

UniqueIDValue represents a unique ID property value.

type User

type User struct {
	Object string `json:"object"`
	ID     string `json:"id"`
}

User represents a Notion user reference.

type VerificationValue

type VerificationValue struct {
	State      string        `json:"state"`
	VerifiedBy *User         `json:"verified_by,omitempty"`
	Date       *DateProperty `json:"date,omitempty"`
}

VerificationValue represents a verification property value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL