pyzotero Documentation

repository·main·Indexed 23 days ago

https://github.com/urschrei/pyzotero

A Python wrapper for the Zotero API (v3) used to manage personal and group Zotero libraries. It supports remote API access, local Zotero server interaction, and includes a Command-Line Interface (CLI) for searching and querying local libraries. Additionally, it provides a Model Context Protocol (MCP) server that exposes Zotero library tools and Semantic Scholar integration for LLMs.

Tokens
13.4K
Snippets
27
Records
73
Agent score
77%

What's inside pyzotero

  1. Retrieve all items using everything()

    main

    By default, Pyzotero's Read API methods (like top() or items()) return 100 items to ensure usability. If you need to retrieve every item in a library without manually managing pagination, wrap your request in the everything() method.

    Example:

    # Retrieve all top-level items
    results = zot.everything(zot.top())
  2. Understand Zotero API return types and errors

    main

    When using Pyzotero, keep the following patterns in mind regarding data and errors:

    • Read API methods: Most methods that retrieve data return lists of dicts or lists of strings (specifically for tag methods).
    • Write API methods: Most methods that modify data return True if the operation was successful. If the operation fails, they will raise an error. For a full list of possible errors, refer to zotero_errors.py.
    • URL Parameter Warning: Be cautious when passing URL parameters. Certain parameters can supersede the intended API call. For example, adding ?start=50&limit=10 to an item-specific URL might cause the API to return a list of items instead of the single requested item. Avoid passing URL parameters that do not apply to the specific API method being used.
  3. Configure search and request parameters

    main

    You can pass search and request parameters directly to Read API methods or use the add_parameters() method to set them for the subsequent call. Parameters set via add_parameters() are valid for the next call only and will be overridden if parameters are passed directly to the method call.

    Directly on call:

    z = zot.top(limit=7, start=3)

    Using add_parameters():

    zot.add_parameters(limit=7, start=3)
    z = zot.top()
    # set parameters on the call itself
    z = zot.top(limit=7, start=3)
    
    # set parameters using explicit method
    zot.add_parameters(limit=7, start=3)
    z = zot.top()
  4. How follow(), everything(), and generators work for pagination

    main

    For Read API calls that return multiple items, Pyzotero provides experimental methods to handle pagination and large datasets more easily.

    Pagination Methods

    • Zotero.follow(): Repeats the previous Read API call for the next x items (default 50). Each subsequent call extends the offset.
    • Zotero.everything(API_call): Attempts to retrieve all items returned by the provided API call in one go.

    Generator Methods

    If you prefer working with Python generators:

    • Zotero.iterfollow(): A generator that wraps the follow() method.
    • Zotero.makeiter(API_call): Returns a generator over a specific Read API method.

    Warning: These methods are only valid for methods that return multiple items (e.g., you cannot use follow() after a single item() call). Generators will raise StopIteration when all items are exhausted.

  5. Understand the structure of returned item data

    main

    When retrieving items, most metadata is contained within the item['data'] key. A typical item dictionary includes:

    • data: A dictionary containing core fields like title, creators, itemType, date, tags, abstractNote, etc.
    • key: The unique Zotero item key.
    • library: Information about the library (id, name, type).
    • links: API links for the item.
    • meta: Metadata such as creatorSummary and numChildren.
    • version: The item version number.
  6. Quickstart: Initialize Zotero client and retrieve items

    main

    To use Pyzotero, you need your library_id and an api_key.

    • Personal Library: Set library_type to 'user'. Your ID is found in Zotero settings under Your userID for use in API calls.
    • Group Library: Set library_type to 'group'. The ID is the integer found in the group URL after /groups/.

    Note: For read access to a local Zotero instance, you can use local=True in the constructor (requires Zotero 7 with local API access enabled).

    from pyzotero import Zotero
    
    zot = Zotero(
        library_id, library_type, api_key
    )  # local=True for read access to local Zotero
    items = zot.top(limit=5)
    # we've retrieved the latest five top-level items in our library
    # we can print each item's item type and ID
    for item in items:
        print(f"Item: {item['data']['itemType']} | Key: {item['data']['key']}")
  7. Install the Pyzotero CLI

    main

    The Command-Line Interface (CLI) allows you to search and query your local Zotero library. To use the CLI, install the [cli] extra.

    uv add "pyzotero[cli]"
    # or
    pip install "pyzotero[cli]"

    You can also run it without installing using uvx or pipx:

    uvx --from "pyzotero[cli]" pyzotero search -q "your query"
    # or
    pipx run --spec "pyzotero[cli]" pyzotero search -q "your query"
    uv add "pyzotero[cli]"
  8. Use the Pyzotero CLI for searching and querying

    main

    The Pyzotero CLI connects to your local Zotero installation to search, list, and view items.

    Search Commands

    • Basic search: pyzotero search -q "query"
    • Full-text search: pyzotero search -q "query" --fulltext (searches PDFs and attachments, returning parent bibliographic records).
    • Filter by item type: pyzotero search -q "query" --itemtype book --itemtype journalArticle
    • Search within a collection: pyzotero search --collection ABC123 -q "test"
    • Filter by tags (AND logic): pyzotero search -q "topic" --tag "tag1" --tag "tag2"
    • Pagination: pyzotero search -q "topic" --limit 20 --offset 20

    Item and Attachment Commands

    • Get item by key: pyzotero item ABC123 --json
    • Get children (notes/attachments): pyzotero children ABC123 --json
    • Get subset of items: pyzotero subset ABC123 DEF456 --json (up to 50 keys).
    • Get attachment full-text: pyzotero fulltext ABC123

    Metadata and Tags

    • List collections: pyzotero listcollections
    • List item types: pyzotero itemtypes
    • List all tags: pyzotero tags
    • List tags in a collection: pyzotero tags --collection ABC123

    Output Formats

    • Human-readable (Default): Includes title, authors, date, DOI, URL, and local PDF paths.
    • JSON: Use the --json flag for machine-readable output (e.g., pyzotero search -q "climate" --json).

    DOI Indexing

    To generate a complete DOI-to-key mapping for caching:

    pyzotero doiindex > doi_cache.json
    pyzotero search -q "machine learning"
  9. Install and configure the Pyzotero MCP server

    main

    The Model Context Protocol (MCP) server exposes your local Zotero library and Semantic Scholar integration as tools for LLMs (like Claude Desktop).

    Installation:

    uv add "pyzotero[mcp]"
    # or
    pip install "pyzotero[mcp]"
    # or as a standalone tool
    uv tool install "pyzotero[mcp]"

    Claude Desktop Configuration: Add the server to your Claude Desktop configuration file.

    If installed via uv:

    {
      "mcpServers": {
        "zotero": {
          "command": "pyzotero-mcp"
        }
      }
    }

    If running via uvx without installation:

    {
      "mcpServers": {
        "zotero": {
          "command": "uvx",
          "args": ["--from", "pyzotero[mcp]", "pyzotero-mcp"]
        }
      }
    }
  10. Retrieve citation and bibliography entries

    main

    To retrieve citations or bibliographies, use the content parameter with add_parameters() or a method call.

    • If content='bib' or content='citation' is used with a style, the return value is a list of UTF-8 formatted HTML <div> or <span> elements.
    • If an export format is used as the content parameter, Pyzotero returns a list of unicode strings in that format (except csljson, which returns a list of dicts). You must provide a limit parameter when using these export formats.
    • If format='bibtex' is used, a bibtexparser object is returned. You can access citations via the .entries property or use the .dump() method to write to a .bib file.
    • If format='keys' is used, a newline-delimited string of item keys is returned.
  11. Install Pyzotero

    main

    You can install Pyzotero using uv, pip, or conda.

    Standard Installation

    uv add pyzotero
    # or
    pip install pyzotero
    # or
    conda install conda-forge::pyzotero

    Install with Command-Line Interface (CLI)

    To include the optional CLI for searching and querying your local Zotero library, install the [cli] extra:

    uv add "pyzotero[cli]"
    # or
    pip install "pyzotero[cli]"

    Run CLI without permanent installation

    If you want to use the CLI tools without installing the package to your environment, use uvx or pipx:

    uvx --from "pyzotero[cli]" pyzotero search -q "your query"
    # or
    pipx run --spec "pyzotero[cli]" pyzotero search -q "your query"
    uv add pyzotero
  12. Understand rate limiting and backoff behavior

    main

    Pyzotero handles HTTP 429 (TooManyRequestsError) specially to facilitate automatic retries.

    When a 429 response is received, the library attempts to extract a backoff duration from the server's Retry-After header. If a duration is found, it is recorded on the Zotero instance via an internal _set_backoff method, allowing the client to wait before retrying.

    If the server does not provide a backoff duration in the header, the library will raise a TooManyRetriesError instead of attempting to wait.