webexsdk

package
v2.0.18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 4, 2026 License: MPL-2.0 Imports: 12 Imported by: 3

README

webexsdk

The webexsdk package is the core foundation of the Webex Go SDK. It provides the HTTP client, configuration, authentication, automatic retry with exponential backoff, pagination, structured error types, and the plugin system that all API modules build on.

Note: Most users should import the top-level webex package, which lazily initialises all API modules. The webexsdk package is documented here for advanced use-cases, custom configuration, and error handling.

Overview

This package provides:

  1. Client — Authenticated HTTP client for the Webex REST API
  2. Config — Timeout, retry, and base URL configuration
  3. Automatic Retry — Exponential backoff for 429, 423, 502, 503, 504
  4. Pagination — RFC 5988 Link header parsing via Page
  5. Structured Errors — Type-safe error hierarchy with convenience checkers
  6. Multipart UploadRequestMultipart for file uploads
  7. Plugin System — Interface for extending the client

Installation

import "github.com/WebexCommunity/webex-go-sdk/v2/webexsdk"

Configuration

cfg := &webexsdk.Config{
    BaseURL:        "https://webexapis.com/v1", // Default
    Timeout:        30 * time.Second,           // Default
    MaxRetries:     3,                          // Default (0 disables retries)
    RetryBaseDelay: 1 * time.Second,            // Default (exponential: delay * 2^attempt)
    Logger:         log.Default(),              // Any webexsdk.Logger (Printf method)
    HttpClient:     nil,                        // Custom *http.Client (optional)
    DefaultHeaders: map[string]string{          // Extra headers on every request
        "X-Custom": "value",
    },
}

client, err := webexsdk.NewClient("YOUR_ACCESS_TOKEN", cfg)
Config Fields
Field Type Default Description
BaseURL string https://webexapis.com/v1 Webex API base URL
Timeout time.Duration 30s HTTP client timeout
MaxRetries int 3 Max retry attempts (0 = no retries)
RetryBaseDelay time.Duration 1s Initial retry delay (exponential backoff)
Logger Logger log.Default() Logger with Printf(format, v...)
HttpClient *http.Client auto-created Custom HTTP client
DefaultHeaders map[string]string empty Headers added to every request

Automatic Retry

The SDK automatically retries requests that receive transient error responses:

Status Code Meaning Retry Behaviour
429 Too Many Requests Wait Retry-After header duration, then retry
423 Locked (malware scanning) Wait Retry-After header duration, then retry
502 Bad Gateway Exponential backoff
503 Service Unavailable Exponential backoff
504 Gateway Timeout Exponential backoff

Backoff formula: RetryBaseDelay * 2^attempt (e.g., 1s → 2s → 4s → 8s).

When Retry-After is present (429 and 423), the header value overrides the calculated backoff.

All request methods support retry: Request, RequestURL, RequestMultipart.

Pagination

List endpoints return paginated results. The Page type parses RFC 5988 Link headers automatically:

// First page
resp, err := client.Request(http.MethodGet, "rooms", params, nil)
page, err := webexsdk.NewPage(resp, client, "rooms")

// Iterate through items
for _, raw := range page.Items {
    var room rooms.Room
    json.Unmarshal(raw, &room)
}

// Next page
if page.HasNext {
    nextPage, err := page.Next()
}

// Previous page
if page.HasPrev {
    prevPage, err := page.Prev()
}
Page Fields
Field Type Description
Items []json.RawMessage Raw JSON items (unmarshal into your type)
HasNext bool Whether a next page exists
HasPrev bool Whether a previous page exists
NextPage string Absolute URL for the next page
PrevPage string Absolute URL for the previous page
Direct Cursor Navigation

Save a cursor URL and jump directly to any page later — no sequential traversal needed:

// Session 1: paginate and save a cursor
page, _ := webhooksClient.List(&webhooks.ListOptions{Max: 10})
cursor := page.NextPage  // save this (e.g., to a database or cache)

// Session 2 (later): jump directly to the saved page
resumedPage, _ := client.PageFromCursor(cursor)
for _, raw := range resumedPage.Items {
    // process items
}

// Continue pagination from the resumed position
if resumedPage.HasNext {
    nextPage, _ := resumedPage.Next()
    // ...
}

This is ideal for:

  • Bookmarking a position in a large result set
  • Resuming pagination after a process restart
  • Skipping pages you've already processed
Supported Modules

All modules with list/pagination endpoints embed *Page and support PageFromCursor:

