### Install NotionSwift via Swift Package Manager Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Add the library to your project dependencies and target. ```swift dependencies: [ .package(url: "https://github.com/Taichone/swift-notion-api.git", from: "0.9.0") ] ``` ```swift .target( name: "YourTarget", dependencies: [ .product(name: "NotionSwift", package: "swift-notion-api") ] ) ``` -------------------------------- ### Install NotionSwift via CocoaPods Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Add the dependency to your Podfile. ```ruby pod 'NotionSwift', '~> 0.9.0' ``` -------------------------------- ### Get Current Bot User Information Source: https://context7.com/taichone/swift-notion-api/llms.txt Fetches information about the bot user associated with the current integration token. Returns the bot's name and ID. ```swift do { let botUser = try await notion.usersMe() print("Bot Name: \(botUser.name ?? "Unknown")") print("Bot ID: \(botUser.id)") } catch { print("Error: \(error)") } ``` -------------------------------- ### Get Current Bot User API Source: https://context7.com/taichone/swift-notion-api/llms.txt Retrieve information about the bot user associated with the current integration token. ```APIDOC ## Get Current Bot User Retrieve information about the bot user associated with the current integration token. ### Method GET ### Endpoint /users/me ### Response #### Success Response (200) - **id** (string) - The bot user's ID. - **name** (string) - The bot user's name. - **type** (string) - Always 'bot' for this endpoint. #### Response Example ```json { "id": "bot-user-id", "name": "My Notion Bot", "type": "bot" } ``` ``` -------------------------------- ### Initialize NotionClient Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Create a client instance using an access key provider. ```swift let notion = NotionClient(accessKeyProvider: StringAccessKeyProvider(accessKey: "{NOTION_TOKEN}")) ``` -------------------------------- ### Initialize NotionClient Source: https://context7.com/taichone/swift-notion-api/llms.txt Configure the client using an integration token. Custom URLSession configurations can be provided for network request tuning. ```swift import NotionSwift // Basic client initialization let notion = NotionClient( accessKeyProvider: StringAccessKeyProvider(accessKey: "secret_your_integration_token") ) // With custom session configuration for timeouts let sessionConfig = URLSessionConfiguration.default sessionConfig.timeoutIntervalForRequest = 30 sessionConfig.timeoutIntervalForResource = 60 let notionWithConfig = NotionClient( accessKeyProvider: StringAccessKeyProvider(accessKey: "secret_your_integration_token"), sessionConfiguration: sessionConfig ) ``` -------------------------------- ### Create a Database Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Create a new database under a parent page with specified properties. ```swift let parentPageId = Page.Identifier("e67db074-973a-4ddb-b397-66d3c75f9ec9") let request = DatabaseCreateRequest( parent: .pageId(parentPageId), icon: .emoji("🤔"), cover: .external(url: "https://images.unsplash.com/photo-1606787366850-de6330128bfc"), title: [ .init(string: "Created at: \(Date())") ], properties: [ "Field 10": .richText ] ) do { let database = try await notion.databaseCreate(request: request) print(database) } catch { print("Error creating database: \(error)") } ``` -------------------------------- ### Configure Logging for NotionSwift Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Sets up logging for the NotionSwift library to track HTTP traffic. Use `.trace` level to see all request content for debugging. ```swift // This code should be in the ApplicationDelegate NotionSwiftEnvironment.logHandler = NotionSwift.PrintLogHandler() // uses print command NotionSwiftEnvironment.logLevel = .trace // show me everything ``` -------------------------------- ### Create a New Database Source: https://context7.com/taichone/swift-notion-api/llms.txt Define a new database structure including title, icon, cover, and property definitions as a child of a page. ```swift let parentPageId = Page.Identifier("e67db074-973a-4ddb-b397-66d3c75f9ec9") let request = DatabaseCreateRequest( parent: .pageId(parentPageId), icon: .emoji("📊"), cover: .external(url: "https://images.unsplash.com/photo-1606787366850-de6330128bfc"), title: [ .init(string: "Project Tasks") ], properties: [ "Name": .title, "Description": .richText, "Status": .select([ .init(name: "Not Started", color: "gray"), .init(name: "In Progress", color: "blue"), .init(name: "Done", color: "green") ]), "Priority": .select([ .init(name: "Low", color: "gray"), .init(name: "Medium", color: "yellow"), .init(name: "High", color: "red") ]), "Due Date": .date, "Completed": .checkbox ] ) do { let database = try await notion.databaseCreate(request: request) print("Created database: \(database.id)") } catch { print("Error: \(error)") } ``` -------------------------------- ### Retrieve a page in Swift Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Fetches page properties or both properties and children blocks. ```swift let pageId = Page.Identifier("{PAGE UUIDv4}") do { let page = try await notion.page(pageId: pageId) print(page) } catch { print("Error retrieving page: \(error)") } ``` ```swift let pageId = Page.Identifier("{PAGE UUIDv4}") do { print("---- Properties -----") let page = try await notion.page(pageId: pageId) print(page) print("---- Children -----") let children = try await notion.blockChildren(blockId: page.id.toBlockIdentifier) print(children) } catch { print("Error: \(error)") } ``` -------------------------------- ### Load Pages in SwiftUI with Async/Await Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Integrates Notion API calls within a SwiftUI view using async/await. Fetches pages from a database and updates the UI. ```swift struct ContentView: View { @State private var pages: [Page] = [] var body: some View { List(pages, id: \.id) { page in Text(page.properties["title"]?.title?.first?.plainText ?? "No title") } .task { await loadPages() } } private func loadPages() async { let notion = NotionClient(accessKeyProvider: StringAccessKeyProvider(accessKey: "{NOTION_TOKEN}")) let databaseId = Database.Identifier("{DATABASE UUIDv4}") do { let result = try await notion.databaseQuery(databaseId: databaseId) pages = result.results } catch { print("Error loading pages: \(error)") } } } ``` -------------------------------- ### Create a page in Swift Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Creates a new page as a child of another page. ```swift let parentPageId = Page.Identifier("{PAGE UUIDv4}") let request = PageCreateRequest( parent: .page(parentPageId), properties: [ "title": .init( type: .title([ .init(string: "Lorem ipsum \(Date())") ]) ) ] ) do { let page = try await notion.pageCreate(request: request) print(page) } catch { print("Error creating page: \(error)") } ``` -------------------------------- ### List Databases via Search Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Use the search endpoint to filter and retrieve available databases. ```swift // fetch available databases do { let searchResult = try await notion.search(request: .init(filter: .database)) let databases = searchResult.results.compactMap { object -> Database? in if case .database(let db) = object { return db } return nil } print(databases) } catch { print("Error fetching databases: \(error)") } ``` -------------------------------- ### Migrate from Callback-based API to Async/Await Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Shows the transformation of a callback-based Notion API call to the modern async/await syntax. This simplifies error handling and improves code readability. ```swift // Old (Callback-based): notion.page(pageId: pageId) { result in switch result { case .success(let page): print(page) case .failure(let error): print(error) } } // New (async/await): do { let page = try await notion.page(pageId: pageId) print(page) } catch { print(error) } ``` -------------------------------- ### Create Notion Page in Database Source: https://context7.com/taichone/swift-notion-api/llms.txt Create a new page as an entry in a database. Requires a valid Database.Identifier. ```swift // Create page in a database let databaseId = Database.Identifier("a1b2c3d4-e5f6-7890-abcd-ef1234567890") let databasePageRequest = PageCreateRequest( parent: .database(databaseId), properties: [ "Name": .init(type: .title([ .init(string: "New Task Item") ])), "Description": .init(type: .richText([ .init(string: "This is the task description with "), .init(string: "bold text", annotations: .bold), .init(string: " and "), .init(string: "italic text", annotations: .italic) ])), "Status": .init(type: .select(.init(name: "Not Started"))), "Priority": .init(type: .select(.init(name: "High"))), "Completed": .init(type: .checkbox(false)) ] ) do { let page = try await notion.pageCreate(request: databasePageRequest) print("Created page: \(page.id)") } catch { print("Error: \(error)") } ``` -------------------------------- ### Configure Logging for Swift Notion API Source: https://context7.com/taichone/swift-notion-api/llms.txt Enable detailed logging for API requests and responses using `NotionSwiftEnvironment`. Choose between a default print handler or implement a custom logger. Set log levels from `.trace` to `.error`. ```swift import NotionSwift // Enable logging with print output NotionSwiftEnvironment.logHandler = PrintLogHandler() NotionSwiftEnvironment.logLevel = .info // .trace for full request/response details // Log levels available: // .trace - Everything including request/response bodies // .debug - Debug information // .info - General information (default) // .warning - Warnings only // .error - Errors only // Custom log handler implementation class CustomLogHandler: LoggerHandler { func log(level: LogLevel, message: String) { // Send to your logging system print("[\(level)] NotionSwift: \(message)") } } NotionSwiftEnvironment.logHandler = CustomLogHandler() ``` -------------------------------- ### Configure NotionClient Network Settings Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Provide a custom URLSessionConfiguration to adjust network timeouts. ```swift let sessionConfig = URLSessionConfiguration.default sessionConfig.timeoutIntervalForRequest = 15 let notion = NotionClient( accessKeyProvider: StringAccessKeyProvider(accessKey: "{NOTION_TOKEN}"), sessionConfiguration: sessionConfig ) ``` -------------------------------- ### List All Workspace Users Source: https://context7.com/taichone/swift-notion-api/llms.txt Retrieves a list of all users (people and bots) within the Notion workspace. Includes handling for pagination to fetch subsequent pages of users if available. ```swift do { let response = try await notion.usersList() for user in response.results { print("[\(user.id)] \(user.name ?? "Unknown")") } // Handle pagination if response.hasMore, let cursor = response.nextCursor { let nextPage = try await notion.usersList(params: BaseQueryParams(startCursor: cursor)) print("Additional users: \(nextPage.results.count)") } } catch { print("Error: \(error)") } ``` -------------------------------- ### Delete or archive a page in Swift Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Archives a page by setting the archived property to true. ```swift let pageId = Page.Identifier("{PAGE UUIDv4}") // Archive page (trash a page) let request = PageUpdateRequest(archived: true) do { let page = try await notion.pageUpdate(pageId: pageId, request: request) print(page) } catch { print("Error deleting page: \(error)") } ``` -------------------------------- ### List All Users API Source: https://context7.com/taichone/swift-notion-api/llms.txt Retrieve all users in the workspace including people and bots. ```APIDOC ## List All Users Retrieve all users in the workspace including people and bots. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **startCursor** (string) - Optional - The cursor to start fetching results from. - **pageSize** (integer) - Optional - The number of results to return per page. ### Response #### Success Response (200) - **results** (array) - An array of user objects. - **nextCursor** (string) - A cursor for fetching the next page of results, if `hasMore` is true. - **hasMore** (boolean) - Indicates if there are more results available. #### Response Example ```json { "results": [ { "id": "user-id-1", "name": "Alice", "type": "person" }, { "id": "user-id-2", "name": "Bot Name", "type": "bot" } ], "nextCursor": "some-cursor", "hasMore": true } ``` ``` -------------------------------- ### Create a database entry in Swift Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Creates a new page within a specified database using PageCreateRequest. ```swift let databaseId = Database.Identifier("{DATABASE UUIDv4}") let request = PageCreateRequest( parent: .database(databaseId), properties: [ "title": .init( type: .title([ .init(string: "Lorem ipsum \(Date())") ]) ), "Field 10": .init( type: .richText([ .init(string: "dolor sit amet") ]) ) ] ) do { let page = try await notion.pageCreate(request: request) print(page) } catch { print("Error creating page: \(error)") } ``` -------------------------------- ### Query Notion Databases Source: https://context7.com/taichone/swift-notion-api/llms.txt Retrieve pages from a database using filters and sorting parameters. Results are returned asynchronously. ```swift let databaseId = Database.Identifier("a1b2c3d4-e5f6-7890-abcd-ef1234567890") // Query all pages in database do { let result = try await notion.databaseQuery(databaseId: databaseId) for page in result.results { let title = page.getTitle()?.first?.plainText ?? "Untitled" print("Page: \(title)") } } catch { print("Error: \(error)") } // Query with filters and sorting let params = DatabaseQueryParams( filter: .and([ .property(name: "Status", type: .status(.equals("In Progress"))), .property(name: "Priority", type: .select(.contains("High"))) ]), sorts: [ .descending(timestamp: .lastEditedTime) ], pageSize: 50 ) do { let filteredResult = try await notion.databaseQuery(databaseId: databaseId, params: params) print("Found \(filteredResult.results.count) matching pages") } catch { print("Error: \(error)") } ``` -------------------------------- ### Create Notion Page as Child Source: https://context7.com/taichone/swift-notion-api/llms.txt Create a new page as a child of another existing page. Requires a valid Page.Identifier for the parent. ```swift // Create page as child of another page let parentPageId = Page.Identifier("c3d4e5f6-a7b8-9012-cdef-345678901234") let childPageRequest = PageCreateRequest( parent: .page(parentPageId), properties: [ "title": .init(type: .title([ .init(string: "My New Sub-Page") ])) ], children: [ .heading1(["Welcome to My Page"]), .paragraph([ "This is the first paragraph with ", .init(string: "formatted", annotations: .bold), " text." ]) ] ) do { let childPage = try await notion.pageCreate(request: childPageRequest) print("Created child page: \(childPage.url)") } catch { print("Error: \(error)") } ``` -------------------------------- ### Create Page Source: https://context7.com/taichone/swift-notion-api/llms.txt Create a new page as a child of another page or as an entry in a database. ```APIDOC ## Create Page ### Description Create a new page as a child of another page or as an entry in a database. ### Method POST ### Endpoint `/pages` ### Parameters #### Request Body - **parent** (object) - Required - Specifies the parent of the new page. Can be a database or another page. - **database_id** (string) - Required if parent type is database. - **page_id** (string) - Required if parent type is page. - **properties** (object) - Required - A map of property names to their values for the new page. - **children** (array of block objects) - Optional - Content to add to the new page. ### Request Example (Create page in a database) ```json { "parent": { "database_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" }, "properties": { "Name": { "title": [ { "plain_text": "New Task Item" } ] }, "Description": { "rich_text": [ { "plain_text": "This is the task description with ", "annotations": { "bold": true } }, { "plain_text": "bold text", "annotations": { "bold": true } }, { "plain_text": " and " }, { "plain_text": "italic text", "annotations": { "italic": true } } ] }, "Status": { "select": { "name": "Not Started" } }, "Priority": { "select": { "name": "High" } }, "Completed": { "checkbox": false } } } ``` ### Request Example (Create page as child of another page) ```json { "parent": { "page_id": "c3d4e5f6-a7b8-9012-cdef-345678901234" }, "properties": { "title": { "title": [ { "plain_text": "My New Sub-Page" } ] } }, "children": [ { "object": "block", "type": "heading_1", "heading_1": { "rich_text": [ { "plain_text": "Welcome to My Page" } ] } }, { "object": "block", "type": "paragraph", "paragraph": { "rich_text": [ { "plain_text": "This is the first paragraph with " }, { "plain_text": "formatted", "annotations": { "bold": true } }, { "plain_text": " text." } ] } } ] } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the newly created page. - **url** (string) - The URL of the newly created page. #### Response Example ```json { "id": "new-page-id-12345", "url": "https://www.notion.so/your-workspace/new-page-id-12345" } ``` ``` -------------------------------- ### Retrieve Notion Page Source: https://context7.com/taichone/swift-notion-api/llms.txt Fetch a page's properties and metadata. Page content (blocks) must be fetched separately. Requires a valid Page.Identifier. ```swift let pageId = Page.Identifier("b2c3d4e5-f6a7-8901-bcde-f23456789012") do { let page = try await notion.page(pageId: pageId) print("Page ID: \(page.id)") print("URL: \(page.url)") print("Archived: \(page.archived)") print("Created: \(page.createdTime)") print("Last edited: \(page.lastEditedTime)") // Access title property if let title = page.getTitle() { print("Title: \(title.map { $0.plainText ?? "" }.joined())") } // Access other properties for (name, property) in page.properties { print("Property '\(name)': \(property.type)") } } catch { print("Error: \(error)") } ``` -------------------------------- ### Retrieve a Database Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Fetch details of a specific database by its identifier. ```swift let databaseId = Database.Identifier("{DATABASE UUIDv4}") do { let database = try await notion.database(databaseId: databaseId) print(database) } catch { print("Error retrieving database: \(error)") } ``` -------------------------------- ### Retrieve Database Metadata Source: https://context7.com/taichone/swift-notion-api/llms.txt Fetch the schema, properties, and metadata for a specific database. ```swift let databaseId = Database.Identifier("a1b2c3d4-e5f6-7890-abcd-ef1234567890") do { let database = try await notion.database(databaseId: databaseId) print("Database: \(database.title.first?.plainText ?? "Untitled")") print("URL: \(database.url)") print("Properties:") for (name, property) in database.properties { print(" - \(name): \(property.type)") } } catch { print("Error: \(error)") } ``` -------------------------------- ### Handle Notion API Errors Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Demonstrates how to handle specific Notion API errors using do-catch blocks with async/await. Catches HTTP errors, decoding errors, and other general errors. ```swift do { let page = try await notion.page(pageId: pageId) // Success - use page } catch NotionClientError.httpError(let statusCode) { print("HTTP Error: \(statusCode)") } catch NotionClientError.decodingError(let decodingError) { print("Decoding Error: \(decodingError)") } catch { print("Other Error: \(error)") } ``` -------------------------------- ### List All Users Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Retrieves a list of all users associated with the Notion workspace. This operation does not require any specific user ID. ```swift do { let users = try await notion.usersList() print(users) } catch { print("Error listing users: \(error)") } ``` -------------------------------- ### Search All Pages and Databases Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Performs a general search across all pages and databases without specific filters. This returns all accessible content. ```swift do { let searchResult = try await notion.search() print(searchResult) } catch { print("Error searching: \(error)") } ``` -------------------------------- ### Retrieve block children in Swift Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Fetches the first level of children for a given block. ```swift let pageId = Block.Identifier("{PAGE UUIDv4}") do { let children = try await notion.blockChildren(blockId: pageId) print(children) } catch { print("Error retrieving block children: \(error)") } ``` -------------------------------- ### Retrieve Page Source: https://context7.com/taichone/swift-notion-api/llms.txt Fetch a page's properties and metadata. Page content (blocks) must be fetched separately using blockChildren. ```APIDOC ## Retrieve Page ### Description Fetch a page's properties and metadata. Page content (blocks) must be fetched separately using blockChildren. ### Method GET ### Endpoint `/pages/{page_id}` ### Parameters #### Path Parameters - **page_id** (string) - Required - The ID of the page to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the page. - **url** (string) - The URL of the page. - **archived** (boolean) - Whether the page is archived. - **created_time** (string) - The creation timestamp of the page. - **last_edited_time** (string) - The last edited timestamp of the page. - **properties** (object) - A map of property names to their values. #### Response Example ```json { "id": "b2c3d4e5-f6a7-8901-bcde-f23456789012", "url": "https://www.notion.so/your-workspace/b2c3d4e5f6a78901bcdef23456789012", "archived": false, "created_time": "2023-10-27T10:00:00.000Z", "last_edited_time": "2023-10-27T10:30:00.000Z", "properties": { "Name": { "title": [ { "plain_text": "Example Page Title" } ] }, "Status": { "select": { "name": "To Do" } } } } ``` ``` -------------------------------- ### Query a Database Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Retrieve pages within a specific database using its identifier. ```swift let databaseId = Database.Identifier("{DATABASE UUIDv4}") do { let result = try await notion.databaseQuery(databaseId: databaseId) print(result) } catch { print("Error querying database: \(error)") } ``` -------------------------------- ### Update a block in Swift Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Updates the content of an existing block. ```swift let blockId = Block.Identifier("{BLOCK UUIDv4}") let text: [RichText] = [ "Current time: ", .init(string: Date().description, annotations: .bold) ] let block = UpdateBlock(type: .paragraph(text: text)) do { let updatedBlock = try await notion.blockUpdate(blockId: blockId, value: block) print("Updated: \(updatedBlock)") } catch { print("Error updating block: \(error)") } ``` -------------------------------- ### Update a Database Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Modify an existing database's metadata and properties. ```swift let id = Database.Identifier("{DATABASE UUIDv4}") // update cover, icon & add a new field let request = DatabaseUpdateRequest( title: nil, icon: .emoji("🤔"), cover: .external(url: "https://images.unsplash.com/photo-1606787366850-de6330128bfc"), properties: [ "Field 10": .richText ] ) do { let database = try await notion.databaseUpdate(databaseId: id, request: request) print(database) } catch { print("Error updating database: \(error)") } ``` -------------------------------- ### Integrate NotionSwift with SwiftUI Source: https://context7.com/taichone/swift-notion-api/llms.txt Uses the NotionClient to fetch and display database tasks within a SwiftUI view using the .task modifier for asynchronous data loading. ```swift import SwiftUI import NotionSwift struct TaskListView: View { @State private var tasks: [Page] = [] @State private var isLoading = true @State private var errorMessage: String? private let notion = NotionClient( accessKeyProvider: StringAccessKeyProvider(accessKey: "secret_your_token") ) private let databaseId = Database.Identifier("your-database-id") var body: some View { NavigationStack { Group { if isLoading { ProgressView("Loading tasks...") } else if let error = errorMessage { ContentUnavailableView("Error", systemImage: "exclamationmark.triangle", description: Text(error)) } else { List(tasks, id: \.id) { task in TaskRowView(task: task) } .refreshable { await loadTasks() } } } .navigationTitle("Tasks") } .task { await loadTasks() } } private func loadTasks() async { isLoading = true errorMessage = nil do { let params = DatabaseQueryParams( filter: .property(name: "Completed", type: .checkbox(.equals(false))), sorts: [.descending(timestamp: .lastEditedTime)] ) let result = try await notion.databaseQuery(databaseId: databaseId, params: params) tasks = result.results } catch { errorMessage = error.localizedDescription } isLoading = false } } struct TaskRowView: View { let task: Page var body: some View { VStack(alignment: .leading) { Text(task.getTitle()?.first?.plainText ?? "Untitled") .font(.headline) Text("Last edited: \(task.lastEditedTime.formatted())") .font(.caption) .foregroundStyle(.secondary) } } } ``` -------------------------------- ### Update page properties in Swift Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Updates specific properties of an existing page. ```swift let pageId = Page.Identifier("{PAGE UUIDv4}") // update title property let request = PageUpdateRequest( properties: [ .name("title"): .init( type: .title([ .init(string: "Updated at: \(Date())") ]) ) ] ) do { let page = try await notion.pageUpdate(pageId: pageId, request: request) print(page) } catch { print("Error updating page: \(error)") } ``` -------------------------------- ### Build Complex Database Query Filters in Swift Source: https://context7.com/taichone/swift-notion-api/llms.txt Construct sophisticated filters for Notion database queries, including text, number, checkbox, select, multi-select, date, and status properties. Supports compound filters (AND/OR) and nested logic. Requires `DatabaseQueryParams`. ```swift let databaseId = Database.Identifier("a1b2c3d4-e5f6-7890-abcd-ef1234567890") // Text property filters let titleFilter = DatabaseFilter.property(name: "Name", type: .title(.contains("Important"))) let textFilter = DatabaseFilter.property(name: "Notes", type: .richText(.isNotEmpty)) // Number filters let numberFilter = DatabaseFilter.property(name: "Amount", type: .number(.greaterThan(100))) // Checkbox filter let checkboxFilter = DatabaseFilter.property(name: "Completed", type: .checkbox(.equals(false))) // Select/Multi-select filters let selectFilter = DatabaseFilter.property(name: "Status", type: .select(.contains("Active"))) let multiSelectFilter = DatabaseFilter.property(name: "Tags", type: .multiSelect(.contains("Priority"))) // Date filters let dateFilter = DatabaseFilter.property(name: "Due Date", type: .date(.before(Date()))) let createdFilter = DatabaseFilter.property(name: "Created", type: .createdTime(.pastWeek)) // Status filter let statusFilter = DatabaseFilter.property(name: "Status", type: .status(.doesNotEqual("Done"))) // Compound filters with AND let andFilter = DatabaseFilter.and([ .property(name: "Status", type: .status(.equals("In Progress"))), .property(name: "Priority", type: .select(.contains("High"))), .property(name: "Completed", type: .checkbox(.equals(false))) ]) // Compound filters with OR let orFilter = DatabaseFilter.or([ .property(name: "Status", type: .status(.equals("Urgent"))), .property(name: "Due Date", type: .date(.before(Date()))) ]) // Complex nested filters let complexFilter = DatabaseFilter.and([ .property(name: "Archived", type: .checkbox(.equals(false))), DatabaseFilter.or([ .property(name: "Priority", type: .select(.contains("High"))), .property(name: "Due Date", type: .date(.thisWeek)) ]) ]) let params = DatabaseQueryParams( filter: complexFilter, sorts: [ .descending(property: "Priority"), .ascending(timestamp: .createdTime) ] ) do { let results = try await notion.databaseQuery(databaseId: databaseId, params: params) print("Found \(results.results.count) matching entries") } catch { print("Error: \(error)") } ``` -------------------------------- ### Retrieve Block Children with Pagination Source: https://context7.com/taichone/swift-notion-api/llms.txt Fetches direct children of a page or block. Handles pagination for retrieving all nested content. ```swift let pageId = Page.Identifier("b2c3d4e5-f6a7-8901-bcde-f23456789012") let blockId = pageId.toBlockIdentifier do { let response = try await notion.blockChildren(blockId: blockId) for block in response.results { print("Block ID: \(block.id)") print("Type: \(block.type)") print("Has children: \(block.hasChildren)") // Recursively fetch nested blocks if needed if block.hasChildren { let nestedBlocks = try await notion.blockChildren(blockId: block.id) print(" Nested blocks: \(nestedBlocks.results.count)") } } // Handle pagination if let nextCursor = response.nextCursor, response.hasMore { let nextPage = try await notion.blockChildren( blockId: blockId, params: BaseQueryParams(startCursor: nextCursor) ) print("Next page has \(nextPage.results.count) blocks") } } catch { print("Error: \(error)") } ``` -------------------------------- ### Search Notion Content Source: https://context7.com/taichone/swift-notion-api/llms.txt Searches for pages and databases containing specific keywords. Supports filtering by object type and sorting results by last edited time. Handles pagination for large result sets. ```swift // Search for pages and databases containing "Project" do { let results = try await notion.search(request: .init(query: "Project")) for result in results.results { switch result { case .page(let page): let title = page.getTitle()?.first?.plainText ?? "Untitled" print("Page: \(title)") case .database(let database): let title = database.title.first?.plainText ?? "Untitled" print("Database: \(title)") case .unknown: print("Unknown object type") } } } catch { print("Error: \(error)") } // Search for databases only do { let databases = try await notion.search(request: .init(filter: .database)) let dbList = databases.results.compactMap { object -> Database? in if case .database(let db) = object { return db } return nil } print("Found \(dbList.count) databases") } catch { print("Error: \(error)") } // Search for pages only, sorted by last edited time do { let pages = try await notion.search(request: .init( query: "Meeting Notes", sort: .init(timestamp: .lastEditedTime, direction: .descending), filter: .page, pageSize: 20 )) print("Found \(pages.results.count) pages") } catch { print("Error: \(error)") } // Get all accessible content do { let all = try await notion.search() print("Total accessible items: \(all.results.count)") } catch { print("Error: \(error)") } ``` -------------------------------- ### Search Pages and Databases by Title Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Searches for pages and databases whose titles contain the specified text. The query is case-insensitive. ```swift do { let searchResult = try await notion.search( request: .init( query: "Lorem" ) ) print(searchResult) } catch { print("Error searching: \(error)") } ``` -------------------------------- ### Retrieve User Information Source: https://context7.com/taichone/swift-notion-api/llms.txt Fetches detailed information about a specific user using their unique ID. Displays the user's name, avatar URL, and type (person or bot), including email for person types. ```swift let userId = User.Identifier("f6a7b8c9-d0e1-2345-f678-901234567890") do { let user = try await notion.user(userId: userId) print("User ID: \(user.id)") print("Name: \(user.name ?? "Unknown")") print("Avatar: \(user.avatarURL ?? "None")") if let userType = user.type { switch userType { case .person(let person): print("Type: Person") print("Email: \(person.email ?? "Not available")") case .bot: print("Type: Bot") case .unknown: print("Type: Unknown") } } } catch { print("Error: \(error)") } ``` -------------------------------- ### Update Database Source: https://context7.com/taichone/swift-notion-api/llms.txt Update a database's title, icon, cover, or add new properties to its schema. ```APIDOC ## Update Database ### Description Update a database's title, icon, cover, or add new properties to its schema. ### Method PATCH (Assumed based on update operation) ### Endpoint `/databases/{database_id}` (Assumed based on common RESTful practices) ### Parameters #### Path Parameters - **database_id** (string) - Required - The ID of the database to update. #### Request Body - **title** (array of rich text objects) - Optional - The new title for the database. - **icon** (object) - Optional - The new icon for the database. Can be an emoji or an external URL. - **cover** (object) - Optional - The new cover for the database. Can be an external URL. - **properties** (object) - Optional - A map of property names to their schema definitions to add new properties. ### Request Example ```json { "title": [ { "plain_text": "Updated Project Tasks" } ], "icon": { "type": "emoji", "emoji": "🚀" }, "cover": { "type": "external", "external": { "url": "https://images.unsplash.com/photo-1518770660439-4636190af475" } }, "properties": { "Assignee": { "type": "people" }, "Tags": { "type": "multi_select", "multi_select": [ { "name": "Bug", "color": "red" }, { "name": "Feature", "color": "green" }, { "name": "Documentation", "color": "blue" } ] } } } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the updated database. - **title** (array of rich text objects) - The current title of the database. - **icon** (object) - The current icon of the database. - **cover** (object) - The current cover of the database. - **properties** (object) - The current schema of the database properties. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "title": [ { "plain_text": "Updated Project Tasks" } ], "icon": { "type": "emoji", "emoji": "🚀" }, "cover": { "type": "external", "external": { "url": "https://images.unsplash.com/photo-1518770660439-4636190af475" } }, "properties": { "Assignee": { "type": "people" }, "Tags": { "type": "multi_select", "multi_select": [ { "name": "Bug", "color": "red" }, { "name": "Feature", "color": "green" }, { "name": "Documentation", "color": "blue" } ] } } } ``` ``` -------------------------------- ### Append block children in Swift Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Appends various block types including headings, paragraphs, columns, and tables to a page. ```swift let pageId = Block.Identifier("{PAGE UUIDv4}") // append paragraph with styled text to a page. let blocks: [WriteBlock] = [ .heading1(["Heading 1"], color: .orange), .paragraph([ "Lorem ipsum dolor sit amet, ", .init(string: "consectetur", annotations: .bold), " adipiscing elit." ]), .heading2(["Heading 2"], color: .orangeBackground), .columnList(columns: [ .column([ .paragraph(["Column 1"]) ]), .column([ .paragraph(["Column 2"]) ]) ]), try! .table( width: 2, headers: [ ["Header 1"], ["Header 2"] ], rows: [ .row( header: ["Row 1 header"], cells: [ ["Cell 1-1"], ["Cell 1-2"] ] ), .row( cells: [ ["Cell 2-1"], ["Cell 2-2"] ] ) ] ) ] do { let result = try await notion.blockAppend(blockId: pageId, children: blocks) print(result) } catch { print("Error appending blocks: \(error)") } ``` -------------------------------- ### Retrieve Block Children Source: https://context7.com/taichone/swift-notion-api/llms.txt Fetches the direct content blocks of a page or block. Nested content requires additional API calls. ```APIDOC ## Retrieve Block Children ### Description Fetch the content blocks of a page or block. Only returns direct children; nested content requires additional calls. ### Method GET ### Endpoint `/v1/blocks/{block_id}/children` ### Parameters #### Path Parameters - **block_id** (string) - Required - The ID of the block whose children to retrieve. #### Query Parameters - **pageSize** (integer) - Optional - The maximum number of results to return. - **nextCursor** (string) - Optional - The cursor to start after for pagination. ### Response #### Success Response (200) - **object** (string) - Type of object, "list". - **results** (array) - An array of block objects. - **nextCursor** (string) - Optional - The cursor to use to retrieve the next page of results. - **hasMore** (boolean) - Whether there are more pages of results. ### Request Example ```swift let pageId = Page.Identifier("b2c3d4e5-f6a7-8901-bcde-f23456789012") let blockId = pageId.toBlockIdentifier do { let response = try await notion.blockChildren(blockId: blockId) // Process response.results } catch { print("Error: \(error)") } ``` ### Response Example ```json { "object": "list", "results": [ { "object": "block", "id": "...", "type": "paragraph", "paragraph": { "rich_text": [ { "type": "text", "text": { "content": "This is a paragraph." } } ] }, "has_children": false } ], "next_cursor": "...", "has_more": true } ``` ``` -------------------------------- ### Delete a Block Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Use this to delete a specific block from Notion. Ensure you have the correct Block Identifier. ```swift let blockId = Block.Identifier("{BLOCK UUIDv4}") do { let deletedBlock = try await notion.blockDelete(blockId: blockId) print("Deleted: \(deletedBlock)") } catch { print("Error deleting block: \(error)") } ``` -------------------------------- ### Retrieve a User Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Fetches a specific user's information using their User Identifier. Requires the User Identifier to be a valid UUID. ```swift let id = User.Identifier("{USER UUIDv4}") do { let user = try await notion.user(userId: id) print(user) } catch { print("Error retrieving user: \(error)") } ``` -------------------------------- ### Search for Databases Only Source: https://github.com/taichone/swift-notion-api/blob/main/README.md Filters search results to include only databases, excluding pages. This is useful when you specifically need to find database entries. ```swift do { let searchResult = try await notion.search( request: .init( filter: .database ) ) print(searchResult) } catch { print("Error searching databases: \(error)") } ``` -------------------------------- ### Search API Source: https://context7.com/taichone/swift-notion-api/llms.txt Search across all pages and databases accessible to the integration. Filter by object type and sort results. ```APIDOC ## Search Search across all pages and databases accessible to the integration. Filter by object type and sort results. ### Method POST ### Endpoint /search ### Parameters #### Request Body - **query** (string) - Optional - The search query string. - **filter** (object) - Optional - Filters for the search results. Can be `.page` or `.database`. - **sort** (object) - Optional - Sorting parameters for the search results. Requires `timestamp` and `direction`. - **pageSize** (integer) - Optional - The number of results to return per page. ### Request Example ```json { "query": "Project", "filter": null, "sort": null, "pageSize": null } ``` ### Response #### Success Response (200) - **results** (array) - An array of search results, which can be pages, databases, or unknown types. - **nextCursor** (string) - A cursor for fetching the next page of results, if `hasMore` is true. - **hasMore** (boolean) - Indicates if there are more results available. #### Response Example ```json { "results": [ { "object": "page", "id": "...", "properties": { ... } }, { "object": "database", "id": "...", "title": [ ... ] } ], "nextCursor": null, "hasMore": false } ``` ```