WebexPythonSDK

repository·main·Indexed 42 days ago

https://github.com/webexcommunity/webexpythonsdk

A community-developed Python library for interacting with Cisco Webex APIs. It provides a native Pythonic experience with automatic handling of authentication, pagination, and rate-limiting. The SDK includes the WebexAPI client for managing resources like people, rooms, messages, and teams, as well as a dedicated module for building and processing Adaptive Cards.

Tokens
14.6K
Snippets
36
Records
59
Agent score
53%

What's inside WebexPythonSDK

  1. Overview of webexpythonsdk

    main

    webexpythonsdk is a community-developed, lightweight, and scalable Python API wrapper for the Cisco Webex APIs. It provides a native Pythonic experience for interacting with Webex services, allowing developers to avoid writing boilerplate code for API semantics.

    Key capabilities include:

    • Interacting with Webex APIs in interactive Python sessions.
    • Rapidly developing automation and integrations for Webex.
    • Cleanly adding Webex functionality to existing Python projects.
  2. Explore the WebexPythonSDK API structure

    main

    The WebexAPI class serves as the primary entry point for interacting with the Webex service. It provides access to various API resource groups, each containing specific methods for performing CRUD (Create, Read, Update, Delete) operations or listing resources.

    Common resource groups include:

    • People: Manage users with methods like list(), create(), get(), update(), and me().
    • Rooms: Manage Webex rooms with methods like list(), create(), get(), get_meeting_info(), update(), and delete().
    • Messages: Interact with messages using list(), list_direct(), create(), get(), and delete().
    • Teams: Manage teams via list(), create(), get(), update(), and delete().
    • Webhooks: Manage webhooks with list(), create(), get(), update(), and delete().
    • Memberships: Manage room memberships with list(), create(), get(), update(), and delete().

    Each resource group is organized under the WebexAPI instance, allowing for a hierarchical way to access Webex features.

  3. Access Webex data using Python object notation

    main

    The webexpythonsdk converts JSON responses from the Webex cloud into native Python objects. Instead of parsing dictionaries, you can access data attributes using dot (.) notation. This enables IDE auto-completion and cleaner code.

    Key Behaviors:

    • Attribute Access: Use object.attribute_name to retrieve values.
    • Optional Attributes: If an attribute is optional (e.g., teamId on a Room object), the SDK returns None if the attribute is missing, rather than raising an AttributeError. This allows for cleaner checks like if room.teamId: instead of using hasattr() or try/except blocks.
    • New Attributes: If Webex adds new data attributes to their API, you can access them immediately via dot notation even without a package update, though IDE tab-completion will not work until the SDK is updated.
    >>> me = api.people.me()
    >>> me.id
    'Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mZjhlZTZmYi1hZmVmLTRhNGQtOTJiMS1kNmIyMTZiNTg5NDk'
    >>> me.displayName
    'Chris Lunsford'
  4. How the WebexAPI connection object works

    main
    The WebexAPI class serves as the primary entry point for the SDK. It creates "connection objects" that hierarchically organize Webex APIs and their endpoints. You interact with specific Webex services by accessing their corresponding API objects through the WebexAPI instance.
  5. Iterate through paginated Webex lists using GeneratorContainer

    main

    When an API call returns a list of items (like rooms or messages), the SDK returns a GeneratorContainer. This object handles Webex API pagination (RFC5988) automatically.

    How it works:

    • Automatic Pagination: The GeneratorContainer incrementally requests subsequent pages from the Webex Cloud as you iterate through it.
    • Live Data: Every time you iterate over a GeneratorContainer, fresh API calls are made. This ensures you are always working with live data.
    • Reusability: You can iterate over the same GeneratorContainer multiple times.
    • Conversion to List: If you need a static snapshot of the data, you can convert the iterable to a standard Python list using list().
    >>> # Returns an iterable object yielding all rooms you are a member of
    >>> rooms = api.rooms.list()
    >>> for room in rooms:
    ...     if 'webexpythonsdk' in room.title:
    ...         demo_room = room
    ...         break
    
    >>> # Convert to a static list if needed
    >>> rooms_list = list(rooms)
  6. How webexpythonsdk works

    main

    The webexpythonsdk is designed to provide a native Python experience for interacting with Webex APIs. Key architectural features include:

    • Authentication: It transparently sources your Webex access token from your local environment.
    • Connection Object: The WebexAPI class serves as the central connection object.
    • Hierarchical API: Methods are organized hierarchically under the WebexAPI instance (e.g., api.rooms.list(), api.messages.create()).
    • Native Data Objects: API responses are returned as native Python objects rather than raw JSON.
    • Automatic Handling: The SDK automatically manages pagination, rate-limiting (wait/retry logic), and multipart encoding for file uploads.
  7. Initialize the WebexAPI client

    main

    To start using the SDK, import WebexAPI and instantiate it. The SDK automatically looks for your Webex access token in the WEBEX_ACCESS_TOKEN environment variable, so you don't need to pass it manually in the constructor.

    Key features of the WebexAPI client:

    • Hierarchical API Access: All Webex API calls are organized into a tree of native Python methods.
    • Dot Syntax: Returned JSON objects are converted into native Python objects, allowing you to access attributes using object.attribute instead of dictionary keys.
    • Automatic Pagination: When calling list methods, the SDK transparently handles fetching subsequent pages of results.
    • Automatic Rate-Limit Handling: If you hit Webex rate limits, the SDK automatically pauses and retries your requests without requiring code changes.
    from webexpythonsdk import WebexAPI
    
    # Ensure WEBEX_ACCESS_TOKEN is set in your environment
    api = WebexAPI()
  8. Process adaptive card actions via webhooks

    main

    When a user interacts with an adaptive card (e.g., clicks a button), Webex sends an attachmentActions webhook to your application.

    1. Webhook Setup

    You must configure a webhook with the following settings:

    • resource: attachmentActions
    • event: created

    2. Extracting the Action ID

    The webhook payload contains the action ID in ['data']['id'].

    3. Retrieving Action Data

    Use the api.attachment_actions.get() method with the extracted ID to retrieve the full action details and the data submitted by the user via the card's inputs.

    # Assuming webhookJson is the payload received from Webex
    # 1. Extract the ID from the webhook payload
    action_id = webhookJson['data']['id']
    
    # 2. Use the SDK to get the full action information
    action = api.attachment_actions.get(action_id)
    
    # 3. Access the submitted input data
    first_name = action.inputs['first_name']
    age = action.inputs['age']
  9. Author adaptive cards using Python abstractions

    main

    The webexpythonsdk provides a Pythonic abstraction for creating Adaptive Cards without manually constructing complex JSON structures. You can compose cards using specialized model classes for the card container, body elements (like TextBlock), inputs (like Text or Number), and actions (like Submit).

    To send a card, include the AdaptiveCard instance in the attachments list of the api.messages.create() method.

    from webexpythonsdk import WebexAPI
    from webexpythonsdk.models.cards.card import AdaptiveCard
    from webexpythonsdk.models.cards.inputs import Text, Number
    from webexpythonsdk.models.cards.card_elements import TextBlock
    from webexpythonsdk.models.cards.actions import Submit
    
    # Define card elements
    greeting = TextBlock("Hey hello there! I am a adaptive card")
    first_name = Text('first_name', placeholder="First Name")
    age = Number('age', placeholder="Age")
    
    # Define actions
    submit = Submit(title="Send me!")
    
    # Compose the card
    card = AdaptiveCard(body=[greeting, first_name, age], actions=[submit])
    
    # Send the card via a message
    api = WebexAPI()
    api.messages.create(text="fallback", roomId="YOUR_ROOM_ID", attachments=[card])
  10. Extend the WebexAPI with custom bound methods

    main

    You can extend the functionality of the WebexAPI connection object by binding your own methods to it. This allows you to leverage the existing session and object-handling features of the SDK for new API endpoints.

    >>> def new_method(self, param):
    ...     json_obj = self._session.get('/example/action/' + param)
    ...     return json_obj
    
    >>> api = WebexAPI()
    >>> api.new_method = new_method
    >>> output = api.new_method(param)