Module Page Type List Method
rooms RoomsPage List(&ListOptions{})
messages MessagesPage List(&ListOptions{})
teams TeamsPage List(&ListOptions{})
webhooks WebhooksPage List(&ListOptions{})
meetings MeetingsPage List(&ListOptions{})
events EventsPage List(&ListOptions{})
memberships MembershipsPage List(&ListOptions{})
teammemberships TeamMembershipsPage List(&ListOptions{})
recordings RecordingsPage List(&ListOptions{})
transcripts TranscriptsPage List(&ListOptions{})
roomtabs RoomTabsPage List(&ListOptions{})
people PeoplePage List(&ListOptions{})

Structured Errors

All API errors are returned as typed structs. The base type is APIError, with specific sub-types for common HTTP status codes:

Error Type HTTP Status Description
*AuthError 401 Invalid or expired access token
*ForbiddenError 403 Insufficient permissions
*NotFoundError 404 Resource not found
*ConflictError 409 Resource conflict
*GoneError 410 Resource permanently removed (e.g., infected file)
*LockedError 423 Resource locked (e.g., file being scanned)
*PreconditionRequiredError 428 Precondition required (e.g., unscannable file)
*RateLimitError 429 Rate limited (RetryAfter field set)
*ServerError 5xx Server-side error
*APIError other Generic API error
APIError Fields
Field Type Description
StatusCode int HTTP status code
Status string HTTP status line
Message string Error message from API response body
TrackingID string Webex tracking ID for support
RetryAfter time.Duration Retry wait time (429, 423)
RawBody []byte Raw response body
Convenience Functions

Use errors.As or these helpers to check error types:

resp, err := client.Request(http.MethodGet, "rooms/invalid", nil, nil)
if err != nil {
    switch {
    case webexsdk.IsNotFound(err):
        // Handle 404
    case webexsdk.IsAuthError(err):
        // Handle 401
    case webexsdk.IsForbidden(err):
        // Handle 403
    case webexsdk.IsRateLimited(err):
        // Handle 429 — check RetryAfter
        var rl *webexsdk.RateLimitError
        if errors.As(err, &rl) {
            time.Sleep(rl.RetryAfter)
        }
    case webexsdk.IsGone(err):
        // Handle 410
    case webexsdk.IsLocked(err):
        // Handle 423
    case webexsdk.IsPreconditionRequired(err):
        // Handle 428
    case webexsdk.IsConflict(err):
        // Handle 409
    case webexsdk.IsServerError(err):
        // Handle 5xx
    default:
        // Generic API error
        var apiErr *webexsdk.APIError
        if errors.As(err, &apiErr) {
            log.Printf("API error %d: %s (trackingId: %s)",
                apiErr.StatusCode, apiErr.Message, apiErr.TrackingID)
        }
    }
}

Request Methods

Method Description
Request(method, path, params, body) Relative path request with retry
RequestWithContext(ctx, method, path, params, body) Single request with context (no retry)
RequestWithRetry(ctx, method, path, params, body) Relative path request with context + retry
RequestURL(method, fullURL, body) Absolute URL request with retry
RequestURLWithRetry(ctx, method, fullURL, body) Absolute URL request with context + retry
RequestMultipart(path, fields, files) Multipart form-data POST with retry
RequestMultipartWithRetry(ctx, path, fields, files) Multipart POST with context + retry
PageFromCursor(cursorURL) Direct navigation to a page via saved cursor URL

Plugin System

API modules implement the Plugin interface and can be registered with the client:

type Plugin interface {
    Name() string
}

client.RegisterPlugin(myPlugin)
plugin, ok := client.GetPlugin("myPlugin")

Logger Interface

Any type implementing Printf can be used as the SDK logger:

type Logger interface {
    Printf(format string, v ...any)
}

The standard library's *log.Logger satisfies this interface.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsAuthError added in v2.0.14

func IsAuthError(err error) bool

IsAuthError reports whether err is an authentication error (HTTP 401).

func IsConflict added in v2.0.14

func IsConflict(err error) bool

IsConflict reports whether err is a conflict error (HTTP 409).

func IsForbidden added in v2.0.14

func IsForbidden(err error) bool

IsForbidden reports whether err is a forbidden error (HTTP 403).

func IsGone added in v2.0.14

func IsGone(err error) bool

IsGone reports whether err is a gone error (HTTP 410).

func IsLocked added in v2.0.14

func IsLocked(err error) bool

IsLocked reports whether err is a locked error (HTTP 423).

func IsNotFound added in v2.0.14

func IsNotFound(err error) bool

IsNotFound reports whether err is a not found error (HTTP 404).

