### Get All Notes Source: https://gkeepapi.readthedocs.io/en/latest/index.html Retrieves all notes associated with the authenticated account. This fetches all notes available to the user. ```python gnotes = keep.all() ``` -------------------------------- ### Get All Labels Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Returns a list of all available labels managed by the API. ```python def labels(self) -> list[_node.Label]: """Get all labels. Returns: Labels """ return list(self._labels.values()) ``` -------------------------------- ### GET /reminders/list Source: https://gkeepapi.readthedocs.io/en/latest/gkeepapi.html Lists current reminders. ```APIDOC ## GET /reminders/list ### Description List current reminders. ### Parameters #### Query Parameters - **master** (bool) - Optional - Default: True. ``` -------------------------------- ### Get Labels Source: https://gkeepapi.readthedocs.io/en/latest/index.html Retrieve specific labels by ID or fetch all available labels. ```python label = keep.getLabel('...') ``` ```python labels = keep.labels() ``` -------------------------------- ### Get All Notes Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves a list of all top-level notes. This includes notes directly under the root. ```python def all(self) -> list[_node.TopLevelNode]: """Get all Notes. Returns: All notes. """ return self._nodes[_node.Root.ID].children ``` -------------------------------- ### Get Auth Token Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves the current authentication token. ```python def getAuthToken(self) -> str | None: """Gets the auth token. Returns: The auth token. """ return self._auth_token ``` -------------------------------- ### Get All Context Sub-Annotations Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Retrieves all sub-annotations contained within the context annotation. ```python def all(self) -> list[Annotation]: """Get all sub annotations. Returns: Sub Annotations. """ return list(self._entries.values()) ``` -------------------------------- ### Get Media Link Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves the canonical URL for a given media resource (blob). ```python def getMediaLink(self, blob: _node.Blob) -> str: """Get the canonical link to media. Args: blob: The media resource. Returns: A link to the media. """ return self._media_api.get(blob) ``` -------------------------------- ### Manipulating Notes and Lists Source: https://gkeepapi.readthedocs.io/en/latest/index.html This section details the attributes and methods for interacting with notes and list items, including getting and setting content, managing list items, and sorting. ```APIDOC ## Note and List Attributes ### Notes - `node.TopLevelNode.id` (Read only) - `node.TopLevelNode.parent` (Read only) - `node.TopLevelNode.title` - `node.TopLevelNode.text` - `node.TopLevelNode.color` - `node.TopLevelNode.archived` - `node.TopLevelNode.pinned` - `node.TopLevelNode.labels` - `node.TopLevelNode.annotations` - `node.TopLevelNode.timestamps` (Read only) - `node.TopLevelNode.collaborators` - `node.TopLevelNode.blobs` (Read only) - `node.TopLevelNode.drawings` (Read only) - `node.TopLevelNode.images` (Read only) - `node.TopLevelNode.audio` (Read only) ### List Items - `node.TopLevelNode.id` (Read only) - `node.TopLevelNode.parent` (Read only) - `node.TopLevelNode.parent_item` (Read only) - `node.TopLevelNode.indented` (Read only) - `node.TopLevelNode.text` - `node.TopLevelNode.checked ## Getting Note Content ### Description Retrieves the title and text content of a note. ### Request Example ```python print gnote.title print gnote.text ``` ## Getting List Content ### Description Retrieves the serialized content of a list or individual list items. ### Request Example ```python # Serialized content print glist.text # ListItem objects glistitems = glist.items # Checked ListItems cglistitems = glist.checked # Unchecked ListItems uglistitems = glist.unchecked ``` ## Setting Note Content ### Description Updates the title, text, color, archived status, and pinned status of a note. ### Request Example ```python gnote.title = 'Title 2' gnote.text = 'Text 2' gnote.color = gkeepapi.node.ColorValue.White gnote.archived = True gnote.pinned = False ``` ## Setting List Content ### Description Adds new items to a list or modifies existing items. ### Request Example - Adding Items ```python # Create a checked item glist.add('Item 2', True) # Create an item at the top of the list glist.add('Item 1', True, gkeepapi.node.NewListItemPlacementValue.Top) # Create an item at the bottom of the list glist.add('Item 3', True, gkeepapi.node.NewListItemPlacementValue.Bottom) ``` ### Request Example - Modifying Items ```python glistitem = glist.items[0] glistitem.text = 'Item 4' glistitem.checked = True ``` ### Request Example - Deleting Items ```python glistitem.delete() ``` ## Setting List Item Position ### Description Adjusts the position of a list item within the list. ### Request Example ```python # Set a specific sort id glistitem1.sort = 42 # Swap the position of two items val = glistitem2.sort glistitem2.sort = glistitem3.sort glistitem3.sort = val ``` ## Sorting a List ### Description Sorts the items within a list. ### Request Example ```python # Sorts items alphabetically by default glist.sort_items() ``` ## Indent/Dedent List Items ### Description Modifies the indentation level of list items. ### Request Example - Indent ```python gparentlistitem.indent(gchildlistitem) ``` ### Request Example - Dedent ```python gparentlistitem.dedent(gchildlistitem) ``` ``` -------------------------------- ### Create and Sync a Note Source: https://gkeepapi.readthedocs.io/en/latest/index.html Demonstrates creating a new note, setting its properties, and syncing changes to the server. Requires authentication with a master token. ```python import gkeepapi # Obtain a master token for your account master_token = '...' keep = gkeepapi.Keep() keep.authenticate('user@gmail.com', master_token) note = keep.createNote('Todo', 'Eat breakfast') note.pinned = True note.color = gkeepapi.node.ColorValue.Red keep.sync() print(note.title) print(note.text) ``` -------------------------------- ### Create and Modify Notes Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Demonstrates the basic workflow for creating a new note, modifying its text, and synchronizing changes with the server. ```python new_note = keep.createNote() These Notes can then be modified:: some_note.text = 'Test' new_note.text = 'Text' These changes are automatically detected and synced up with:: keep.sync() ``` -------------------------------- ### Cache Notes with Dump and Restore Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Demonstrates how to serialize note data to a file using `dump` and load it back using `restore` to speed up subsequent program runs by resuming from a cached state. ```python # Store cache state = keep.dump() fh = open('state', 'w') json.dump(state, fh) # Load cache fh = open('state', 'r') state = json.load(fh) keep.restore(state) ``` -------------------------------- ### Get Device ID Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves the device identifier used for authentication. ```python def getDeviceId(self) -> str: """Gets the device id. Returns: The device id. """ return self._device_id ``` -------------------------------- ### Store and Retrieve Master Token with Keyring Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Shows how to use the keyring library to securely store and retrieve the master token for authentication, avoiding hardcoding it in scripts. ```python import keyring # To save the token # ... # keyring.set_password('google-keep-token', 'user@gmail.com', master_token) master_token = keyring.get_password("google-keep-token", "user@gmail.com") ``` -------------------------------- ### Get Account Email Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves the email address associated with the account. ```python def getEmail(self) -> str: """Gets the account email. Returns: The account email. """ return self._email ``` -------------------------------- ### Basic gkeepapi Usage Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Demonstrates the basic workflow of authenticating with gkeepapi, creating a note, modifying it, and syncing changes. ```python import gkeepapi # Obtain a master token for your account master_token = '...' keep = gkeepapi.Keep() keep.authenticate('user@gmail.com', master_token) note = keep.createNote('Todo', 'Eat breakfast') note.pinned = True note.color = gkeepapi.node.ColorValue.Red keep.sync() print(note.title) print(note.text) ``` -------------------------------- ### Get Master Token Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves the stored master token for the account. ```python def getMasterToken(self) -> str: """Gets the master token. Returns: The account master token. """ return self._master_token ``` -------------------------------- ### Initialize API Wrapper Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Initializes the base API wrapper with a base URL and optional authentication object. ```python class API: """Base API wrapper""" RETRY_CNT = 2 def __init__(self, base_url: str, auth: APIAuth | None = None) -> None: ``` -------------------------------- ### MediaAPI Client Implementation Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Provides low-level access to media blobs. Use the Keep class for higher-level operations. ```python class MediaAPI(API): """Low level Google Media API client. Mimics the Android Google Keep app. You probably want to use :py:class:`Keep` instead. """ API_URL = "https://keep.google.com/media/v2/" def __init__(self, auth: APIAuth | None = None) -> None: """Construct a low-level Google Media API client""" super().__init__(self.API_URL, auth) def get(self, blob: _node.Blob) -> str: """Get the canonical link to a media blob. Args: blob: The blob. Returns: A link to the media. """ url = self._base_url + blob.parent.server_id + "/" + blob.server_id if blob.blob.type == _node.BlobType.Drawing: url += "/" + blob.blob._drawing_info.drawing_id # noqa: SLF001 return self._send(url=url, method="GET", allow_redirects=False).headers[ "location" ] ``` -------------------------------- ### Get All NodeAnnotations Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Retrieves all annotation objects stored within the NodeAnnotations container. ```python def all(self) -> list[Annotation]: """Get all annotations. Returns: Annotations. """ return list(self._annotations.values()) ``` -------------------------------- ### Initialize APIAuth Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Constructs an API authentication manager. Requires scopes for authentication. ```python class APIAuth: """Authentication token manager""" def __init__(self, scopes: str) -> None: """Construct API authentication manager""" self._master_token = None self._auth_token = None self._email = None self._device_id = None self._scopes = scopes ``` -------------------------------- ### Initialize API Client Session Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Constructs the base session with user-agent headers for the Google Keep API. ```python """Construct a low-level API client""" self._session = requests.Session() self._auth = auth self._base_url = base_url self._session.headers.update( { "User-Agent": "x-gkeepapi/%s (https://github.com/kiwiz/gkeepapi)" % __version__ } ) ``` -------------------------------- ### Google Keep Client Initialization Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Initializes the high-level Google Keep client. Requires authentication with a master token. Provides methods for retrieving and creating notes. ```python class Keep: """High level Google Keep client. Manipulates a local copy of the Keep node tree. First, obtain a master token for your account. To start, first authenticate:: keep.authenticate('...', '...') Individual Notes can be retrieved by id:: some_note = keep.get('some_id') New Notes can be created:: ``` -------------------------------- ### Create a New Note Source: https://gkeepapi.readthedocs.io/en/latest/gkeepapi.html Initializes a new note object within the Keep client. ```python new_note = keep.createNote() ``` -------------------------------- ### Get Authentication Details Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves the current authentication object associated with the API client. ```APIDOC ## GET /auth ### Description Retrieves the current authentication object associated with the API client. ### Method GET ### Endpoint /auth ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python auth_details = keep_api.getAuth() ``` ### Response #### Success Response (200) - **auth** (APIAuth) - The authentication object. #### Response Example ```json { "auth": "" } ``` ``` -------------------------------- ### Create a New Note Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Creates a new note with a specified title and text content. The `Keep` object tracks this new note for syncing. ```python gnote = keep.createNote('Title', 'Text') ``` -------------------------------- ### gkeepapi Package Contents Source: https://gkeepapi.readthedocs.io/en/latest/_sources/gkeepapi.rst.txt General documentation for the root gkeepapi package. ```APIDOC ## gkeepapi ### Description Core module contents for the gkeepapi package, providing the primary interface for interacting with Google Keep services. ``` -------------------------------- ### Get Label by ID Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves an existing label using its unique identifier. Returns None if the label is not found. ```python def getLabel(self, label_id: str) -> _node.Label | None: """Get an existing label. Args: label_id: Label id. Returns: The label. """ return self._labels.get(label_id) ``` -------------------------------- ### RemindersAPI Client Implementation Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Provides low-level access to Google Keep reminders. Includes methods for creating and updating reminders. ```python class RemindersAPI(API): """Low level Google Reminders API client. Mimics the Android Google Keep app. You probably want to use :py:class:`Keep` instead. """ API_URL = "https://www.googleapis.com/reminders/v1internal/reminders/" def __init__(self, auth: APIAuth | None = None) -> None: """Construct a low-level Google Reminders API client""" super().__init__(self.API_URL, auth) self.static_params = { "taskList": [ {"systemListId": "MEMENTO"}, ], "requestParameters": { "userAgentStructured": { "clientApplication": "KEEP", "clientApplicationVersion": { "major": "9", "minor": "9.9.9.9", }, "clientPlatform": "ANDROID", }, }, } def create( self, node_id: str, node_server_id: str, dtime: datetime.datetime ) -> Any: # noqa: ANN401 """Create a new reminder. Args: node_id: The note ID. node_server_id: The note server ID. dtime: The due date of this reminder. Return: ??? Raises: APIException: If the server returns an error. """ params = {} params.update(self.static_params) params.update( { "task": { "dueDate": { "year": dtime.year, "month": dtime.month, "day": dtime.day, "time": { "hour": dtime.hour, "minute": dtime.minute, "second": dtime.second, }, }, "snoozed": True, "extensions": { "keepExtension": { "reminderVersion": "V2", "clientNoteId": node_id, "serverNoteId": node_server_id, }, }, }, "taskId": { "clientAssignedId": "KEEP/v2/" + node_server_id, }, } ) return self.send(url=self._base_url + "create", method="POST", json=params) def update_internal( self, node_id: str, node_server_id: str, dtime: datetime.datetime ) -> Any: # noqa: ANN401 """Update an existing reminder. Args: node_id: The note ID. ``` -------------------------------- ### Initialize a Note Node Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Constructs a Note object, which represents a Google Keep note. It initializes the node with the specified type. ```python super().__init__(type_=self._TYPE, **kwargs) ``` -------------------------------- ### Get Text Node from Note Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Retrieves the primary text content node (ListItem) from a Note. Returns None if no such node exists. ```python node = None for child_node in self.children: if isinstance(child_node, ListItem): node = child_node break return node ``` -------------------------------- ### MediaAPI - Get Media Blob Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves the canonical link to a media blob. This is a low-level client mimicking the Android Google Keep app. ```APIDOC ## GET /media/v2/{serverId}/{blobServerId}/{drawingId} ### Description Gets the canonical link to a media blob. This method is part of the low-level Google Media API client. ### Method GET ### Endpoint https://keep.google.com/media/v2/ ### Parameters #### Path Parameters - **serverId** (string) - Required - The server ID of the blob's parent. - **blobServerId** (string) - Required - The server ID of the blob. - **drawingId** (string) - Optional - The drawing ID, required if the blob type is Drawing. ### Request Example ```json { "blob": { "type": "Drawing", "_drawing_info": { "drawing_id": "example_drawing_id" } }, "parent": { "server_id": "example_server_id" }, "server_id": "example_blob_server_id" } ``` ### Response #### Success Response (200) - **location** (string) - The canonical URL to the media blob. #### Response Example ```json { "location": "https://example.com/media/blob/url" } ``` ``` -------------------------------- ### Define List and Graveyard Settings Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Enumerations for list item placement, graveyard visibility, and checked item policies. ```python class NewListItemPlacementValue(enum.Enum): """Target location to put new list items.""" Top = "TOP" """Top""" Bottom = "BOTTOM" """Bottom""" ``` ```python class GraveyardStateValue(enum.Enum): """Visibility setting for the graveyard.""" Expanded = "EXPANDED" """Expanded""" Collapsed = "COLLAPSED" """Collapsed""" ``` ```python class CheckedListItemsPolicyValue(enum.Enum): """Movement setting for checked list items.""" Default = "DEFAULT" """Default""" Graveyard = "GRAVEYARD" """Graveyard""" ``` -------------------------------- ### Node Class Methods Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Provides details on methods for managing child nodes within a Node object, including getting, appending, and removing children. ```APIDOC ## Node Class Methods ### Description Methods for interacting with child nodes of a given Node. ### Methods #### `get(node_id: str)` Get child node with the given ID. - **Parameters** - `node_id` (str) - Required - The node ID. - **Returns** - `Node | None` - Child node or None if not found. #### `append(node: Node, dirty: bool = True)` Add a new child node. - **Parameters** - `node` (Node) - Required - Node to add. - `dirty` (bool) - Optional - Whether this node should be marked dirty. Defaults to True. - **Returns** - `Node` - The added node. #### `remove(node: Node, dirty: bool = True)` Remove the given child node. - **Parameters** - `node` (Node) - Required - Node to remove. - `dirty` (bool) - Optional - Whether this node should be marked dirty. Defaults to True. - **Returns** - `None` ``` -------------------------------- ### TopLevelNode Initialization and Loading Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Initializes a TopLevelNode with default values for color, archived status, pinned status, and title. It also loads these properties, along with labels and collaborators, from raw data. ```python class TopLevelNode(Node): """Top level node base class.""" __slots__ = ("_color", "_archived", "_pinned", "_title", "labels", "collaborators") _TYPE = None def __init__(self, **kwargs: dict) -> None: """Construct a top level node""" super().__init__(parent_id=Root.ID, **kwargs) self._color = ColorValue.White self._archived = False self._pinned = False self._title = "" self.labels = NodeLabels() self.collaborators = NodeCollaborators() def _load(self, raw: dict) -> None: super()._load(raw) self._color = ColorValue(raw["color"]) if "color" in raw else ColorValue.White self._archived = raw.get("isArchived", False) self._pinned = raw.get("isPinned", False) self._title = raw.get("title", "") self.labels.load(raw.get("labelIds", [])) self.collaborators.load( raw.get("roleInfo", []), raw.get("shareRequests", []), ) self._moved = "moved" in raw ``` -------------------------------- ### Get Category Annotation from NodeAnnotations Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Finds and returns the Category annotation from the collection of annotations within NodeAnnotations. Returns None if no Category annotation is found. ```python def _get_category_node(self) -> Category | None: for annotation in self._annotations.values(): if isinstance(annotation, Category): return annotation return None ``` -------------------------------- ### Load Authentication from Master Token Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Authenticates to Google using a master token. Raises LoginException if there's an issue during authentication. ```python def load(self, email: str, master_token: str, device_id: str) -> bool: """Authenticate to Google with the provided master token. Args: email: The account to use. master_token: The master token. device_id: An identifier for this client. Raises: LoginException: If there was a problem logging in. """ self._email = email self._device_id = device_id self._master_token = master_token # Obtain an OAuth token. self.refresh() return True ``` -------------------------------- ### Get a Note by ID Source: https://gkeepapi.readthedocs.io/en/latest/index.html Retrieves a specific note using its unique ID. The ID can typically be found in the URL when viewing the note in the web application. ```python gnote = keep.get('...') ``` -------------------------------- ### Sync and Media API Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Endpoints for synchronizing local state with the server and retrieving media links. ```APIDOC ## POST /sync ### Description Synchronize the local Keep tree with the server. Local changes are detected and pushed, or optionally destroyed if a full resync is requested. ### Method POST ### Endpoint /sync ### Parameters #### Request Body - **resync** (bool) - Optional - If true, clears local state and performs a full resync. --- ## GET /media/link ### Description Get the canonical link to a media resource. ### Method GET ### Endpoint /media/link ### Parameters #### Request Body - **blob** (object) - Required - The media resource object. ``` -------------------------------- ### Get a Specific Note by ID Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Retrieves a single note using its unique ID. The ID can typically be found in the URL when viewing the note in the web application. ```python gnote = keep.get('...') ``` -------------------------------- ### KeepAPI Initialization Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Initializes the low-level Google Keep API client. It requires authentication details and sets up the base URL and session headers. ```APIDOC ## KeepAPI Initialization ### Description Initializes the low-level Google Keep API client. It requires authentication details and sets up the base URL and session headers. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from gkeepapi import Keep, APIAuth # Assuming you have your auth details auth: APIAuth = ... keep_api = Keep(auth) ``` ### Response None ``` -------------------------------- ### Create a new managed note Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Creates a new note with optional title and text. Changes are uploaded on sync. The note is automatically added to the system. ```python def createNote( self, title: str | None = None, text: str | None = None, ) -> _node.Node: """Create a new managed note. Any changes to the note will be uploaded when :py:meth:`sync` is called. Args: title: The title of the note. text: The text of the note. Returns: The new note. """ node = _node.Note() if title is not None: node.title = title if text is not None: node.text = text self.add(node) return node ``` -------------------------------- ### Get Text Content of a List Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Retrieves the combined text content of all items in a list, with each item on a new line. This provides a consolidated view of the list's text. ```python return "\n".join(str(node) for node in self.items) ``` -------------------------------- ### Get Reminder Changes Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Retrieves historical changes for reminders based on the local storage version. Includes snooze preset updates. Requires `storage_version` and handles `APIException`. ```python params = { "storageVersion": storage_version, "includeSnoozePresetUpdates": True, } params.update(self.static_params) return self.send(url=self._base_url + "history", method="POST", json=params) ``` -------------------------------- ### Fetch Media Links Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Retrieve a download link for a media blob attached to a note. ```python blob = gnote.images[0] keep.getMediaLink(blob) ``` -------------------------------- ### Root Node Initialization Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Initializes the internal root node. The root node has a fixed ID and its 'dirty' status is always false. ```python class Root(Node): """Internal root node.""" __slots__ = () ID = "root" def __init__(self) -> None: """Construct a root node""" super().__init__(id_=self.ID) @property def dirty(self) -> bool: # noqa: D102 return False ``` -------------------------------- ### Get Text Content of a Note Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Retrieves the text content of a Google Keep note. If a text node exists, its text is returned; otherwise, the note's internal text is used. ```python node = self._get_text_node() if node is None: return self._text return node.text ``` -------------------------------- ### NodeSettings Configuration Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Methods for saving and loading node settings including list item placement and graveyard visibility. ```APIDOC ## POST /NodeSettings/save ### Description Saves the current settings container to a dictionary format. ### Method POST ### Endpoint /NodeSettings/save ### Parameters #### Request Body - **clean** (bool) - Optional - Whether to return a clean state. ### Response #### Success Response (200) - **newListItemPlacement** (string) - The default location to insert new list items. - **graveyardState** (string) - The visibility state for the list graveyard. - **checkedListItemsPolicy** (string) - The policy for checked list items. ``` -------------------------------- ### Node Child Management Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Methods for managing child nodes within a parent node. Includes getting a child by ID, appending a new child, and removing an existing child. Appending and removing can optionally mark the parent node as dirty. ```python def get(self, node_id: str) -> "Node | None": """Get child node with the given ID. Args: node_id: The node ID. Returns: Child node. """ return self._children.get(node_id) ``` ```python def append(self, node: "Node", dirty: bool = True) -> "Node": """Add a new child node. Args: node: Node to add. dirty: Whether this node should be marked dirty. """ self._children[node.id] = node node.parent = self if dirty: self.touch() return node ``` ```python def remove(self, node: "Node", dirty: bool = True) -> None: """Remove the given child node. Args: node: Node to remove. dirty: Whether this node should be marked dirty. """ if node.id in self._children: self._children[node.id].parent = None del self._children[node.id] if dirty: self.touch() ``` -------------------------------- ### Create a New List Source: https://gkeepapi.readthedocs.io/en/latest/index.html Creates a new list note with a title and a list of items. Each item can be specified with its text and checked status (True for checked, False for not checked). ```python glist = keep.createList('Title', [ ('Item 1', False), # Not checked ('Item 2', True) # Checked ]) # Sync up changes keep.sync() ``` -------------------------------- ### Enable Debug Logs Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Activate development debug logs for the gkeepapi library by setting the `DEBUG` attribute to `True`. ```python gkeepapi.node.DEBUG = True ``` -------------------------------- ### Create a new list Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Creates a new list with an optional title and items. Each item is a tuple of text and checked status. Changes are uploaded on sync. The list is automatically added to the system. ```python def createList( self, title: str | None = None, items: list[tuple[str, bool]] | None = None, ) -> _node.List: """Create a new list and populate it. Any changes to the note will be uploaded when :py:meth:`sync` is called. Args: title: The title of the list. items: A list of tuples. Each tuple represents the text and checked status of the listitem. Returns: The new list. """ if items is None: items = [] node = _node.List() if title is not None: node.title = title sort = random.randint(1000000000, 9999999999) # noqa: S311 for text, checked in items: node.add(text, checked, sort) sort -= _node.List.SORT_DELTA self.add(node) return node ``` -------------------------------- ### Obtain Master Token using Docker Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt A command-line one-liner using Docker to obtain a master token for Google Keep authentication. It prompts for email, OAuth token, and Android ID. ```bash docker run --rm -it --entrypoint /bin/sh python:3 -c 'pip install gpsoauth; python3 -c -- "print(__import__("gpsoauth").exchange_token(input("Email: "), input("OAuth Token: "), input("Android ID: ")))"' ``` -------------------------------- ### Login to Google Account Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Authenticates to Google using provided credentials. Raises BrowserLoginRequiredException if browser login is needed or LoginException if there's another problem. ```python def login(self, email: str, password: str, device_id: str) -> None: """Authenticate to Google with the provided credentials. Args: email: The account to use. password: The account password. device_id: An identifier for this client. Raises: LoginException: If there was a problem logging in. """ self._email = email self._device_id = device_id # Obtain a master token. res = gpsoauth.perform_master_login(self._email, password, self._device_id) # Bail if browser login is required. if res.get("Error") == "NeedsBrowser": raise exception.BrowserLoginRequiredException(res.get("Url")) # Bail if no token was returned. if "Token" not in res: raise exception.LoginException(res.get("Error"), res.get("ErrorDetail")) self._master_token = res["Token"] # Obtain an OAuth token. self.refresh() ``` -------------------------------- ### Sync Notes with Server Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Internal method to synchronize note data. It fetches changes from the server, applies them locally, and handles potential resync or upgrade requirements. ```python def _sync_notes(self) -> None: # Fetch updates until we reach the newest version. while True: logger.debug("Starting keep sync: %s", self._keep_version) # Collect any changes and send them up to the server. labels_updated = any(i.dirty for i in self._labels.values()) changes = self._keep_api.changes( target_version=self._keep_version, nodes=[i.save() for i in self._findDirtyNodes()], labels=[i.save() for i in self._labels.values()] if labels_updated else None, ) if changes.get("forceFullResync"): raise exception.ResyncRequiredException("Full resync required") if changes.get("upgradeRecommended"): raise exception.UpgradeRecommendedException("Upgrade recommended") # Hydrate labels. if "userInfo" in changes: self._parseUserInfo(changes["userInfo"]) # Hydrate notes and any children. if "nodes" in changes: self._parseNodes(changes["nodes"]) self._keep_version = changes["toVersion"] logger.debug("Finishing sync: %s", self._keep_version) # Check if there are more changes to retrieve. if not changes["truncated"]: break ``` -------------------------------- ### Initialize KeepAPI Client Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Initializes the low-level Google Keep API client with a unique session ID. ```python class KeepAPI(API): """Low level Google Keep API client. Mimics the Android Google Keep app. You probably want to use :py:class:`Keep` instead. """ API_URL = "https://www.googleapis.com/notes/v1/" def __init__(self, auth: APIAuth | None = None) -> None: """Construct a low-level Google Keep API client""" super().__init__(self.API_URL, auth) create_time = time.time() self._session_id = self._generateId(create_time) @classmethod def _generateId(cls, tz: int) -> str: return "s--%d--%d" % ( int(tz * 1000), random.randint(1000000000, 9999999999), # noqa: S311 ) ``` -------------------------------- ### Create a new label Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Creates a new label with the given name. Raises a LabelException if a label with the same name already exists. ```python def createLabel(self, name: str) -> _node.Label: """Create a new label. Args: name: Label name. Returns: The new label. Raises: LabelException: If the label exists. """ if self.findLabel(name): raise exception.LabelException("Label exists") node = _node.Label() node.name = name self._labels[node.id] = node ``` -------------------------------- ### POST /list Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Lists current reminders based on recurrence options. ```APIDOC ## POST /list ### Description Retrieves a list of reminders. Supports filtering by master status. ### Method POST ### Endpoint /list ### Query Parameters - **master** (boolean) - Optional - If true, returns master reminders; otherwise, returns instances within a specific time range. ``` -------------------------------- ### POST /reminders/create Source: https://gkeepapi.readthedocs.io/en/latest/gkeepapi.html Creates a new reminder associated with a specific note. ```APIDOC ## POST /reminders/create ### Description Create a new reminder. ### Parameters #### Request Body - **node_id** (str) - Required - The note ID. - **node_server_id** (str) - Required - The note server ID. - **dtime** (datetime) - Required - The due date of this reminder. ### Response - **APIException** - Raised if the server returns an error. ``` -------------------------------- ### Create a New Label Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Create a new label with a specified name using the `createLabel` method. ```python label = keep.createLabel('todo') ``` -------------------------------- ### Sync Changes with Server Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Synchronizes nodes and labels between the local client and the Google Keep server. ```python def changes( self, target_version: str | None = None, nodes: list[dict] | None = None, labels: list[dict] | None = None, ) -> dict: """Sync up (and down) all changes. Args: target_version: The local change version. nodes: A list of nodes to sync up to the server. labels: A list of labels to sync up to the server. Return: Description of all changes. Raises: APIException: If the server returns an error. """ # Handle defaults. if nodes is None: nodes = [] if labels is None: labels = [] current_time = time.time() # Initialize request parameters. params = { "nodes": nodes, "clientTimestamp": _node.NodeTimestamps.int_to_str(current_time), "requestHeader": { "clientSessionId": self._session_id, "clientPlatform": "ANDROID", "clientVersion": { "major": "9", "minor": "9", "build": "9", "revision": "9", }, "capabilities": [ {"type": "NC"}, # Color support (Send note color) {"type": "PI"}, # Pinned support (Send note pinned) ``` -------------------------------- ### Load Context Annotation Entries Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Loads context entries from a raw dictionary. It initializes an empty dictionary for entries and populates it by parsing nested annotations. ```python def _load(self, raw: dict) -> None: super()._load(raw) self._entries = {} for key, entry in raw.get("context", {}).items(): self._entries[key] = NodeAnnotations.from_json({key: entry}) ``` -------------------------------- ### Authenticate with Google Keep Source: https://gkeepapi.readthedocs.io/en/latest/gkeepapi.html Initializes authentication for the Keep client using an email and master token. ```python keep.authenticate('...', '...') ``` -------------------------------- ### gkeepapi.node Module Source: https://gkeepapi.readthedocs.io/en/latest/_sources/gkeepapi.rst.txt Documentation for the node module within the gkeepapi package. ```APIDOC ## gkeepapi.node ### Description This module handles the node structures used within the gkeepapi package for Google Keep data representation. ``` -------------------------------- ### gkeepapi.Keep method createList() Source: https://gkeepapi.readthedocs.io/en/latest/genindex.html Creates a new list in Google Keep. ```APIDOC ## createList() (gkeepapi.Keep method) ### Description Creates a new list in Google Keep. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Set Account Email Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Sets the email address for the account. ```python def setEmail(self, email: str) -> None: """Sets the account email. Args: email: The account email. """ self._email = email ``` -------------------------------- ### Deprecated Login Method Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Illustrates the deprecated `login` method for authentication, which is discouraged and may not work due to security requirements. ```python keep.login('user@gmail.com', 'password') ``` -------------------------------- ### MediaAPI - Media Handling Source: https://gkeepapi.readthedocs.io/en/latest/gkeepapi.html Methods for handling media associated with Google Keep notes. ```APIDOC ## GET /api/media/link ### Description Gets the canonical link to a media resource. ### Method GET ### Endpoint /api/media/link ### Parameters #### Query Parameters - **blob** (Blob) - Required - The media resource. ### Response #### Success Response (200) - **str** - A link to the media. #### Response Example ```json "https://example.com/media/some_blob_id" ``` ``` -------------------------------- ### Node Properties and Methods Source: https://gkeepapi.readthedocs.io/en/latest/gkeepapi.html Common properties and methods available across different Node types. ```APIDOC ## Node Properties ### _category_ - **Description**: Get the category. - **Returns**: The category. ### _dirty_ - **Description**: Get dirty state. - **Returns**: Whether this element is dirty. ### _links_ - **Description**: Get all links. - **Returns**: A list of links. ## Node Methods ### _classmethod _from_json(_raw : dict_) - **Description**: Helper to construct an annotation from a dict. - **Parameters**: - **raw** (dict) - Raw annotation representation. - **Returns**: An Annotation object or None. ### remove(_annotation : Annotation_) - **Description**: Removes an annotation. - **Parameters**: - **annotation** (Annotation) - An Annotation object. ### save(_clean : bool = True_) - **Description**: Save the annotations container. - **Returns**: A dictionary representing the saved annotations. ``` -------------------------------- ### Obtain Master Token using Docker Source: https://gkeepapi.readthedocs.io/en/latest/index.html A Docker command to obtain a master token by running a Python script that prompts for necessary information. Requires Docker and Python 3. ```bash docker run --rm -it --entrypoint /bin/sh python:3 -c 'pip install gpsoauth; python3 -c @' print(__import__("gpsoauth").exchange_token(input("Email: "), input("OAuth Token: "), input("Android ID: "))))@' ``` -------------------------------- ### TimestampsMixin Lifecycle Methods Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi/node.html Methods to update timestamps and manage the trashed or deleted state of an item. ```python class TimestampsMixin: """A mixin to add methods for updating timestamps.""" __slots__ = () # empty to resolve multiple inheritance def __init__(self) -> None: """Instantiate mixin""" self.timestamps: NodeTimestamps def touch(self, edited: bool = False) -> None: """Mark the node as dirty. Args: edited: Whether to set the edited time. """ self._dirty = True dt = datetime.datetime.now(tz=datetime.timezone.utc) self.timestamps.updated = dt if edited: self.timestamps.edited = dt @property def trashed(self) -> bool: """Get the trashed state. Returns: Whether this item is trashed. """ return ( self.timestamps.trashed is not None and self.timestamps.trashed > NodeTimestamps.int_to_dt(0) ) def trash(self) -> None: """Mark the item as trashed.""" self.timestamps.trashed = datetime.datetime.now(tz=datetime.timezone.utc) def untrash(self) -> None: """Mark the item as untrashed.""" self.timestamps.trashed = self.timestamps.int_to_dt(0) @property def deleted(self) -> bool: """Get the deleted state. Returns: Whether this item is deleted. """ return ( self.timestamps.deleted is not None and self.timestamps.deleted > NodeTimestamps.int_to_dt(0) ) def delete(self) -> None: """Mark the item as deleted.""" self.timestamps.deleted = datetime.datetime.now(tz=datetime.timezone.utc) def undelete(self) -> None: """Mark the item as undeleted.""" self.timestamps.deleted = None ``` -------------------------------- ### Authenticate with Credentials Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Authenticates using email and password. Note that this method is deprecated in favor of authenticate(). ```python def login( self, email: str, password: str, state: dict | None = None, sync: bool = True, device_id: str | None = None, ) -> None: """Authenticate to Google with the provided credentials & sync. This flow is discouraged. Args: email: The account to use. password: The account password. state: Serialized state to load. sync: Whether to sync data. device_id: Device id. Raises: LoginException: If there was a problem logging in. """ logger.warning("'Keep.login' is deprecated. Please use 'Keep.authenticate' instead") auth = APIAuth(self.OAUTH_SCOPES) if device_id is None: device_id = f"{get_mac():x}" auth.login(email, password, device_id) self.load(auth, state, sync) ``` -------------------------------- ### Authenticate with gkeepapi Source: https://gkeepapi.readthedocs.io/en/latest/_sources/index.rst.txt Authenticates a Keep client instance using a username and master token. Ensure the master token is kept secure. ```python keep = gkeepapi.Keep() keep.authenticate('user@gmail.com', master_token) ``` -------------------------------- ### Parse User Info Internal Method Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html Updates the internal label registry based on raw user information data. ```python def _parseUserInfo(self, raw: dict) -> None: labels = {} if "labels" in raw: for label in raw["labels"]: # If the mainId field exists, this is an update. if label["mainId"] in self._labels: node = self._labels[label["mainId"]] # Remove this key from our list of labels. del self._labels[label["mainId"]] logger.debug("Updated label: %s", label["mainId"]) else: # Otherwise, this is a brand new label. node = _node.Label() logger.debug("Created label: %s", label["mainId"]) node.load(label) labels[label["mainId"]] = node # All remaining labels are deleted. for label_id in self._labels: logger.debug("Deleted label: %s", label_id) self._labels = labels ``` -------------------------------- ### List Management Source: https://gkeepapi.readthedocs.io/en/latest/_modules/gkeepapi.html APIs for creating and managing lists. ```APIDOC ## POST /api/lists ### Description Creates a new managed list and populates it. Changes will be uploaded when sync is called. ### Method POST ### Endpoint /api/lists ### Parameters #### Request Body - **title** (string) - Optional - The title of the list. - **items** (list[object]) - Optional - A list of objects, where each object represents a list item with 'text' (string) and 'checked' (boolean) properties. ### Request Example { "title": "My Shopping List", "items": [ {"text": "Apples", "checked": false}, {"text": "Milk", "checked": true} ] } ### Response #### Success Response (200) - **list_id** (string) - The ID of the newly created list. #### Response Example { "list_id": "list-67890" } ``` -------------------------------- ### gkeepapi.RemindersAPI method create() Source: https://gkeepapi.readthedocs.io/en/latest/genindex.html Creates a reminder in Google Keep. ```APIDOC ## create() (gkeepapi.RemindersAPI method) ### Description Creates a reminder in Google Keep. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ```