Documentation
¶
Overview ¶
Package newsdataapi is the official Go client for the Newsdata.io REST API.
It wraps every endpoint (latest, archive, sources, crypto, market, count, crypto/count, market/count) with client-side parameter validation, retries with exponential backoff, scroll/paginate helpers, and a typed error hierarchy.
Quickstart:
client, err := newsdataapi.NewClient("YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
resp, err := client.Latest(context.Background(), newsdataapi.LatestParams{
Q: "bitcoin",
Country: []string{"us", "gb"},
Language: []string{"en"},
})
if err != nil {
log.Fatal(err)
}
articles, _ := resp.Articles()
for _, a := range articles {
fmt.Println(a.Title, "-", a.Link)
}
All methods accept a context.Context for cancellation and deadlines. Errors are typed (NewsdataValidationError, NewsdataAuthError, NewsdataRateLimitError, NewsdataServerError, NewsdataAPIError, NewsdataNetworkError) and can be inspected with errors.As.
Index ¶
- Constants
- Variables
- type Article
- type Client
- func (c *Client) Archive(ctx context.Context, params Params) (*Response, error)
- func (c *Client) Count(ctx context.Context, params Params) (*Response, error)
- func (c *Client) Crypto(ctx context.Context, params Params) (*Response, error)
- func (c *Client) CryptoCount(ctx context.Context, params Params) (*Response, error)
- func (c *Client) Latest(ctx context.Context, params Params) (*Response, error)
- func (c *Client) Market(ctx context.Context, params Params) (*Response, error)
- func (c *Client) MarketCount(ctx context.Context, params Params) (*Response, error)
- func (c *Client) Paginate(ctx context.Context, endpoint string, params Params, ...) error
- func (c *Client) ScrollAll(ctx context.Context, endpoint string, params Params, maxResults int) (*Response, error)
- func (c *Client) Sources(ctx context.Context, params Params) (*Response, error)
- type Logger
- type NewsdataAPIError
- type NewsdataAuthError
- type NewsdataError
- type NewsdataNetworkError
- type NewsdataRateLimitError
- type NewsdataServerError
- type NewsdataValidationError
- type Option
- func WithBaseURL(u string) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithIncludeHeaders(b bool) Option
- func WithLogger(l Logger) Option
- func WithMaxRetries(n int) Option
- func WithPaginationDelay(d time.Duration) Option
- func WithRetryBackoff(d time.Duration) Option
- func WithRetryBackoffMax(d time.Duration) Option
- func WithTimeout(d time.Duration) Option
- type Params
- type Response
Constants ¶
const ( EndpointLatest = "latest" EndpointArchive = "archive" EndpointCrypto = "crypto" EndpointSources = "sources" EndpointMarket = "market" EndpointCount = "count" EndpointCryptoCount = "crypto_count" EndpointMarketCount = "market_count" )
Endpoint name constants. These are also the strings ScrollAll and Paginate accept for their `endpoint` argument.
Variables ¶
var ( ErrValidation = errors.New("newsdataapi: validation error") ErrAPI = errors.New("newsdataapi: API error") ErrNetwork = errors.New("newsdataapi: network error") )
Sentinel for callers that want a single error.Is check.
Functions ¶
This section is empty.
Types ¶
type Article ¶
type Article struct {
ArticleID string `json:"article_id"`
Title string `json:"title"`
Link string `json:"link"`
Description string `json:"description,omitempty"`
Content string `json:"content,omitempty"`
Keywords []string `json:"keywords,omitempty"`
Creator []string `json:"creator,omitempty"`
VideoURL string `json:"video_url,omitempty"`
ImageURL string `json:"image_url,omitempty"`
PubDate string `json:"pubDate,omitempty"`
PubDateTZ string `json:"pubDateTZ,omitempty"`
SourceID string `json:"source_id,omitempty"`
SourcePriority int `json:"source_priority,omitempty"`
SourceURL string `json:"source_url,omitempty"`
SourceIcon string `json:"source_icon,omitempty"`
SourceName string `json:"source_name,omitempty"`
Language string `json:"language,omitempty"`
Country []string `json:"country,omitempty"`
Category []string `json:"category,omitempty"`
AITag []string `json:"ai_tag,omitempty"`
AIRegion []string `json:"ai_region,omitempty"`
AIOrg []string `json:"ai_org,omitempty"`
Sentiment string `json:"sentiment,omitempty"`
SentimentStats map[string]any `json:"sentiment_stats,omitempty"`
DataType string `json:"datatype,omitempty"`
}
Article is the typed shape of a single news result from the API. Fields use snake_case JSON tags to match the API; AI-enriched fields (ai_*) are set on articles where the platform produced them and are otherwise empty.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the HTTP client for the Newsdata.io API. Construct with NewClient and call the per-endpoint methods (Latest, Archive, ...) — those return a *Response and any client-side validation error or API-mapped error.
Client is safe for concurrent use by multiple goroutines.
func NewClient ¶
NewClient constructs a Client. apiKey is required; opts override the defaults listed in each WithXxx helper.
func (*Client) Count ¶
Count fetches aggregate news counts for a date range. GET /1/count. Requires "from_date" and "to_date" in params.
func (*Client) CryptoCount ¶
CryptoCount fetches aggregate crypto counts. GET /1/crypto/count. Requires "from_date" and "to_date" in params.
func (*Client) MarketCount ¶
MarketCount fetches aggregate market counts. GET /1/market/count. Requires "from_date" and "to_date" in params.
func (*Client) Paginate ¶
func (c *Client) Paginate( ctx context.Context, endpoint string, params Params, yield func(*Response, error) bool, ) error
Paginate calls the endpoint once per page, invoking yield on each. Return false from yield to stop early; the function returns the error yield was called with (if any) or nil on clean completion.
endpoint must be one of the Endpoint* constants. Sources is not supported.
func (*Client) ScrollAll ¶
func (c *Client) ScrollAll(ctx context.Context, endpoint string, params Params, maxResults int) (*Response, error)
ScrollAll follows nextPage cursors and returns one merged Response, capped at maxResults articles (0 = no cap, follow until exhaustion).
For news endpoints, Results is the concatenation of every page's results. For count endpoints (where the final page returns an aggregate object), the aggregate is placed in the returned Response as Results and the article arrays are concatenated separately (see Articles() / Aggregate()).
endpoint must be one of the Endpoint* constants. Sources is not supported.
type Logger ¶
Logger is the minimal interface the client uses for diagnostic logs. It is compatible with anything that has Info / Warn methods (slog.Logger does, and any custom logger can be adapted with a thin wrapper).
type NewsdataAPIError ¶
NewsdataAPIError indicates the API returned a structured error response.
func (*NewsdataAPIError) Error ¶
func (e *NewsdataAPIError) Error() string
func (*NewsdataAPIError) Is ¶
func (e *NewsdataAPIError) Is(target error) bool
type NewsdataAuthError ¶
type NewsdataAuthError struct{ *NewsdataAPIError }
NewsdataAuthError is raised on 401 / 403 responses.
func (*NewsdataAuthError) Error ¶
func (e *NewsdataAuthError) Error() string
func (*NewsdataAuthError) Unwrap ¶
func (e *NewsdataAuthError) Unwrap() error
Unwrap allows `errors.As` to also match NewsdataAPIError on this type.
type NewsdataError ¶
type NewsdataError struct {
Op string // optional: the API operation, e.g. "latest"
Msg string
Err error
}
NewsdataError is the base type wrapping every SDK-originated error.
func (*NewsdataError) Error ¶
func (e *NewsdataError) Error() string
func (*NewsdataError) Unwrap ¶
func (e *NewsdataError) Unwrap() error
type NewsdataNetworkError ¶
type NewsdataNetworkError struct {
Err error
}
NewsdataNetworkError indicates a transport-level failure (DNS, TLS, timeout, context cancellation) prevented the request from completing.
func (*NewsdataNetworkError) Error ¶
func (e *NewsdataNetworkError) Error() string
func (*NewsdataNetworkError) Is ¶
func (e *NewsdataNetworkError) Is(target error) bool
func (*NewsdataNetworkError) Unwrap ¶
func (e *NewsdataNetworkError) Unwrap() error
type NewsdataRateLimitError ¶
type NewsdataRateLimitError struct {
*NewsdataAPIError
RetryAfter int // seconds, when the Retry-After header was parseable; 0 otherwise
}
NewsdataRateLimitError is raised on 429 responses once retries are exhausted.
func (*NewsdataRateLimitError) Error ¶
func (e *NewsdataRateLimitError) Error() string
func (*NewsdataRateLimitError) Unwrap ¶
func (e *NewsdataRateLimitError) Unwrap() error
type NewsdataServerError ¶
type NewsdataServerError struct{ *NewsdataAPIError }
NewsdataServerError is raised on 5xx responses once retries are exhausted.
func (*NewsdataServerError) Error ¶
func (e *NewsdataServerError) Error() string
func (*NewsdataServerError) Unwrap ¶
func (e *NewsdataServerError) Unwrap() error
type NewsdataValidationError ¶
type NewsdataValidationError struct {
Param string // The offending parameter name, when known.
Message string
}
NewsdataValidationError indicates a parameter failed client-side validation. No request was sent.
func (*NewsdataValidationError) Error ¶
func (e *NewsdataValidationError) Error() string
func (*NewsdataValidationError) Is ¶
func (e *NewsdataValidationError) Is(target error) bool
Is hooks so callers can use errors.Is(err, ErrValidation) etc.
type Option ¶
Option configures a Client at construction time.
func WithBaseURL ¶
WithBaseURL overrides the API base URL (useful for staging / a proxy). The trailing slash is added if missing.
func WithHTTPClient ¶
WithHTTPClient injects a custom *http.Client (e.g. with a custom Transport for proxies, mTLS, instrumentation). Note: setting this overrides the WithTimeout value — set the timeout on your own client instead.
func WithIncludeHeaders ¶
WithIncludeHeaders, when true, attaches the response headers on each returned Response (as Response.ResponseHeaders). Default: false.
func WithLogger ¶
WithLogger attaches a logger that receives diagnostic messages (one line per request attempt, retry, and backoff). The API key is always redacted from logged URLs.
func WithMaxRetries ¶
WithMaxRetries sets the total number of request attempts (1 = no retry). Retries cover network errors, HTTP 429, and 5xx responses. Auth and other 4xx errors are never retried. Default: 5.
func WithPaginationDelay ¶
WithPaginationDelay sets the delay between page requests when using ScrollAll or Paginate. Default: 1s.
func WithRetryBackoff ¶
WithRetryBackoff sets the base for exponential backoff between retries. Default: 2s. Successive attempts wait 2s, 4s, 8s, 16s, 32s (capped by WithRetryBackoffMax).
func WithRetryBackoffMax ¶
WithRetryBackoffMax caps the longest single backoff sleep. Default: 60s.
func WithTimeout ¶
WithTimeout sets a per-request timeout. Applied via http.Client.Timeout, so it covers the full request (connect + body). Default: 30s.
type Params ¶
Params is the request payload for any endpoint method. Keys are case- insensitive (the API normalises to lowercase, and so do we) and values may be a string, a []string (comma-joined), a bool, an int, a float, or *bool / *float64 if you need to distinguish "unset" from a zero value.
A few keys are interpreted specially and never sent to the API:
"rawQuery" (string) — sent verbatim; mutually exclusive with all other
params; parsed and validated against the
endpoint's allowed keys.
See the README for the per-endpoint accepted parameter list.
type Response ¶
type Response struct {
Status string `json:"status,omitempty"`
TotalResults int `json:"totalResults,omitempty"`
Results json.RawMessage `json:"results,omitempty"`
NextPage string `json:"nextPage,omitempty"`
ResponseHeaders http.Header `json:"-"`
}
Response is the top-level JSON envelope returned by every endpoint.
`Results` is held as raw JSON because its type varies by endpoint:
- news endpoints (latest, archive, crypto, market) return an array of articles;
- the count endpoints return an aggregate object on the final page.
Use the Articles() / Aggregate() helpers to decode it into a typed shape.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
error_handling
command
Typed error handling with errors.As — same pattern as the Python / Node clients but using Go's idiomatic error chain.
|
Typed error handling with errors.As — same pattern as the Python / Node clients but using Go's idiomatic error chain. |
|
latest
command
A minimal example: fetch the latest news with a few filters.
|
A minimal example: fetch the latest news with a few filters. |
|
paginate
command
Two flavours of pagination:
|
Two flavours of pagination: |