func IsPreconditionRequired added in v2.0.14

func IsPreconditionRequired(err error) bool

IsPreconditionRequired reports whether err is a precondition required error (HTTP 428).

func IsRateLimited added in v2.0.14

func IsRateLimited(err error) bool

IsRateLimited reports whether err is a rate limit error (HTTP 429).

func IsServerError added in v2.0.14

func IsServerError(err error) bool

IsServerError reports whether err is a server error (HTTP 5xx).

func NewAPIError added in v2.0.14

func NewAPIError(resp *http.Response, body []byte) error

NewAPIError creates a structured error from an HTTP response and its body. It parses the JSON body for message and trackingId fields, reads the Retry-After header, and returns the appropriate error sub-type based on the HTTP status code.

func ParseResponse

func ParseResponse(resp *http.Response, v interface{}) error

ParseResponse parses an HTTP response into the given interface

Types

type APIError added in v2.0.14

type APIError struct {
	// StatusCode is the HTTP status code from the response.
	StatusCode int

	// Status is the HTTP status line (e.g., "404 Not Found").
	Status string

	// Message is the error message from the Webex API response body.
	Message string

	// TrackingID is the Webex tracking identifier for support debugging.
	TrackingID string

	// RetryAfter is the duration to wait before retrying, parsed from
	// the Retry-After header. Zero if not applicable.
	RetryAfter time.Duration

	// RawBody is the raw response body bytes, preserved for debugging.
	RawBody []byte

	// Err is an optional wrapped error for errors.Unwrap support.
	Err error
}

APIError is the base error type for all Webex API errors. It provides structured access to the HTTP status code, error message, tracking ID, and raw response body. All specific error sub-types embed this struct, so consumers can use errors.As(err, &apiErr) to access common fields regardless of the specific error type.

func (*APIError) Error added in v2.0.14

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) Unwrap added in v2.0.14

func (e *APIError) Unwrap() error

Unwrap returns the wrapped error, if any.

type AuthError added in v2.0.14

type AuthError struct {
	*APIError
}

AuthError is returned for HTTP 401 Unauthorized responses.

func (*AuthError) Unwrap added in v2.0.14

func (e *AuthError) Unwrap() error

Unwrap returns the underlying APIError for errors.As traversal.

type Client

type Client struct {

	// Base URL for API requests
	BaseURL *url.URL

	// Configuration for the client
	Config *Config
	// contains filtered or unexported fields
}

Client is the main Webex client struct

func NewClient

func NewClient(accessToken string, config *Config) (*Client, error)

NewClient creates a new Webex client with the given access token and optional configuration If config is nil, the default configuration will be used.

func (*Client) GetAccessToken

func (c *Client) GetAccessToken() string

GetAccessToken returns the access token used for API authentication

func (*Client) GetHTTPClient

func (c *Client) GetHTTPClient() *http.Client

GetHTTPClient returns the HTTP client used for API requests

func (*Client) GetLogger

func (c *Client) GetLogger() Logger

GetLogger returns the logger used by the SDK.

func (*Client) GetPlugin

func (c *Client) GetPlugin(name string) (Plugin, bool)

GetPlugin returns a plugin by name

func (*Client) PageFromCursor added in v2.0.16

func (c *Client) PageFromCursor(cursorURL string) (*Page, error)

PageFromCursor fetches a page directly from a cursor URL (e.g., a previously saved NextPage or PrevPage). This enables direct navigation to any page without sequential traversal — useful for bookmarking or resuming pagination.

Usage:

page, _ := webhooksClient.List(&ListOptions{Max: 10})
cursor := page.NextPage  // save this to a database, cache, etc.

// Later — jump directly to that page:
resumedPage, _ := client.PageFromCursor(cursor)

func (*Client) RegisterPlugin

func (c *Client) RegisterPlugin(plugin Plugin)

RegisterPlugin registers a plugin with the client

func (*Client) Request

func (c *Client) Request(method, path string, params url.Values, body interface{}) (*http.Response, error)

Request performs an HTTP request to the Webex API with automatic retry for transient errors (429, 502, 503, 504). The caller is responsible for closing the response body when done.

func (*Client) RequestMultipart

func (c *Client) RequestMultipart(path string, fields []MultipartField, files []MultipartFile) (*http.Response, error)

RequestMultipart performs a multipart/form-data POST request to the Webex API with automatic retry for transient errors (429, 502, 503, 504). This is required for local file uploads (e.g., sending messages with attachments). The caller is responsible for closing the response body when done.

