Smartsheet Python SDK

repository·master·Indexed 40 days ago

https://github.com/smartsheet-platform/smartsheet-python-sdk

A library designed to simplify connections between Python applications and the Smartsheet API. It supports Python 3.6+ and pypy, providing tools for event reporting streams, HTTP proxy configuration, and passthrough methods for unsupported API features. It includes specialized support for Smartsheetgov.com and Smartsheet Regions Europe instances.

Tokens
3K
Snippets
12
Records
13
Agent score
49%

What's inside Smartsheet

  1. Quickstart with the Smartsheet Python SDK

    master

    To begin using the Smartsheet Python SDK, follow these three steps:

    1. Set your access token: Define the SMARTSHEET_ACCESS_TOKEN environment variable in your system. You can obtain this via direct API access in the Smartsheet platform.
    2. Install the SDK: Use pip to install the package.
    3. Import the module: Import smartsheet in your Python script to start interacting with the API.

    For more complex operations, refer to the full Smartsheet API Documentation for specific usage examples.

    # 1. Set environment variable
    export SMARTSHEET_ACCESS_TOKEN='your_access_token_here'
    
    # 2. Install the SDK
    pip install smartsheet-python-sdk
    # 3. Import the module
    import smartsheet
  2. Quickstart: Getting Started with the Smartsheet Python SDK

    master

    Follow these steps to set up your first Smartsheet integration:

    1. Set your Access Token: Set the SMARTSHEET_ACCESS_TOKEN environment variable in your system. You can obtain a token via direct API access in the Smartsheet platform.
    2. Install the SDK: Run pip install smartsheet-python-sdk.
    3. Import the module: In your Python script, use import smartsheet.
    4. Use the API: Refer to the official Smartsheet API Documentation for specific usage examples and sample code.
    import smartsheet
  3. Get started with the Smartsheet Python SDK

    master

    Follow these steps to begin using the SDK in your Python application:

    1. Set Authentication: Set the SMARTSHEET_ACCESS_TOKEN environment variable with your Smartsheet access token.
    2. Install the SDK: Run pip install smartsheet-python-sdk.
    3. Import the module: Use import smartsheet in your Python code.
    4. Use the API: Refer to the Smartsheet API Documentation for specific method calls and usage patterns.
    import smartsheet
    # Your code here
  4. System requirements for Smartsheet Python SDK

    master

    Python Versions

    The SDK supports the following runtimes:

    • Python 3.6, 3.7, 3.8, 3.9
    • pypy
    • pypy3

    Note: Python 3.6 or higher is required for proper Unicode support (e.g., handling non-ASCII characters in Smartsheet data).

    Required Dependencies

    The following packages are required for the SDK to function:

    • requests
    • requests-toolbelt
    • six
    • certifi
    • python-dateutil
  5. Consume the Smartsheet Event Reporting stream

    master

    Use smartsheet_client.Events.list_events to consume events from the Smartsheet event stream.

    Pagination and Iteration

    • Initial Request: Use the since parameter to specify a starting point. since can be an ISO 8601 string (e.g., 2010-01-01T00:00:00Z) or a UNIX epoch. If using a UNIX epoch, you must set numeric_dates=True.
    • Subsequent Requests: To fetch the next batch, use the stream_position parameter set to the next_stream_position value from the previous response. Do not provide both since and stream_position in the same call.
    • Availability: Check the more_available property. If False, events might still be generating; continue using the same stream_position in subsequent requests until more data appears.

    Accessing Event Details

    Additional event metadata is stored in the additional_details dictionary. Note that this dictionary uses camelCase (JSON names) rather than Pythonic snake_case (e.g., use sheetName, not sheet_name).

    # this example is looking specifically for new sheet events
    def print_new_sheet_events_in_list(events_list):
        # enumerate all events in the list of returned events
        for event in events_list.data:
            # find all created sheets
            if event.object_type == smartsheet.models.enums.EventObjectType.SHEET and event.action == smartsheet.models.enums.EventAction.CREATE:
                # additional details are available for some events, they can be accessed as a Python dictionary
                # in the additional_details attribute
                print(event.additional_details['sheetName'])
    
    
    smartsheet_client = smartsheet.Smartsheet()
    smartsheet_client.errors_as_exceptions()
    
    # begin listing events in the stream starting with the `since` parameter
    last_week = datetime.now() - timedelta(days=7)
    # this example looks at the previous 7 days of events by providing a `since` argument set to last week's date in ISO format
    events_list = smartsheet_client.Events.list_events(since=last_week.isoformat(), max_count=1000)
    print_new_sheet_events_in_list(events_list)
    
    # continue listing events in the stream, if the previous response indicates that more data is available.
    while events_list.more_available:
        events_list = smartsheet_client.Events.list_events(stream_position=events_list.next_stream_position, max_count=10000,
                                            numeric_dates=True)
        print_new_sheet_events_in_list(events_list)
  6. Configure logging for the Smartsheet Python SDK

    master

    The SDK supports three log levels to help with debugging and monitoring API interactions. Use the standard Python logging.basicConfig method to configure them:

    • ERROR: Messages related to API or JSON serialization errors.
    • INFO: Messages about the API resources being requested.
    • DEBUG: API request/response bodies and messages regarding object attributes changed by the SDK due to API call nature.

    To enable detailed debugging, set the level to logging.DEBUG.

    import logging
    logging.basicConfig(filename='mylog.log', level=logging.DEBUG)
  7. Initialize client for Smartsheetgov.com or Smartsheet Regions Europe

    master

    If you are using a specialized Smartsheet instance, you must specify the correct api_base during client initialization.

    • Smartsheetgov.com: Use the constant smartsheet.__gov_base__ (Base URI: https://api.smartsheetgov.com/2.0/).
    • Smartsheet Regions Europe: Use the constant smartsheet._eu_base_ (Base URI: https://api.smartsheet.eu/2.0/).
    # For Smartsheetgov
    client = smartsheet.Smartsheet(api_base=smartsheet.__gov_base__)
    
    # For Smartsheet Regions Europe
    client = smartsheet.Smartsheet(api_base=smartsheet._eu_base__)
  8. Install the Smartsheet Python SDK

    master

    You can install the SDK using pip or by installing manually from the source code.

    Using pip

    Install the package named smartsheet-python-sdk via the Python Package Index:

    pip install smartsheet-python-sdk

    Manual Installation

    Download the source code from GitHub and run the setup script:

    python setup.py install
  9. Use the Passthrough option for unsupported API features

    master

    If an API feature is not yet implemented in the Python SDK, you can use the Passthrough methods to send and receive raw JSON objects. The client's base URL is automatically prepended to the provided endpoint.

    Available Methods:

    • client.Passthrough.get(endpoint, query_params)
    • client.Passthrough.post(endpoint, payload, query_params)
    • client.Passthrough.put(endpoint, payload, query_params)
    • client.Passthrough.delete(endpoint)

    Parameters:

    • endpoint: The specific API endpoint (e.g., '/sheets').
    • payload: The data to pass (dictionary or string).
    • query_params: An optional dictionary of query parameters.

    Handling Responses: All passthrough calls return a JSON result. Access the dictionary representation via the .data attribute. To get the raw JSON string, use the .to_json() method.

    payload = {"name": "my new sheet",
                "columns": [
                  {"title": "Favorite", "type": "CHECKBOX", "symbol": "STAR"},
                  {"title": "Primary Column", "primary": True, "type": "TEXT_NUMBER"}
                ]
              }
    
    response = client.Passthrough.post('/sheets', payload)
  10. Use the Server class to retrieve application constants

    master

    The Server class provides access to server-level operations. You can use the server_info() method to retrieve application constants (returning a ServerInfo object). This class requires an initialized smartsheet object to function, as it uses the base object to prepare and execute requests.

    # Assuming 'smartsheet' is an initialized Smartsheet client instance
    server_client = smartsheet.server
    info = server_client.server_info()
    print(info)