Documentation
¶
Overview ¶
Package intercom provides a Go client for the Intercom API v2.15.
Services are organized into domain-scoped sub-packages (contacts, tickets, tags, etc.) and accessed via accessor methods on the Client.
Usage:
client := intercom.NewClient("your-bearer-token")
// Get a contact
contact, err := client.Contacts().Get(ctx, "contact-id")
// List all contacts with auto-pagination
iter := client.Contacts().ListAll(ctx, nil)
for iter.Next() {
fmt.Println(iter.Current().Name)
}
if err := iter.Err(); err != nil {
log.Fatal(err)
}
// Or collect all pages into a slice in one call
contacts, err := client.Contacts().ListAll(ctx, nil).Collect()
// Iterate with a callback using ForEach
err = client.Contacts().ListAll(ctx, nil).ForEach(func(c contacts.Contact) error {
fmt.Println(c.Name)
return nil
})
// Search contacts with filters (types from the api/ package)
result, err := client.Contacts().Search(ctx, &api.SearchRequest{
Query: api.SingleFilterOf("email", api.OpEquals, "alice@example.com"),
})
Every service method has a Raw companion that returns a *Result with HTTP metadata (status code, headers, raw body bytes). API errors (4xx/5xx) populate Result.Error instead of returning a Go error:
result, err := client.Contacts().GetRaw(ctx, "contact-id")
if err != nil {
log.Fatal(err) // transport error only
}
if result.Error != nil {
fmt.Printf("API error %d: %s\n", result.StatusCode, result.Error.Error())
} else {
contact, _ := contacts.ParseGetResult(result)
fmt.Println(contact.Name)
fmt.Println(result.Header.Get("X-RateLimit-Remaining"))
}
The client can be configured with functional options:
client := intercom.NewClient("token",
intercom.WithHTTPClient(customHTTPClient),
intercom.WithLogger(myLogger),
intercom.WithBaseURL("https://custom.url/"),
)
All API methods accept a context.Context as their first parameter for cancellation and timeout control.
Error responses from the Intercom API are returned as *api.ErrorResponse values. Helper functions in the api/ package check for common HTTP status codes:
api.IsNotFound(err) // 404 api.IsRateLimited(err) // 429 api.IsUnauthorized(err) // 401 api.IsBadRequest(err) // 400 api.IsForbidden(err) // 403 api.IsConflict(err) // 409 api.IsUnprocessableEntity(err) // 422 api.IsServerError(err) // 5xx
For rate-limited responses (429), the ErrorResponse includes parsed rate limit headers:
if api.IsRateLimited(err) {
var apiErr *api.ErrorResponse
if errors.As(err, &apiErr) && apiErr.RateLimit != nil {
fmt.Printf("Retry after %v\n", apiErr.RateLimit.RetryAfter)
time.Sleep(apiErr.RateLimit.RetryAfter)
}
}
Intercom API error codes can be matched using HasErrorCode and the predefined ErrorCode constants:
var apiErr *api.ErrorResponse
if errors.As(err, &apiErr) {
if apiErr.HasErrorCode(api.ErrParameterInvalid) {
// handle invalid parameter
}
}
Core types (Result, Iter, Filter, ErrorResponse, ListOptions) live in the public api/ package. Sub-package-specific types (request/response structs, domain models) are imported from their respective packages.
Example (ContactsGetRaw) ¶
ExampleContactsService_GetRaw demonstrates using a Raw method to access HTTP metadata alongside the typed response data.
package main
import (
"context"
"fmt"
"log"
intercom "github.com/rassakhatsky/intercom-go-sdk"
"github.com/rassakhatsky/intercom-go-sdk/contacts"
)
func main() {
client := intercom.NewClient("your-bearer-token")
ctx := context.Background()
result, err := client.Contacts().GetRaw(ctx, "contact-id")
if err != nil {
log.Fatal(err) // only returned for transport/network errors
}
// Check for API errors (4xx/5xx) — no Go error is returned for these
if result.Error != nil {
fmt.Printf("API error %d: %s\n", result.StatusCode, result.Error.Error())
return
}
// Decode the typed response data using the Parse function
contact, err := contacts.ParseGetResult(result)
if err != nil {
log.Fatal(err)
}
fmt.Println("Contact:", contact.Name)
// Access HTTP metadata for debugging or advanced logic
fmt.Println("Status:", result.StatusCode)
fmt.Println("Rate-Limit-Remaining:", result.Header.Get("X-RateLimit-Remaining"))
// Access the raw JSON body
fmt.Println("Raw body length:", len(result.Body))
}
Output:
Example (ContactsSearchRaw) ¶
ExampleContactsService_SearchRaw demonstrates using a Raw search method with access to rate-limit headers for custom retry logic.
package main
import (
"context"
"fmt"
"log"
intercom "github.com/rassakhatsky/intercom-go-sdk"
"github.com/rassakhatsky/intercom-go-sdk/api"
"github.com/rassakhatsky/intercom-go-sdk/contacts"
)
func main() {
client := intercom.NewClient("your-bearer-token")
ctx := context.Background()
result, err := client.Contacts().SearchRaw(ctx, &api.SearchRequest{
Query: api.SingleFilterOf("email", api.OpEquals, "alice@example.com"),
})
if err != nil {
log.Fatal(err)
}
if result.Error != nil {
fmt.Printf("API error: %s\n", result.Error.Error())
return
}
page, err := contacts.ParseSearchResult(result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d contacts\n", len(page.Data))
fmt.Printf("Rate limit remaining: %s\n", result.Header.Get("X-RateLimit-Remaining"))
}
Output:
Example (ErrorCodeMatching) ¶
Example_errorCodeMatching demonstrates matching specific Intercom API error codes returned in error responses.
package main
import (
"context"
"errors"
"fmt"
"log"
intercom "github.com/rassakhatsky/intercom-go-sdk"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
client := intercom.NewClient("your-bearer-token")
ctx := context.Background()
_, err := client.Contacts().Get(ctx, "contact-id")
if err != nil {
var apiErr *api.ErrorResponse
if errors.As(err, &apiErr) {
switch {
case apiErr.HasErrorCode(api.ErrParameterInvalid):
fmt.Println("Invalid parameter:", apiErr.Error())
case apiErr.HasErrorCode(api.ErrTokenUnauthorized):
fmt.Println("Token is unauthorized, check your API key")
case apiErr.HasErrorCode(api.ErrRateLimitExceeded):
fmt.Println("Rate limit exceeded, back off and retry")
default:
fmt.Println("API error:", apiErr.Error())
}
} else {
log.Fatal(err) // transport error
}
}
}
Output:
Example (RateLimitHandling) ¶
Example_rateLimitHandling demonstrates handling rate-limited responses with parsed rate limit metadata.
package main
import (
"context"
"errors"
"fmt"
"time"
intercom "github.com/rassakhatsky/intercom-go-sdk"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
client := intercom.NewClient("your-bearer-token")
ctx := context.Background()
_, err := client.Contacts().Get(ctx, "contact-id")
if api.IsRateLimited(err) {
var apiErr *api.ErrorResponse
if errors.As(err, &apiErr) && apiErr.RateLimit != nil {
fmt.Printf("Rate limited. Limit: %d, Remaining: %d\n",
apiErr.RateLimit.Limit, apiErr.RateLimit.Remaining)
fmt.Printf("Retry after: %v\n", apiErr.RateLimit.RetryAfter)
fmt.Printf("Window resets at: %v\n", apiErr.RateLimit.Reset)
time.Sleep(apiErr.RateLimit.RetryAfter)
}
}
}
Output:
Example (ServerErrorRetry) ¶
Example_serverErrorRetry demonstrates checking for server-side errors to implement retry logic.
package main
import (
"context"
"fmt"
"log"
intercom "github.com/rassakhatsky/intercom-go-sdk"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
client := intercom.NewClient("your-bearer-token")
ctx := context.Background()
_, err := client.Contacts().Get(ctx, "contact-id")
if api.IsServerError(err) {
fmt.Println("Server error, retrying...")
// implement retry with backoff
} else if api.IsNotFound(err) {
fmt.Println("Contact not found")
} else if err != nil {
log.Fatal(err)
}
}
Output:
Index ¶
- type Client
- func (c *Client) AIContent() *aiPkg.ContentService
- func (c *Client) Admins() *admins.Service
- func (c *Client) Articles() *articles.Service
- func (c *Client) AwayStatusReasons() *admins.AwayStatusReasonsService
- func (c *Client) Brands() *settings.BrandsService
- func (c *Client) Calls() *calls.Service
- func (c *Client) Companies() *companies.Service
- func (c *Client) Contacts() *contacts.Service
- func (c *Client) Conversations() *conversations.Service
- func (c *Client) CustomChannelEvents() *settings.ChannelEventsService
- func (c *Client) CustomObjects() *data.ObjectsService
- func (c *Client) DataAttributes() *data.AttributesService
- func (c *Client) DataEvents() *data.EventsService
- func (c *Client) DataExport() *export.DataService
- func (c *Client) Do(ctx context.Context, req *http.Request, v any) (*api.Response, error)
- func (c *Client) DoDownload(ctx context.Context, req *http.Request, w io.Writer) error
- func (c *Client) DoRaw(ctx context.Context, req *http.Request) (*api.Result, error)
- func (c *Client) DoRawNoRedirect(ctx context.Context, req *http.Request) (*api.Result, error)
- func (c *Client) Emails() *messaging.EmailsService
- func (c *Client) ExportReporting() *export.ReportingService
- func (c *Client) FinVoice() *aiPkg.VoiceService
- func (c *Client) HelpCenter() *helpcenter.Service
- func (c *Client) IPAllowlist() *settings.IPAllowlistService
- func (c *Client) InternalArticles() *articles.InternalService
- func (c *Client) Jobs() *settings.JobsService
- func (c *Client) Messages() *messaging.MessagesService
- func (c *Client) NewRequest(method, urlStr string, body any) (*http.Request, error)
- func (c *Client) News() *news.Service
- func (c *Client) Notes() *settings.NotesService
- func (c *Client) PhoneCallRedirects() *calls.RedirectsService
- func (c *Client) Segments() *segments.Service
- func (c *Client) SubscriptionTypes() *messaging.SubscriptionsService
- func (c *Client) Tags() *tags.Service
- func (c *Client) Teams() *admins.TeamsService
- func (c *Client) TicketStates() *tickets.StatesService
- func (c *Client) TicketTypes() *tickets.TypesService
- func (c *Client) Tickets() *tickets.Service
- func (c *Client) Visitors() *contacts.VisitorsService
- func (c *Client) Workflows() *workflows.Service
- type ClientOption
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client manages communication with the Intercom API.
func NewClient ¶
func NewClient(token string, opts ...ClientOption) *Client
NewClient creates a new Intercom API client. It panics if token is empty or contains only whitespace.
func (*Client) AIContent ¶
func (c *Client) AIContent() *aiPkg.ContentService
AIContent returns the AI content service.
func (*Client) AwayStatusReasons ¶
func (c *Client) AwayStatusReasons() *admins.AwayStatusReasonsService
AwayStatusReasons returns the away status reasons service.
func (*Client) Brands ¶
func (c *Client) Brands() *settings.BrandsService
Brands returns the brands service.
func (*Client) Conversations ¶
func (c *Client) Conversations() *conversations.Service
Conversations returns the conversations service.
func (*Client) CustomChannelEvents ¶
func (c *Client) CustomChannelEvents() *settings.ChannelEventsService
CustomChannelEvents returns the custom channel events service.
func (*Client) CustomObjects ¶
func (c *Client) CustomObjects() *data.ObjectsService
CustomObjects returns the custom objects service.
func (*Client) DataAttributes ¶
func (c *Client) DataAttributes() *data.AttributesService
DataAttributes returns the data attributes service.
func (*Client) DataEvents ¶
func (c *Client) DataEvents() *data.EventsService
DataEvents returns the data events service.
func (*Client) DataExport ¶
func (c *Client) DataExport() *export.DataService
DataExport returns the data export service.
func (*Client) Do ¶
Do sends an API request and returns the API response. The JSON response body is decoded into v if v is non-nil. API errors (4xx/5xx) are returned as *ErrorResponse errors suitable for inspection with status predicates (IsNotFound, IsBadRequest, etc.).
func (*Client) DoDownload ¶
DoDownload executes an HTTP request and streams the response body to w. It is intended for binary downloads (e.g., CSV/gzip exports). On 4xx/5xx responses, it reads the error body and returns an *ErrorResponse.
func (*Client) DoRaw ¶
DoRaw executes an HTTP request and returns a Result with raw HTTP metadata and body. API errors (4xx/5xx) populate Result.Error instead of returning a Go error; only transport/IO failures return a Go error.
func (*Client) DoRawNoRedirect ¶
DoRawNoRedirect executes an HTTP request like DoRaw, but does not follow HTTP redirects. This is used when the API returns a redirect (e.g., 302) and the caller needs the Location header rather than the redirect target.
func (*Client) Emails ¶
func (c *Client) Emails() *messaging.EmailsService
Emails returns the emails service.
func (*Client) ExportReporting ¶
func (c *Client) ExportReporting() *export.ReportingService
ExportReporting returns the export reporting service.
func (*Client) FinVoice ¶
func (c *Client) FinVoice() *aiPkg.VoiceService
FinVoice returns the Fin Voice service.
func (*Client) HelpCenter ¶
func (c *Client) HelpCenter() *helpcenter.Service
HelpCenter returns the help center service.
func (*Client) IPAllowlist ¶
func (c *Client) IPAllowlist() *settings.IPAllowlistService
IPAllowlist returns the IP allowlist service.
func (*Client) InternalArticles ¶
func (c *Client) InternalArticles() *articles.InternalService
InternalArticles returns the internal articles service.
func (*Client) Messages ¶
func (c *Client) Messages() *messaging.MessagesService
Messages returns the messages service.
func (*Client) NewRequest ¶
NewRequest creates an API request. A relative URL path can be provided in urlStr, in which case it is resolved relative to the BaseURL of the Client. If body is non-nil, it is JSON-encoded and included as the request body.
func (*Client) Notes ¶
func (c *Client) Notes() *settings.NotesService
Notes returns the notes service.
func (*Client) PhoneCallRedirects ¶
func (c *Client) PhoneCallRedirects() *calls.RedirectsService
PhoneCallRedirects returns the phone call redirects service.
func (*Client) SubscriptionTypes ¶
func (c *Client) SubscriptionTypes() *messaging.SubscriptionsService
SubscriptionTypes returns the subscription types service.
func (*Client) Teams ¶
func (c *Client) Teams() *admins.TeamsService
Teams returns the teams service.
func (*Client) TicketStates ¶
func (c *Client) TicketStates() *tickets.StatesService
TicketStates returns the ticket states service.
func (*Client) TicketTypes ¶
func (c *Client) TicketTypes() *tickets.TypesService
TicketTypes returns the ticket types service.
func (*Client) Visitors ¶
func (c *Client) Visitors() *contacts.VisitorsService
Visitors returns the visitors service.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption configures the Client.
func WithBaseURL ¶
func WithBaseURL(u string) ClientOption
WithBaseURL sets a custom base URL for API requests.
func WithHTTPClient ¶
func WithHTTPClient(hc *http.Client) ClientOption
WithHTTPClient sets a custom HTTP client for API requests. It panics if hc is nil.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package admins provides services for managing Intercom admins and teams.
|
Package admins provides services for managing Intercom admins and teams. |
|
Package ai provides services for Intercom AI features.
|
Package ai provides services for Intercom AI features. |
|
Package api provides the core types and interfaces shared across all sub-packages in the Intercom Go SDK.
|
Package api provides the core types and interfaces shared across all sub-packages in the Intercom Go SDK. |
|
Package articles provides services for managing Intercom help center articles.
|
Package articles provides services for managing Intercom help center articles. |
|
Package calls provides services for Intercom phone calls.
|
Package calls provides services for Intercom phone calls. |
|
Package companies provides a service for managing Intercom companies.
|
Package companies provides a service for managing Intercom companies. |
|
Package contacts provides services for managing Intercom contacts and visitors.
|
Package contacts provides services for managing Intercom contacts and visitors. |
|
Package conversations provides a service for managing Intercom conversations.
|
Package conversations provides a service for managing Intercom conversations. |
|
Package data provides services for Intercom custom data.
|
Package data provides services for Intercom custom data. |
|
Package export provides services for Intercom data exports.
|
Package export provides services for Intercom data exports. |
|
Package helpcenter provides a service for managing Intercom Help Centers and their collections.
|
Package helpcenter provides a service for managing Intercom Help Centers and their collections. |
|
Package messaging provides services for Intercom messaging and email.
|
Package messaging provides services for Intercom messaging and email. |
|
Package news provides a service for managing Intercom news items and newsfeeds.
|
Package news provides a service for managing Intercom news items and newsfeeds. |
|
Package segments provides a service for managing Intercom segments.
|
Package segments provides a service for managing Intercom segments. |
|
Package settings provides services for Intercom workspace configuration.
|
Package settings provides services for Intercom workspace configuration. |
|
Package tags provides a service for managing Intercom tags.
|
Package tags provides a service for managing Intercom tags. |
|
Package tickets provides services for managing Intercom tickets.
|
Package tickets provides services for managing Intercom tickets. |
|
Package workflows provides a service for managing Intercom workflows.
|
Package workflows provides a service for managing Intercom workflows. |