func (*Client) RequestMultipartWithRetry added in v2.0.14

func (c *Client) RequestMultipartWithRetry(ctx context.Context, path string, fields []MultipartField, files []MultipartFile) (*http.Response, error)

RequestMultipartWithRetry performs a multipart/form-data POST with retry support. The multipart body is rebuilt on each retry attempt.

func (*Client) RequestURL added in v2.0.14

func (c *Client) RequestURL(method, fullURL string, body interface{}) (*http.Response, error)

RequestURL performs an HTTP GET request to a full URL (not relative to BaseURL). This is used for pagination where Link headers contain absolute URLs. The request includes the same authentication and default headers as regular requests. The caller is responsible for closing the response body when done.

func (*Client) RequestURLWithRetry added in v2.0.14

func (c *Client) RequestURLWithRetry(ctx context.Context, method, fullURL string, body interface{}) (*http.Response, error)

RequestURLWithRetry performs an HTTP request to a full URL with retry logic.

func (*Client) RequestWithContext

func (c *Client) RequestWithContext(ctx context.Context, method, path string, params url.Values, body interface{}) (*http.Response, error)

RequestWithContext performs an HTTP request to the Webex API with the given context. The context can be used for per-request timeouts and cancellation. The caller is responsible for closing the response body when done.

func (*Client) RequestWithRetry

func (c *Client) RequestWithRetry(ctx context.Context, method, path string, params url.Values, body interface{}) (*http.Response, error)

RequestWithRetry performs an HTTP request with automatic retry for transient errors. It retries on HTTP 429 (Too Many Requests, respecting Retry-After header) and transient server errors (502, 503, 504) using exponential backoff. The caller is responsible for closing the response body when done.

type Config

type Config struct {
	// BaseURL is the base URL of the Webex API
	BaseURL string

	// Timeout for API requests
	Timeout time.Duration

	// Default headers to include in API requests
	DefaultHeaders map[string]string

	// Custom HTTP client to use instead of the default one
	// If nil, a default client will be created with the specified Timeout
	HttpClient *http.Client

	// MaxRetries is the maximum number of retries for transient errors (429, 502, 503, 504).
	// Set to 0 to disable retries. Default: 3.
	MaxRetries int

	// RetryBaseDelay is the initial delay between retries. Default: 1s.
	// Subsequent retries use exponential backoff (delay * 2^attempt).
	RetryBaseDelay time.Duration

	// Logger is the logger for SDK operations. If nil, the standard library's
	// default logger (log.Default()) is used.
	Logger Logger
}

Config holds the configuration for the Webex client

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration for the Webex client

type ConflictError added in v2.0.14

type ConflictError struct {
	*APIError
}

ConflictError is returned for HTTP 409 Conflict responses.

func (*ConflictError) Unwrap added in v2.0.14

func (e *ConflictError) Unwrap() error

Unwrap returns the underlying APIError for errors.As traversal.

type FieldError added in v2.0.14

type FieldError struct {
	// Code is the error code (e.g., "kms_failure").
	Code string `json:"code"`
	// Reason describes why the field could not be retrieved.
	Reason string `json:"reason"`
}

FieldError represents an error on a specific field of a resource. When the Webex API encounters a partial failure retrieving a resource in a list response, individual fields may contain errors instead of their normal values.

type ForbiddenError added in v2.0.14

type ForbiddenError struct {
	*APIError
}

ForbiddenError is returned for HTTP 403 Forbidden responses.

func (*ForbiddenError) Unwrap added in v2.0.14

func (e *ForbiddenError) Unwrap() error

Unwrap returns the underlying APIError for errors.As traversal.

type GoneError added in v2.0.14

type GoneError struct {
	*APIError
}

GoneError is returned for HTTP 410 Gone responses. For the Contents API, this indicates an infected file that was removed.

func (*GoneError) Unwrap added in v2.0.14

func (e *GoneError) Unwrap() error

Unwrap returns the underlying APIError for errors.As traversal.

type LockedError added in v2.0.14

type LockedError struct {
	*APIError
}

LockedError is returned for HTTP 423 Locked responses. For the Contents API, this indicates a file is being scanned for malware. The RetryAfter field (inherited from APIError) indicates when to retry.

func (*LockedError) Unwrap added in v2.0.14

func (e *LockedError) Unwrap() error

Unwrap returns the underlying APIError for errors.As traversal.

type Logger

type Logger interface {
	Printf(format string, v ...any)
}

