Box Python SDK

repository·main·Indexed 19 days ago

https://github.com/box/box-python-sdk

A programmatic interface to the Box Content Cloud. Version 10 is built on the auto-generated box_sdk_gen package for full feature coverage, while version 4 provides a migration path for legacy v3 users. The SDK supports multiple authentication methods (Developer Token, OAuth 2.0, Client Credentials Grant, and JWT) and provides comprehensive coverage for core content, collaboration, governance, and advanced features like Box AI, Box Sign, and Webhooks.

Tokens
90.3K
Snippets
384
Records
453
Agent score
65%

What's inside box-python-sdk

  1. Explore Box API functionality by topic

    main

    The SDK provides comprehensive coverage for nearly all Box API features. You can find specific implementation guides and examples for topics including:

    • Core Content: Files, Folders, File Versions, Trash, Downloads, and Uploads.
    • Collaboration: Collaborations, Users, Groups, Shared Links, and Invites.
    • Metadata & Governance: Metadata Templates, Metadata Taxonomies, Retention Policies, Legal Holds, and Classifications.
    • Advanced Features: AI, Search, Webhooks, Workflows, Box Sign, and Box AI Studio.
    • Enterprise & Security: Enterprise Configurations, Shield Information Barriers, and Storage Policies.
  2. Understand the difference between boxsdk (v3) and box_sdk_gen (v10)

    main

    The v10 release introduces a fundamental change in how the SDK is built:

    • v3 and lower (boxsdk): Manually maintained code.
    • v10 and higher (box_sdk_gen): Auto-generated code based on the OpenAPI Specification. This ensures faster access to the latest Box API features.

    Hybrid Usage (v4 Package): Box provides a v4 version of the SDK that consolidates both the legacy boxsdk (v3) and the new box_sdk_gen (v10) packages. This allows you to use new features from box_sdk_gen incrementally without a full immediate migration of your entire codebase. However, full migration to v10 is recommended.

  3. Use the `fields` parameter to request specific user attributes

    main

    By default, Box returns a standard set of fields. To retrieve additional attributes, use the fields parameter (a list of strings) in methods like get_users, create_user, get_user_me, or get_user_by_id.

    Warning: Specifying the fields parameter changes the response behavior. Only the requested fields (plus a minimal representation) will be returned; standard fields are excluded unless explicitly requested in the list.

  4. Switch from Service Account to App User in JWT Auth

    main

    If you are using JWT authentication, you can switch from the default Service Account to a specific App User. This can be done in two ways:

    1. Using an existing auth object: Call .with_user_subject('USER_ID') on your current BoxJWTAuth instance. This returns a new auth object without modifying the original.
    2. Directly in JWTConfig: Pass the user_id instead of enterprise_id when constructing the JWTConfig object.
    from box_sdk_gen import BoxClient, BoxJWTAuth, JWTConfig
    
    # Method 1: Using with_user_subject
    jwt_config = JWTConfig.from_config_file(config_file_path="/path/to/settings.json")
    auth = BoxJWTAuth(config=jwt_config)
    user_auth = auth.with_user_subject("USER_ID")
    user_client = BoxClient(auth=user_auth)
    
    # Method 2: Direct user_id in config
    jwt_config = JWTConfig(
        client_id="YOUR_CLIENT_ID",
        client_secret="YOUR_CLIENT_SECRET",
        jwt_key_id="YOUR_JWT_KEY_ID",
        private_key="YOUR_PRIVATE_KEY",
        private_key_passphrase="PASSPHRASE",
        user_id="USER_ID",
    )
    auth = BoxJWTAuth(config=jwt_config)
    user_client = BoxClient(auth=auth)
  5. Manage Box Sign requests with SignRequestsManager

    main

    The SignRequestsManager provides methods to manage the lifecycle of signature requests through the client.sign_requests interface.

    Available Operations:

    • cancel_sign_request(sign_request_id, reason=None): Cancels an existing request.
    • resend_sign_request(sign_request_id): Resends the signature request email to all outstanding signers (processed asynchronously).
    • get_sign_request_by_id(sign_request_id): Retrieves a specific SignRequest object.
    • get_sign_requests(marker=None, limit=None, senders=None, shared_requests=None): Lists signature requests created by the user.
    • create_sign_request(...): Initiates a new signature request.
  6. Understand the Box SDK Retry Strategy

    main

    The SDK uses a built-in BoxRetryStrategy via the BoxNetworkClient to automatically retry failed API requests using exponential backoff.

    The strategy relies on two main methods:

    • should_retry: Decides if a retry is appropriate based on HTTP status codes (e.g., 429, 5xx, 401), headers, and attempt counts.
    • retry_after: Calculates the delay before the next attempt, prioritizing the server's Retry-After header if present, otherwise using an exponential backoff formula.

    Retry Decision Logic:

    • Network Exceptions (Status 0): Retried up to max_retries_on_exception times. These use a separate counter from HTTP errors.
    • HTTP 202 (Accepted): Retried if a Retry-After header is present.
    • HTTP 5xx (Server Errors): Retried automatically.
    • HTTP 429 (Rate Limited): Retried automatically.
    • HTTP 401 (Unauthorized): The SDK attempts to refresh the token and then retries the request.
  7. Switch between Service Account and User in CCG

    main

    When using BoxCCGAuth, you can easily switch between a Service Account and a User by creating new auth objects from the existing one using subject-specific methods. The new token is automatically fetched on the next API call.

    from box_sdk_gen import BoxClient, BoxCCGAuth, CCGConfig
    
    # Initial CCG setup (e.g., as Service Account)
    ccg_config = CCGConfig(
        client_id="YOUR_CLIENT_ID",
        client_secret="YOUR_CLIENT_SECRET",
        enterprise_id="YOUR_ENTERPRISE_ID",
    )
    auth = BoxCCGAuth(config=ccg_config)
    
    # Switch to Enterprise Subject
    enterprise_auth = auth.with_enterprise_subject(enterprise_id="YOUR_ENTERPRISE_ID")
    enterprise_client = BoxClient(auth=enterprise_auth)
    
    # Switch to User Subject
    user_auth = auth.with_user_subject(user_id="YOUR_USER_ID")
    user_client = BoxClient(auth=user_auth)
  8. Work with the Immutable design in `box_sdk_gen`

    main

    The box_sdk_gen package follows an immutable design pattern. Instead of modifying an existing object in place, methods that change the state of a client or configuration return a new instance of the class with the updated state.

    Methods that return a new modified instance typically use the with_ prefix. This prevents side effects and makes code more predictable.

    from box_sdk_gen import BoxClient
    
    # Returns a NEW client instance configured to act as the specified user
    as_user_client: BoxClient = client.with_as_user_header("USER_ID")
  9. How event deduplication works in the Event Stream

    main
    The EventStream class includes built-in deduplication logic. It tracks events based on their unique event_id. If the same event is received multiple times via the long-polling mechanism, the SDK ensures it is only emitted once to your listeners, preventing redundant processing of the same event.
  10. Configure Token Storage types

    main

    The SDK uses TokenStorage to manage how tokens are persisted. You can choose from several built-in implementations via OAuthConfig:

    • In-memory (Default): Tokens are stored in volatile memory and lost when the application stops.
    • FileTokenStorage: Persists tokens to a file so they can be reused across application runs.
    • FileWithInMemoryCacheTokenStorage: Combines file persistence with an in-memory cache for fast access while maintaining persistence.
    • Custom Storage: Implement the TokenStorage interface to use your own storage mechanism (e.g., a database).
    from box_sdk_gen import BoxOAuth, OAuthConfig, FileTokenStorage, FileWithInMemoryCacheTokenStorage
    
    # Use FileTokenStorage
    auth_file = BoxOAuth(
        OAuthConfig(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
            token_storage=FileTokenStorage(),
        )
    )
    
    # Use FileWithInMemoryCacheTokenStorage
    auth_cache = BoxOAuth(
        OAuthConfig(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
            token_storage=FileWithInMemoryCacheTokenStorage(),
        )
    )