qbittorrent-api

repository·main·Indexed 19 days ago

https://github.com/rmartin16/qbittorrent-api

A Python client for the qBittorrent Web API (v4.1+), providing a high-level interface to manage torrents, application settings, RSS feeds, searches, and data transfers. It supports automatic authentication via credentials or API keys (v5.2.0+), session management through context managers, and provides a synchronous interface via the Sync class. While blocking, it can be integrated into asynchronous applications using asyncio.to_thread().

Tokens
21.7K
Snippets
67
Records
101
Agent score
65%

What's inside qbittorrent-api

  1. How authentication and session management work

    main

    The qbittorrentapi.Client handles authentication automatically. If an authentication cookie expires, the client requests a new one in line with the next API call.

    Users can manually call auth_log_in() to verify credentials or auth_log_out() to end a session. For best practices when creating many clients or short-lived instances, use the with qbittorrentapi.Client(...) as qbt_client: context manager pattern to ensure sessions are closed correctly.

  2. How qbittorrent-api namespaces and interaction modes work

    main

    The client provides three ways to interact with the qBittorrent Web API, ranging from direct mapping to high-level object manipulation:

    1. Direct Method Mapping: Every Web API endpoint is implemented as a one-to-one method on the client instance (e.g., qbt_client.torrents_info()).
    2. Namespace-based Interface: A more intuitive and robust interface organized into eight namespaces: auth, app, log, sync, transfer, torrents, rss, and search. This allows for structured access like qbt_client.app.preferences or qbt_client.log.main.warning().
    3. Object-oriented Methods: Certain returned objects (most notably torrent objects) have their own methods for direct manipulation, such as torrent.reannounce() or torrent.set_location().
    import qbittorrentapi
    
    qbt_client = qbittorrentapi.Client(host='localhost:8080', username='admin', password='adminadmin')
    
    # 1. Direct mapping
    qbt_client.torrents_info()
    
    # 2. Namespace interface
    qbt_client.torrents.stop.all()
    
    # 3. Object-oriented methods
    for torrent in qbt_client.torrents.info.active():
        torrent.reannounce()
  3. How authentication and authorization work in qbittorrent-api

    main

    The qbittorrent-api library handles authentication through the AuthAPIMixIn class and manages permissions/access via the Authorization class.

    When using a Client instance, the library automatically manages the logged-in state for you. While you don't strictly need to manually call login methods for every request, the client maintains session state to ensure subsequent API calls are authorized. If you are creating many short-lived client instances, it is recommended to explicitly log out to avoid leaving orphaned sessions on the qBittorrent WebUI.

  4. Understand Search API data structures

    main

    When interacting with the Search API, the following data structures are used to represent responses and state:

    • SearchJobDictionary: Represents a dictionary of search jobs.
    • SearchResultsDictionary: Represents the collection of results returned from a search.
    • SearchStatusesList: A list of SearchStatus objects representing the current state of search jobs.
    • SearchCategoriesList: A list of SearchCategory objects defining available search categories.
    • SearchPluginsList: A list of SearchPlugin objects representing installed search plugins.
  5. Work with torrent data structures

    main

    When interacting with the torrent API, you will encounter several specialized dictionary and list objects that represent qBittorrent data:

    • TorrentDictionary: Represents the core data and properties of a torrent.
    • TorrentPropertiesDictionary: Contains specific metadata and properties of a torrent.
    • TorrentLimitsDictionary: Manages download and upload limits.
    • TorrentCategoriesDictionary: Manages category assignments.
    • TorrentFilesList / TorrentFile: Represents the list of files within a torrent and individual file metadata.
    • TrackersList / Tracker: Represents the list of trackers associated with a torrent.
    • WebSeedsList / WebSeed: Represents web seeds used for downloading.
    • TagList / Tag: Represents the tags assigned to a torrent.
  6. Understand Sync data structures: SyncMainDataDictionary and SyncTorrentPeersDictionary

    main

    The synchronous API uses specialized dictionary classes to return data from the qBittorrent server, ensuring consistent access to API responses:

    • SyncMainDataDictionary: Used for general API responses containing main data objects.
    • SyncTorrentPeersDictionary: Specifically used for responses related to torrent peer information.

    These classes allow you to interact with the returned data using standard dictionary patterns while maintaining the structure expected from the qBittorrent Web API.

  7. Manage qBittorrent sessions and prevent high memory usage

    main

    The client transparently manages sessions, automatically logging in and requesting new sessions upon expiration. However, every new Client instance creates a new session in qBittorrent.

    Important: If you are creating many Client instances in a short period, you must call auth_log_out() for each instance or use a context manager to prevent abnormally high memory usage on the qBittorrent host.

    import qbittorrentapi
    
    with qbittorrentapi.Client(**conn_info) as qbt_client:
        if qbt_client.torrents_add(urls="...") != "Ok.":
            raise Exception("Failed to add torrent.")
  8. Handle untrusted or self-signed WebUI certificates

    main

    If your qBittorrent WebUI uses an untrusted or self-signed HTTPS certificate, connections will fail unless verification is disabled.

    To disable verification:

    • Pass VERIFY_WEBUI_CERTIFICATE=False to the Client constructor.
    • Set the environment variable QBITTORRENTAPI_DO_NOT_VERIFY_WEBUI_CERTIFICATE to a non-null value.

    Warning: This disables certificate verification, making the connection susceptible to man-in-the-middle attacks, though the connection remains encrypted.

    qbt_client = Client(..., VERIFY_WEBUI_CERTIFICATE=False)
  9. Use qbittorrent-api in asynchronous applications

    main

    The qbittorrent-api library does not natively support Python's async/await syntax and all API calls are blocking. To prevent these blocking calls from stalling an asyncio event loop in an asynchronous application, you should run the client methods within a thread pool using asyncio.to_thread() (available in Python 3.9+).

    When using asyncio.to_thread(), pass the client method as the first argument, followed by any arguments required by that specific method.

    import asyncio
    import qbittorrentapi
    
    qbt_client = qbittorrentapi.Client()
    
    async def fetch_torrents():
        # Use asyncio.to_thread to run the blocking torrents_info call without blocking the event loop
        return await asyncio.to_thread(qbt_client.torrents_info, category="uploaded")
    
    async def fetch_qbt_info():
        # Example of calling app_build_info
        return await asyncio.to_thread(qbt_client.app_build_info)
    
    # Running the async function
    if __name__ == "__main__":
        print(asyncio.run(fetch_qbt_info()))
  10. Authenticate with Host, Username, and Password

    main

    You can authenticate with your qBittorrent WebUI using credentials in three ways:

    1. During instantiation: Pass host, username, and password to the Client constructor.
    2. After instantiation: Call auth_log_in(username='...', password='...'). Note that the client will automatically attempt to authenticate for any API request even if you don't call this explicitly.
    3. Environment variables: Set the following variables in your environment:
      • QBITTORRENTAPI_HOST
      • QBITTORRENTAPI_USERNAME
      • QBITTORRENTAPI_PASSWORD
    qbt_client = Client(host="localhost:8080", username='...', password='...')
    
    # Or after creation:
    qbt_client.auth_log_in(username='...', password='...')
  11. Authenticate using an API Key (qBittorrent v5.2.0+)

    main

    For qBittorrent versions 5.2.0 and newer, you can use an API key instead of a username and password. When an API key is provided, it takes precedence over credentials. Authentication is handled via an Authorization: Bearer header, skipping the standard cookie-based login/logout round-trips.

    Options:

    • Pass api_key to the Client constructor.
    • Set the QBITTORRENTAPI_API_KEY environment variable.
    qbt_client = Client(host="localhost:8080", api_key="qbt_...")