Logger is the interface for SDK logging. Any logger that implements Printf (such as the standard library's *log.Logger) can be used.

type MultipartField

type MultipartField struct {
	Name  string
	Value string
}

MultipartField represents a text field in a multipart request.

type MultipartFile

type MultipartFile struct {
	FieldName string // Form field name (e.g., "files")
	FileName  string // Original filename (e.g., "report.pdf")
	Content   []byte // Raw file bytes
}

MultipartFile represents a file to upload in a multipart request.

type NotFoundError added in v2.0.14

type NotFoundError struct {
	*APIError
}

NotFoundError is returned for HTTP 404 Not Found responses.

func (*NotFoundError) Unwrap added in v2.0.14

func (e *NotFoundError) Unwrap() error

Unwrap returns the underlying APIError for errors.As traversal.

type Page

type Page struct {
	Items    []json.RawMessage `json:"items"`
	NextPage string            `json:"-"`
	PrevPage string            `json:"-"`
	HasNext  bool              `json:"-"`
	HasPrev  bool              `json:"-"`
	Client   *Client           `json:"-"`
	Resource Resource          `json:"-"`
}

Page represents a paginated response from the Webex API. Pagination follows RFC 5988 (Web Linking) — next/prev URLs are parsed from the response's Link header.

func NewPage

func NewPage(resp *http.Response, client *Client, resource Resource) (*Page, error)

NewPage creates a new Page from an HTTP response. It parses the Link header (RFC 5988) for pagination URLs and the JSON body for the items array.

func (*Page) Next

func (p *Page) Next() (*Page, error)

Next retrieves the next page of results using the URL from the Link header.

func (*Page) Prev

func (p *Page) Prev() (*Page, error)

Prev retrieves the previous page of results using the URL from the Link header.

type Plugin

type Plugin interface {
	// Name returns the name of the plugin
	Name() string
}

Plugin represents a Webex API plugin

type PreconditionRequiredError added in v2.0.14

type PreconditionRequiredError struct {
	*APIError
}

PreconditionRequiredError is returned for HTTP 428 Precondition Required responses. For the Contents API, this indicates an unscannable file. Adding the query parameter allow=unscannable will enable the download.

func (*PreconditionRequiredError) Unwrap added in v2.0.14

func (e *PreconditionRequiredError) Unwrap() error

Unwrap returns the underlying APIError for errors.As traversal.

type RateLimitError added in v2.0.14

type RateLimitError struct {
	*APIError
}

RateLimitError is returned for HTTP 429 Too Many Requests responses. The RetryAfter field (inherited from APIError) indicates how long to wait.

func (*RateLimitError) Unwrap added in v2.0.14

func (e *RateLimitError) Unwrap() error

Unwrap returns the underlying APIError for errors.As traversal.

type Resource added in v2.0.16

type Resource string

Resource is a typed string identifying a Webex API resource collection.

const (
	ResourceRooms               Resource = "rooms"
	ResourceMessages            Resource = "messages"
	ResourceTeams               Resource = "teams"
	ResourceWebhooks            Resource = "webhooks"
	ResourceMeetings            Resource = "meetings"
	ResourceMeetingParticipants Resource = "meetingParticipants"
	ResourceMemberships         Resource = "memberships"
	ResourcePeople              Resource = "people"
	ResourceTeamMemberships     Resource = "team/memberships"
	ResourceRecordings          Resource = "recordings"
	ResourceTranscripts         Resource = "meetingTranscripts"
	ResourceEvents              Resource = "events"
	ResourceRoomTabs            Resource = "room/tabs"
	ResourceItems               Resource = "items"
)

type ResourceErrors added in v2.0.14

type ResourceErrors map[string]FieldError

ResourceErrors maps field names to their errors within a single resource. Present in list response items when partial failures occur (HTTP 200 with some items having field-level errors).

Example JSON:

"errors": {
  "title": {
    "code": "kms_failure",
    "reason": "Key management server failed to respond appropriately."
  }
}

func (ResourceErrors) HasErrors added in v2.0.14

func (re ResourceErrors) HasErrors() bool

HasErrors returns true if this ResourceErrors map contains any errors.

func (ResourceErrors) HasFieldError added in v2.0.14

func (re ResourceErrors) HasFieldError(field string) bool

HasFieldError returns true if the specified field has an error.

type ServerError added in v2.0.14

type ServerError struct {
	*APIError
}

ServerError is returned for HTTP 5xx responses (500, 502, 503, 504).

func (*ServerError) Unwrap added in v2.0.14

func (e *ServerError) Unwrap() error

Unwrap returns the underlying APIError for errors.As traversal.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL