SDK Reference
SDK Reference
This section provides a detailed reference for the AI News SDK, including available methods, parameters, and data formats. The SDK is currently focused on a single primary method for news retrieval, as well as configuration and error handling utilities.
AINews SDK Initialization
new AINews(options)
– Creates a new client instance for the AI News SDK.
apiKey
(string, required): Your ChainGPT API key. This is obtained from the ChainGPT AI Hub dashboard. The key is used to authenticate your requests to the AI News API.Example:
Once initialized, you use the ainews
instance to call the news-fetching methods described below.
ainews.getNews(parameters)
ainews.getNews(parameters)
Fetches AI-generated news articles, optionally filtered by various criteria. This method returns a Promise that resolves to a response object containing the news data.
Parameters: (All fields are optional, unless otherwise noted. If no filters are provided, it returns the latest general news.)
categoryId
: number or number[] – One or multiple Category IDs to filter by. Categories represent broad topics (e.g. DeFi, NFTs, Metaverse). See Category ID Table below for the list of category IDs. You can provide a single ID or an array of IDs. If provided, the results will include only news items whose category matches one of these IDs.subCategoryId
: number or number[] – One or multiple Sub-Category IDs to filter by. Sub-categories typically correspond to blockchain ecosystems or platforms (e.g. Bitcoin, Ethereum, Solana). Use this to get news related to specific blockchains. See the Sub-Category (Blockchain) ID Table below. As with categoryId, you can pass one ID or an array.tokenId
: number or number[] – One or multiple Token IDs to filter by. This filters news by specific cryptocurrency or token. For example, there are token IDs for BTC, ETH, BNB, etc. (See Token ID Table.) Use this to focus on news primarily about a particular coin/token.searchQuery
: string – A search keyword or phrase. When provided, the API will search within the title and description of news articles for matches. This is a full-text search that can be used to find news on a particular topic (e.g. “exchange hack” or “NFT marketplace”).fetchAfter
: Date or string (ISO 8601 date) – If set, only news items published after this date/time will be returned. This is useful for getting historical data or incrementally fetching new articles since the last check. For example,fetchAfter: new Date("2025-01-01")
will fetch news from 2025 onward. (If not provided, the API will return recent news by default.)limit
: number – The maximum number of news items to return. If not specified, a default limit (e.g. 10) is used by the API. You can use this to control page size when paginating.offset
: number – The number of items to skip from the start. Useoffset
in combination withlimit
for pagination. For instance, to get the second page of results with page size 10, uselimit: 10
andoffset: 10
.sortBy
: string – Field to sort the results by. The default (and currently primary) sort is by date/time. For example,sortBy: 'createdAt'
will sort by the article’s creation timestamp (most likely descending, i.e. newest first). If not specified, the news is sorted by newest first by default. Currently, other sort fields may not be commonly used, as real-time news is typically just sorted by recency.
Response: On success, the Promise resolves to an object typically structured as:
data.rows
is an array of news items. Each item contains fields like:id: Internal ID of the news entry.
title: The headline of the news article (AI-generated or taken from source).
description: The condensed summary of the article content (generated by the AI).
source: The source of the news (e.g., name of the original website or "ChainGPT AI" if aggregated).
sourceUrl: A link to the original source article (if available). This can be used if you want to redirect users to full story on the source site.
category/categoryId: The category name and ID the article was classified under (e.g. "DeFi" and 5).
subCategory/subCategoryId: The sub-category (blockchain ecosystem) and its ID (e.g. "Ethereum" and 15).
token/tokenId: If the article is primarily about a specific token/project, this field gives its name and ID (e.g. "Ethereum" and 80). Not all articles have a specific token focus, in which case this might be null.
createdAt: Timestamp when the AI published the news article (ISO date string).
updatedAt: Timestamp of last update (usually same as createdAt unless the article was updated).
count
: The number of items returned in this response.offset
: The offset that was applied (useful to verify pagination).limit
: The limit that was applied.
Example usage:
In example 4 above, categoryId: 2
corresponds to "Blockchain Gaming" category, and subCategoryId: 20
is "Polygon". This would return news articles that are tagged as blockchain gaming and related to the Polygon ecosystem (for instance, news about a game built on Polygon).
Error Handling: If the request fails (due to network issues, invalid parameters, or an authentication error), the getNews()
Promise will reject with an error. Specifically, the SDK will throw an error of type Errors.AINewsError
for API-related issues. You should catch these errors and inspect error.message
for details. (See Error Handling below.)
Category ID Reference
Below is the list of Category identifiers available for filtering. Categories represent high-level topics or sectors within crypto/Web3.
Category
ID
Blockchain Gaming
2
DAO (Decentralized Autonomous Orgs)
3
DApps (Decentralized Apps)
4
DeFi (Decentralized Finance)
5
Lending
6
Metaverse
7
NFT (Non-Fungible Tokens)
8
Stablecoins
9
Cryptocurrency (General)
64
Decentralized (General)
65
Smart Contracts
66
Distributed Ledger
67
Cryptography
68
Digital Assets
69
Tokenization
70
Consensus Mechanisms
71
ICO (Initial Coin Offering)
72
Crypto Wallets
73
Web3.0
74
Interoperability
75
Mining
76
Cross-Chain Transactions
77
Exchange
78
(ID 1 is reserved or not used in this context. Categories 2–9 cover specific segments, and 64+ cover broader conceptual topics.) Use these IDs in the categoryId
filter to get news belonging to those categories. For example, to filter for NFT news, use categoryId: [8]
.
Sub-Category (Blockchain) ID Reference
Sub-categories usually denote blockchain platforms or ecosystems. Use these IDs in the subCategoryId
filter to get news related to a specific blockchain or protocol ecosystem:
Bitcoin
11
BNB Chain
12
Celo
13
Cosmos
14
Ethereum
15
Fantom
16
Flow
17
Litecoin
18
Monero
19
Polygon
20
XRP Ledger
21
Solana
22
TRON
23
Terra
24
Tezos
25
WAX
26
Algorand
27
Arbitrum
28
Astar
29
Aurora
30
Avalanche
31
Base
32
Binance Smart Chain
33
Cardano
34
Cronos
36
Moonbeam
37
Harmony
41
Oasis Network
42
Oasis Sapphire (Oasis ParaChain)
43
Ontology
44
Optimism
45
Other (Misc. Blockchains)
46
PlatON
47
Rangers Protocol
49
Ronin
50
Shiden Network
51
SKALE
52
Stacks
54
Stargaze
55
Steem
56
SX Network
57
Telos
58
Telos EVM
59
Theta Network
61
ThunderCore
62
These cover most major Layer-1 and Layer-2 networks. The Other (46) category catches any chain news not explicitly listed. For example, to get only Ethereum ecosystem news, use subCategoryId: [15]
. For Bitcoin news, use subCategoryId: [11]
. If a news article is about multiple chains, it will typically be classified under the primary chain it concerns.
Token ID Reference
The following are Token identifiers for filtering by specific cryptocurrency or token project. Use these in the tokenId
filter to get news specifically about that token (usually price news, major project updates, etc.):
Bitcoin (BTC)
79
Ethereum (ETH)
80
Tether USD (USDT)
81
BNB (BNB)
82
XRP (XRP)
83
USD Coin (USDC)
84
Solana (SOL)
85
Cardano (ADA)
86
Dogecoin (DOGE)
87
TRON (TRX)
88
Toncoin (TON)
89
Dai (DAI)
90
Polygon (MATIC)
91
Polkadot (DOT)
92
Litecoin (LTC)
93
Wrapped Bitcoin (WBTC)
94
Bitcoin Cash (BCH)
95
Chainlink (LINK)
96
Shiba Inu (SHIB)
97
UNUS SED LEO (LEO)
98
TrueUSD (TUSD)
99
Avalanche (AVAX)
100
Stellar (XLM)
101
Monero (XMR)
102
OKB (OKB)
103
Cosmos (ATOM)
104
Uniswap (UNI)
105
Ethereum Classic (ETC)
106
BUSD (BUSD)
107
Hedera (HBAR)
108
For example, tokenId: [79]
will filter news about Bitcoin, and tokenId: [99]
would filter news about TrueUSD. You can combine multiple tokens in the array if you want news that is about either of those tokens.
Error Handling and Exceptions
All SDK methods that communicate with the API can throw exceptions if something goes wrong. The common error class for this SDK is Errors.AINewsError
. Here are some scenarios and how to handle them:
Invalid API Key / Unauthorized: If your API key is missing or incorrect, the request will fail with an authorization error. The SDK will throw an
AINewsError
in this case, with a message indicating an auth issue (e.g. “Invalid API key”).Insufficient Credits: If you run out of credits in your ChainGPT account, the API will refuse requests. This will also result in an
AINewsError
(the message might say something like “Insufficient credits” in the error).Rate Limit Exceeded: The API enforces rate limits. Users can make up to 200 requests per minute. If you exceed this, you may get a rate-limit error (HTTP 429). The SDK would throw an
AINewsError
in this case as well. If this happens, implement backoff/retry logic or slow down your request rate.Network or Server Errors (5xx): If the ChainGPT API is down or unreachable, or a server error occurs, the SDK will throw an
AINewsError
. The message will contain the HTTP status or a general description (like “Network request failed”).Invalid Parameters: If you supply an incorrectly formatted parameter (e.g. a string where a number is expected), the API might return a 400 Bad Request. This would also surface as an
AINewsError
from the SDK. Double-check types and allowed values if you see such errors.
Example of catching errors:
In the above snippet, we intentionally used an invalid tokenId (999). The API might respond with an error like “Invalid token ID”, which the SDK wraps in an AINewsError. We check the instance and handle it accordingly.
Always wrap your getNews
calls in try/catch (or .catch
on the Promise) especially in production, to ensure your application can gracefully handle outages or errors from the news service.
Request Limits and Performance
As mentioned, the API allows up to 200 requests per minute per API key. Exceeding this will trigger rate limiting. If you need to make a high volume of requests (for example, in a busy production environment), consider these best practices:
Caching: Cache the results of news queries on your end. For instance, if your frontend calls your backend for news every minute, but the news only updates every few minutes, you can cache the response for a short time (say 30-60 seconds) to avoid hitting the API too often.
Batch Requests: Rather than making many individual requests for different filters, try to batch filters into one call if possible. For example, instead of two separate calls for category 5 and category 7, you can do one call with
categoryId: [5,7]
to get both.Respect
limit
appropriately: If you only need the latest item (for a ticker or alert), call withlimit: 1
instead of retrieving a full page.Monitor Usage: The ChainGPT dashboard likely shows your credit usage. Keep an eye on it to ensure you don’t run out unexpectedly. You might implement a check in your app to warn if credits are low.
Language and Environment Compatibility
The official SDK is written for Node.js (JavaScript/TypeScript) environments. It can be used in Node 14+ and in server-side contexts. It is not intended to run in browsers directly (as you wouldn’t want to expose your API key client-side, and CORS might also block direct calls to the API). If you are developing in another language or environment, you have a few options:
Use the REST API directly: The ChainGPT AI News SDK is essentially a wrapper around HTTP calls. You can make direct HTTP requests to the API endpoints (e.g., via
fetch
oraxios
in other languages) using your API key in the headers. You’ll need to refer to ChainGPT’s API docs for the exact endpoints and request format. The responses will be in JSON similar to what’s shown above.Serverless Functions or Backend as a middleman: Even for mobile apps or web apps in other languages, you can create a small backend (using Node or any language) that uses the SDK or HTTP calls to fetch news and then deliver it to your client in a safe manner.
Community SDKs: As the product grows, there may be community-contributed libraries in Python, Ruby, etc. (At the time of writing, JavaScript is the primary supported SDK).
Last updated
Was this helpful?