Documentation
¶
Overview ¶
Package api provides the core types and interfaces shared across all sub-packages in the Intercom Go SDK.
Key types include the Caller interface (implemented by intercom.Client), Result for raw HTTP responses, Iter and PagedResult for pagination, Filter and SearchRequest for search queries, ErrorResponse and status predicates for error handling, and shared domain types like TagRef, AdminRef, and ContactRef used across multiple services.
Index ¶
- func AddQueryOptions(path string, opts any) (string, error)
- func Decode[T any](r *Result) (*T, error)
- func IsBadRequest(err error) bool
- func IsConflict(err error) bool
- func IsForbidden(err error) bool
- func IsNotFound(err error) bool
- func IsRateLimited(err error) bool
- func IsServerError(err error) bool
- func IsUnauthorized(err error) bool
- func IsUnprocessableEntity(err error) bool
- func ResultError(r *Result) error
- type AdminRef
- type ArticleContent
- type ArticleTranslatedContent
- type Author
- type Caller
- type ContactRef
- type ContactRefList
- type CursorPages
- type Deleted
- type Empty
- type ErrorCode
- type ErrorDetail
- type ErrorResponse
- type ErrorResult
- type Filter
- type Iter
- type LinkedObject
- type LinkedObjectList
- type ListOptions
- type Logger
- type Note
- type NoteAuthor
- type NoteListResult
- type Operator
- type PageFetcher
- type PagedResult
- type Part
- type RateLimitInfo
- type Response
- type Result
- type ScrollOptions
- type SearchPagination
- type SearchRequest
- type SegmentListResult
- type SegmentRef
- type StartingAfterPage
- type SubscriptionType
- type Tag
- type TagList
- type TagRef
- type TagRefList
- type Translation
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddQueryOptions ¶
AddQueryOptions encodes struct fields tagged with `url:"name,omitempty"` as query parameters and appends them to the given path.
func Decode ¶
Decode unmarshals the JSON body of a Result into a value of type T. For 2xx responses with an empty body, it returns a pointer to a zero-value T. For non-2xx responses with an empty body, it returns an error.
Example ¶
package main
import (
"fmt"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
// Simulate a successful API response with a JSON body.
result := &api.Result{
StatusCode: 200,
Body: []byte(`{"id":"42","name":"Alice"}`),
}
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
user, err := api.Decode[User](result)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("ID=%s Name=%s\n", user.ID, user.Name)
}
Output: ID=42 Name=Alice
Example (EmptyBody) ¶
package main
import (
"fmt"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
// A 204 No Content response with no body returns a zero-value struct.
result := &api.Result{
StatusCode: 204,
Body: nil,
}
type Resp struct{ OK bool }
resp, err := api.Decode[Resp](result)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("OK=%v\n", resp.OK)
}
Output: OK=false
func IsBadRequest ¶
IsBadRequest returns true if the error is an Intercom 400 response.
func IsConflict ¶
IsConflict returns true if the error is an Intercom 409 response.
func IsForbidden ¶
IsForbidden returns true if the error is an Intercom 403 response.
func IsNotFound ¶
IsNotFound returns true if the error is an Intercom 404 response.
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
// Construct an ErrorResponse that represents a 404.
err := &api.ErrorResponse{
StatusCode: http.StatusNotFound,
Errors: []api.ErrorDetail{
{Code: "not_found", Message: "Contact not found"},
},
}
fmt.Println(api.IsNotFound(err))
fmt.Println(api.IsRateLimited(err))
}
Output: true false
func IsRateLimited ¶
IsRateLimited returns true if the error is an Intercom 429 response.
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
err := &api.ErrorResponse{
StatusCode: http.StatusTooManyRequests,
Errors: []api.ErrorDetail{
{Code: api.ErrRateLimitExceeded, Message: "Rate limit exceeded"},
},
}
fmt.Println(api.IsRateLimited(err))
}
Output: true
func IsServerError ¶
IsServerError returns true if the error is an Intercom 5xx response.
func IsUnauthorized ¶
IsUnauthorized returns true if the error is an Intercom 401 response.
func IsUnprocessableEntity ¶
IsUnprocessableEntity returns true if the error is an Intercom 422 response.
func ResultError ¶
ResultError converts Result.Error into an *ErrorResponse suitable for inspection with status predicates (IsNotFound, IsBadRequest, etc.).
Types ¶
type AdminRef ¶
type AdminRef struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
}
AdminRef represents an admin in sub-resource responses. Used by: tags, conversations, admins.
type ArticleContent ¶
type ArticleContent struct {
Type string `json:"type,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Body string `json:"body,omitempty"`
AuthorID int `json:"author_id,omitempty"`
State string `json:"state,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
UpdatedAt int64 `json:"updated_at,omitempty"`
URL string `json:"url,omitempty"`
}
ArticleContent represents translated content for a single locale. Used by: articles, helpcenter.
type ArticleTranslatedContent ¶
type ArticleTranslatedContent struct {
Type string `json:"type,omitempty"`
AR *ArticleContent `json:"ar,omitempty"`
BG *ArticleContent `json:"bg,omitempty"`
BS *ArticleContent `json:"bs,omitempty"`
CA *ArticleContent `json:"ca,omitempty"`
CS *ArticleContent `json:"cs,omitempty"`
DA *ArticleContent `json:"da,omitempty"`
DE *ArticleContent `json:"de,omitempty"`
EL *ArticleContent `json:"el,omitempty"`
EN *ArticleContent `json:"en,omitempty"`
ES *ArticleContent `json:"es,omitempty"`
ET *ArticleContent `json:"et,omitempty"`
FI *ArticleContent `json:"fi,omitempty"`
FR *ArticleContent `json:"fr,omitempty"`
HE *ArticleContent `json:"he,omitempty"`
HR *ArticleContent `json:"hr,omitempty"`
HU *ArticleContent `json:"hu,omitempty"`
ID *ArticleContent `json:"id,omitempty"`
IT *ArticleContent `json:"it,omitempty"`
JA *ArticleContent `json:"ja,omitempty"`
KO *ArticleContent `json:"ko,omitempty"`
LT *ArticleContent `json:"lt,omitempty"`
LV *ArticleContent `json:"lv,omitempty"`
MN *ArticleContent `json:"mn,omitempty"`
NB *ArticleContent `json:"nb,omitempty"`
NL *ArticleContent `json:"nl,omitempty"`
PL *ArticleContent `json:"pl,omitempty"`
PT *ArticleContent `json:"pt,omitempty"`
PtBR *ArticleContent `json:"pt-BR,omitempty"`
RO *ArticleContent `json:"ro,omitempty"`
RU *ArticleContent `json:"ru,omitempty"`
SL *ArticleContent `json:"sl,omitempty"`
SR *ArticleContent `json:"sr,omitempty"`
SV *ArticleContent `json:"sv,omitempty"`
TR *ArticleContent `json:"tr,omitempty"`
VI *ArticleContent `json:"vi,omitempty"`
ZhCN *ArticleContent `json:"zh-CN,omitempty"`
ZhTW *ArticleContent `json:"zh-TW,omitempty"`
}
ArticleTranslatedContent holds translations for an article keyed by locale. Used by: articles, helpcenter.
type Author ¶
type Author struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
}
Author represents the author of a conversation part, ticket part, or source. Used by: conversations, tickets (via Part).
type Caller ¶
type Caller interface {
NewRequest(method, urlStr string, body any) (*http.Request, error)
DoRaw(ctx context.Context, req *http.Request) (*Result, error)
DoRawNoRedirect(ctx context.Context, req *http.Request) (*Result, error)
Do(ctx context.Context, req *http.Request, v any) (*Response, error)
DoDownload(ctx context.Context, req *http.Request, w io.Writer) error
}
Caller abstracts the HTTP operations needed by sub-package services. The root intercom.Client implements this interface.
type ContactRef ¶
type ContactRef struct {
Type string `json:"type"`
ID string `json:"id"`
ExternalID string `json:"external_id,omitempty"`
}
ContactRef is a lightweight reference to a contact. Used by: notes, contacts, companies, conversations, tickets.
type ContactRefList ¶
type ContactRefList struct {
Type string `json:"type"`
Contacts []ContactRef `json:"contacts"`
}
ContactRefList holds the contacts participating in a conversation or ticket. Used by: conversations, tickets.
type CursorPages ¶
type CursorPages struct {
Type string `json:"type"`
Page int `json:"page"`
PerPage int `json:"per_page"`
TotalPages int `json:"total_pages"`
Next *StartingAfterPage `json:"next,omitempty"`
}
CursorPages represents the pagination metadata in list responses.
type Deleted ¶
type Deleted struct {
ID string `json:"id"`
Object string `json:"object"`
Deleted bool `json:"deleted"`
}
Deleted represents the response from deleting a resource. Used by: tickets, articles, conversations, companies. Note: contacts.Deleted has a different structure (Type + ExternalID instead of Object).
type Empty ¶
type Empty struct{}
Empty is used as the type parameter for Decode when the API returns no body.
type ErrorCode ¶
type ErrorCode string
ErrorCode represents an Intercom API error code.
const ( ErrServerError ErrorCode = "server_error" ErrClientError ErrorCode = "client_error" ErrTypeMismatch ErrorCode = "type_mismatch" ErrParameterNotFound ErrorCode = "parameter_not_found" ErrParameterInvalid ErrorCode = "parameter_invalid" ErrActionForbidden ErrorCode = "action_forbidden" ErrConflict ErrorCode = "conflict" ErrAPIPlanRestricted ErrorCode = "api_plan_restricted" ErrRateLimitExceeded ErrorCode = "rate_limit_exceeded" ErrUnsupported ErrorCode = "unsupported" ErrTokenRevoked ErrorCode = "token_revoked" ErrTokenBlocked ErrorCode = "token_blocked" ErrTokenNotFound ErrorCode = "token_not_found" ErrTokenExpired ErrorCode = "token_expired" ErrMissingAuth ErrorCode = "missing_authorization" ErrRetryAfter ErrorCode = "retry_after" ErrJobClosed ErrorCode = "job_closed" ErrNotRestorable ErrorCode = "not_restorable" ErrTeamNotFound ErrorCode = "team_not_found" ErrAdminNotFound ErrorCode = "admin_not_found" )
type ErrorDetail ¶
ErrorDetail represents a single error within an API error response.
type ErrorResponse ¶
type ErrorResponse struct {
StatusCode int `json:"-"`
Headers http.Header `json:"-"`
Type string `json:"type"`
RequestID string `json:"request_id,omitempty"`
Errors []ErrorDetail `json:"errors"`
RawBody string `json:"-"`
RateLimit *RateLimitInfo `json:"-"`
}
ErrorResponse represents an error response from the Intercom API.
func (*ErrorResponse) Error ¶
func (e *ErrorResponse) Error() string
Error returns a human-readable description of the API error.
func (*ErrorResponse) HasErrorCode ¶
func (e *ErrorResponse) HasErrorCode(code ErrorCode) bool
HasErrorCode reports whether any error in the Errors slice matches the given code.
type ErrorResult ¶
type ErrorResult struct {
Type string `json:"type"`
RequestID string `json:"request_id,omitempty"`
Code ErrorCode `json:"-"`
Message string `json:"-"`
Errors []ErrorDetail `json:"errors"`
}
ErrorResult represents a typed API error response.
func (*ErrorResult) Error ¶
func (e *ErrorResult) Error() string
Error returns a human-readable description of the API error.
type Filter ¶
type Filter struct {
Field string `json:"field,omitempty"`
Operator Operator `json:"operator"`
Value any `json:"value"`
}
Filter represents either a single field filter or a compound (AND/OR) filter. Use SingleFilterOf, And, and Or to construct filters.
Value holds a scalar (string, int) for single field filters, a slice for IN/NIN operators, or []*Filter for compound (AND/OR) filters. Callers should use the constructor functions rather than setting Value directly.
func And ¶
And creates a compound filter that requires all sub-filters to match.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
// Combine two filters with AND — both must match.
f := api.And(
api.SingleFilterOf("role", api.OpEquals, "user"),
api.SingleFilterOf("name", api.OpStarts, "A"),
)
data, _ := json.Marshal(f)
fmt.Println(string(data))
}
Output: {"operator":"AND","value":[{"field":"role","operator":"=","value":"user"},{"field":"name","operator":"^","value":"A"}]}
func Or ¶
Or creates a compound filter that requires any sub-filter to match.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
// Combine two filters with OR — either can match.
f := api.Or(
api.SingleFilterOf("email", api.OpContains, "@acme.com"),
api.SingleFilterOf("email", api.OpContains, "@example.com"),
)
data, _ := json.Marshal(f)
fmt.Println(string(data))
}
Output: {"operator":"OR","value":[{"field":"email","operator":"~","value":"@acme.com"},{"field":"email","operator":"~","value":"@example.com"}]}
func SingleFilterOf ¶
SingleFilterOf creates a filter that matches a single field. The value can be a string, int, or slice for IN/NIN operators.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
// Build a filter that matches contacts with role "user".
f := api.SingleFilterOf("role", api.OpEquals, "user")
data, _ := json.Marshal(f)
fmt.Println(string(data))
}
Output: {"field":"role","operator":"=","value":"user"}
type Iter ¶
type Iter[T any] struct { // contains filtered or unexported fields }
Iter provides lazy iteration over paginated results. It is not safe for concurrent use.
func NewIter ¶
func NewIter[T any](ctx context.Context, opts *ListOptions, fetcher PageFetcher[T]) *Iter[T]
NewIter creates a new paginated iterator. The fetcher function is called to retrieve each page of results as needed.
Example ¶
package main
import (
"context"
"fmt"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
// Create a mock page fetcher that returns two pages.
fetcher := func(_ context.Context, opts *api.ListOptions) (*api.PagedResult[string], error) {
switch opts.StartingAfter {
case "":
return &api.PagedResult[string]{
Data: []string{"a", "b"},
Pages: api.CursorPages{
Next: &api.StartingAfterPage{StartingAfter: "cursor-2"},
},
}, nil
case "cursor-2":
return &api.PagedResult[string]{
Data: []string{"c"},
Pages: api.CursorPages{},
}, nil
default:
return nil, fmt.Errorf("unexpected cursor")
}
}
iter := api.NewIter(context.Background(), nil, fetcher)
// Idiomatic iteration: Next/Current/Err loop.
for iter.Next() {
fmt.Println(iter.Current())
}
if err := iter.Err(); err != nil {
fmt.Println("error:", err)
}
}
Output: a b c
func (*Iter[T]) Collect ¶
Collect drains the iterator and returns all items as a slice. If an error occurs mid-pagination, Collect returns the items collected so far along with the error. For zero results it returns a non-nil empty slice.
Example ¶
package main
import (
"context"
"fmt"
"github.com/rassakhatsky/intercom-go-sdk/api"
)
func main() {
fetcher := func(_ context.Context, opts *api.ListOptions) (*api.PagedResult[string], error) {
if opts.StartingAfter == "" {
return &api.PagedResult[string]{
Data: []string{"x", "y", "z"},
Pages: api.CursorPages{},
}, nil
}
return nil, fmt.Errorf("unexpected cursor")
}
iter := api.NewIter(context.Background(), nil, fetcher)
items, err := iter.Collect()
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(items)
}
Output: [x y z]
func (*Iter[T]) Current ¶
func (it *Iter[T]) Current() T
Current returns the most recent item yielded by Next().
func (*Iter[T]) ForEach ¶
ForEach calls fn for each item yielded by the iterator. If fn returns a non-nil error, iteration stops and that error is returned. If a page fetch fails, the fetch error is returned. Callers can distinguish the two by checking iter.Err() after ForEach returns: it is non-nil only for fetch errors.
func (*Iter[T]) Next ¶
Next advances the iterator to the next item. It returns false when there are no more items or an error occurs. Use Current() to get the item and Err() to check for errors.
func (*Iter[T]) PageResponse ¶
func (it *Iter[T]) PageResponse() *PagedResult[T]
PageResponse returns the raw paged result for the current page.
type LinkedObject ¶
type LinkedObject struct {
Type string `json:"type"`
ID string `json:"id"`
Category string `json:"category,omitempty"`
}
LinkedObject represents a single linked object (ticket, conversation, etc.) within a LinkedObjectList. Used by: conversations, tickets.
type LinkedObjectList ¶
type LinkedObjectList struct {
Type string `json:"type"`
Data []LinkedObject `json:"data"`
TotalCount int `json:"total_count"`
HasMore bool `json:"has_more"`
}
LinkedObjectList holds linked objects on a conversation or ticket. Used by: conversations, tickets.
type ListOptions ¶
type ListOptions struct {
PerPage int `url:"per_page,omitempty"`
StartingAfter string `url:"starting_after,omitempty"`
}
ListOptions specifies cursor-based pagination parameters.
type Logger ¶
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Error(msg string, args ...any)
}
Logger defines the interface for SDK logging. `*log/slog.Logger` satisfies this interface.
type Note ¶
type Note struct {
Type string `json:"type"`
ID string `json:"id"`
CreatedAt int64 `json:"created_at,omitempty"`
Body string `json:"body,omitempty"`
Contact *ContactRef `json:"contact,omitempty"`
Author *NoteAuthor `json:"author,omitempty"`
}
Note represents an Intercom note. Used by: settings/notes, contacts, companies.
type NoteAuthor ¶
type NoteAuthor struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
}
NoteAuthor represents the admin who authored a note. Used by: settings/notes, contacts, companies.
type NoteListResult ¶
type NoteListResult struct {
Type string `json:"type"`
Data []Note `json:"data"`
TotalCount int `json:"total_count"`
Pages CursorPages `json:"pages"`
}
NoteListResult is the response for listing notes on a contact or company. Used by: contacts, companies.
type Operator ¶
type Operator string
Operator represents a filter operator for Intercom search queries.
const ( OpEquals Operator = "=" OpNotEquals Operator = "!=" OpGreaterThan Operator = ">" OpLessThan Operator = "<" OpContains Operator = "~" OpNotContains Operator = "!~" OpIn Operator = "IN" OpNotIn Operator = "NIN" OpStarts Operator = "^" OpEnds Operator = "$" )
Filter operators for single field filters.
type PageFetcher ¶
type PageFetcher[T any] func(ctx context.Context, opts *ListOptions) (*PagedResult[T], error)
PageFetcher is a function that fetches a single page of results.
type PagedResult ¶
type PagedResult[T any] struct { Type string `json:"type"` Data []T `json:"data"` TotalCount int `json:"total_count"` Pages CursorPages `json:"pages"` }
PagedResult is a generic response for paginated list endpoints.
type Part ¶
type Part struct {
Type string `json:"type"`
ID string `json:"id"`
PartType string `json:"part_type,omitempty"`
Body string `json:"body,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
UpdatedAt int64 `json:"updated_at,omitempty"`
NotifiedAt int64 `json:"notified_at,omitempty"`
AssignedTo *Author `json:"assigned_to,omitempty"`
Author *Author `json:"author,omitempty"`
ExternalID string `json:"external_id,omitempty"`
Redacted bool `json:"redacted,omitempty"`
}
Part represents a conversation part or ticket part. Superset of conversations and tickets Part types. Used by: conversations, tickets. Conversations use NotifiedAt; tickets do not.
type RateLimitInfo ¶
type RateLimitInfo struct {
Limit int // X-RateLimit-Limit: total requests allowed per window
Remaining int // X-RateLimit-Remaining: requests remaining in current window
Reset time.Time // X-RateLimit-Reset: when the rate limit window resets (Unix timestamp)
RetryAfter time.Duration // Retry-After: how long to wait before retrying
}
RateLimitInfo contains rate limit metadata parsed from HTTP response headers.
type Result ¶
type Result struct {
StatusCode int
Header http.Header
URL string
Body []byte
Error *ErrorResult // non-nil for 4xx/5xx
}
Result contains raw HTTP response metadata, body, and any API error.
type ScrollOptions ¶
type ScrollOptions struct {
ScrollParam string `url:"scroll_param,omitempty"`
}
ScrollOptions specifies scroll-based pagination parameters (used by Companies).
type SearchPagination ¶
type SearchPagination struct {
PerPage int `json:"per_page,omitempty"`
StartingAfter string `json:"starting_after,omitempty"`
}
SearchPagination controls pagination in search requests.
type SearchRequest ¶
type SearchRequest struct {
Query *Filter `json:"query"`
Pagination *SearchPagination `json:"pagination,omitempty"`
}
SearchRequest represents a request body for Intercom's search endpoints.
type SegmentListResult ¶
type SegmentListResult struct {
Type string `json:"type"`
Data []SegmentRef `json:"data"`
}
SegmentListResult is the response for listing segments for a contact or company. Used by: contacts, companies.
type SegmentRef ¶
type SegmentRef struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
UpdatedAt int64 `json:"updated_at,omitempty"`
PersonType string `json:"person_type,omitempty"`
}
SegmentRef represents a segment in sub-resource responses. Used by: contacts, companies.
type StartingAfterPage ¶
type StartingAfterPage struct {
PerPage int `json:"per_page,omitempty"`
StartingAfter string `json:"starting_after,omitempty"`
}
StartingAfterPage contains the cursor for the next page.
type SubscriptionType ¶
type SubscriptionType struct {
Type string `json:"type"`
ID string `json:"id"`
State string `json:"state,omitempty"`
ConsentType string `json:"consent_type,omitempty"`
DefaultTranslation *Translation `json:"default_translation,omitempty"`
Translations []Translation `json:"translations,omitempty"`
ContentTypes []string `json:"content_types,omitempty"`
}
SubscriptionType represents a subscription type in Intercom. Used by: messaging, contacts.
type Tag ¶
type Tag struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name"`
AppliedAt *int64 `json:"applied_at,omitempty"`
AppliedBy *AdminRef `json:"applied_by,omitempty"`
}
Tag represents an Intercom tag (full representation). Used by: tags, contacts.
type TagList ¶
TagList represents a list of tags (full Tag objects with json:"data"). Used by: tags, contacts.
type TagRef ¶
type TagRef struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name,omitempty"`
AppliedAt *int64 `json:"applied_at,omitempty"`
}
TagRef represents a tag in sub-resource responses. Used by: contacts, companies, conversations, tickets.
type TagRefList ¶
TagRefList represents a list of tag references embedded in a parent resource (json:"tags"). Used by: conversations, companies. Distinct from TagList which uses []Tag with json:"data".
type Translation ¶
type Translation struct {
Name string `json:"name"`
Description string `json:"description"`
Locale string `json:"locale"`
}
Translation represents a localised version of a subscription type. Used by: messaging, contacts.