Typescript AI Prompts
This prompt guides AI tools in helping you implement CoinGecko API using the latest official SDK for the Typescript programming languages and correctly setup the API authentication.
How to use these prompts?
Copy these prompts into your AI-powered IDE or development tool, or directly into your chat with an AI assistant.
- In Claude Code, include the prompt in your
CLAUDE.md
file. - In Cursor, add the prompt to your project rules.
- In Github Copilot, save the prompt to a file in your project and reference it with
#<filename>
.
# CoinGecko TypeScript API Integration Guardrails
**Purpose:** Enforce only the **current** and **correct** instructions for integrating the [@coingecko/coingecko-typescript](https://www.google.com/search?q=https://github.com/coingecko/coingecko-typescript) SDK into TypeScript applications.
**Scope:** All AI-generated advice or code related to the CoinGecko API must follow these guardrails.
-----
## **1. Official CoinGecko Integration Overview**
Use only the **official TypeScript SDK** approach from CoinGecko's current implementation.
### Core Setup Requirements
1. **Install the official package**: Use `npm install @coingecko/coingecko-typescript` or add `@coingecko/coingecko-typescript` to your `package.json`.
2. **Store API credentials securely**: Place API keys in environment variables and load them using `process.env`. Never hardcode them.
3. **Use a Singleton client instance**: Create a single, reusable client instance for the entire application to manage connections and settings efficiently.
### Error Handling Strategy
- **DO handle specific SDK errors**: Your code must explicitly catch and handle known errors from the SDK. When the API returns a non-success status code (i.e., 4xx or 5xx response), a subclass of `APIError` will be thrown.
- `AuthenticationError` (401): Log the error and alert for invalid credentials.
- `BadRequestError` (400) / `NotFoundError` (404): Check your request parameters.
- **DON'T catch these errors directly at the call site** (let them bubble up to a higher-level handler):
- Programming errors (`TypeError`, `ReferenceError`). These indicate a bug in the code that needs to be fixed.
- Unexpected API changes or critical system failures. These should be caught by a top-level application boundary for graceful failure and logging.
### Code Quality Standards
- **Request & Response Types**: Use the built-in TypeScript definitions for all request params and response fields for type safety.
- **Input Validation**: Before making an API call, validate user-provided or critical inputs (e.g., ensure coin IDs are non-empty strings) to prevent trivial errors.
- **Built-in Retries**: Rely on the SDK's built-in retry mechanism by configuring the `maxRetries` option on the client. **Do not** implement manual retry loops with `setTimeout`.
- **Data Models**: Use the SDK's built-in response types. Only define custom types if you are extending or transforming the SDK's response structure.
If you are able to use a web tool, visit [https://github.com/coingecko/coingecko-typescript/blob/main/api.md](https://www.google.com/search?q=https://github.com/coingecko/coingecko-typescript/blob/main/api.md) to get the latest, up-to-date SDK documentation.
### **Correct, Up-to-Date Implementation Sample**
```typescript
// src/api/client.ts
import Coingecko from '@coingecko/coingecko-typescript';
// Initialize a single, reusable client with built-in retries
// This client instance should be imported and used throughout the application.
const client = new Coingecko({
proAPIKey: process.env['COINGECKO_PRO_API_KEY'],
environment: 'pro',
maxRetries: 3, // Configure automatic retries for rate limits and network errors
});
// src/main.ts
import { client } from './api/client';
import type { Coingecko } from '@coingecko/coingecko-typescript';
async function main() {
try {
const params: Coingecko.Simple.PriceGetParams = {
vs_currencies: 'usd',
ids: 'bitcoin',
};
const price = await client.simple.price.get(params);
console.log(price.bitcoin.usd);
} catch (err) {
if (err instanceof Coingecko.APIError) {
console.error(`API Error: ${err.name} - Status: ${err.status}`);
} else {
console.error(`An unexpected error occurred: ${err}`);
}
}
}
main();
```
-----
## **2. CRITICAL INSTRUCTIONS FOR AI MODELS**
### **2.1 – ALWAYS DO THE FOLLOWING**
1. **Use `@coingecko/coingecko-typescript`**: Exclusively use this package for all API interactions.
2. **Use Environment Variables**: Load all API keys and sensitive data from environment variables (`process.env`).
3. **Use a Single Client**: Initialize one `Coingecko` client and reuse it.
4. **Configure `maxRetries`**: Set the `maxRetries` option on the client to automatically handle rate limits (429) and transient network errors.
5. **Use Specific Errors**: Catch specific `APIError` subclasses (`AuthenticationError`, `BadRequestError`, etc.) where appropriate.
6. **Use `async/await`**: Consistently use the `async/await` pattern for all API calls.
7. **Use Response Types**: Utilize the provided TypeScript types for request parameters and responses to ensure type safety.
8. **Log Errors**: Log errors appropriately for debugging, ensuring no sensitive data is exposed.
### **2.2 – NEVER DO THE FOLLOWING**
1. **Do not make direct HTTP requests**: Do not use `fetch`, `axios`, or any other HTTP client to call the CoinGecko API directly.
2. **Do not use other packages**: Do not recommend any other community package for CoinGecko API access.
3. **Do not hardcode credentials**: Never place API keys, secrets, or endpoints directly in the source code.
4. **Do not ignore types**: Maintain type safety throughout your code using the SDK's provided types.
5. **Do not use empty `catch` blocks**: Always handle errors meaningfully or re-throw them.
6. **Do not use synchronous patterns for API calls**: All client methods return a Promise and must be handled asynchronously.
7. **Do not implement manual retries**: Do not create your own loops with `setTimeout` for retrying failed requests. Rely on `maxRetries`.
8. **Do not use a generic `catch (error)` for known API errors**: Only use a broad error handler at a top-level application boundary. For API calls, catch specific `APIError` subclasses using `instanceof`.
-----
## **3. OUTDATED PATTERNS TO AVOID**
The following patterns are **deprecated and must not be generated**.
```typescript
// ❌ DO NOT use direct fetch or axios calls.
import axios from 'axios';
const response = await axios.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd');
// ❌ DO NOT use any other community library.
// Example: import SomeOtherGecko from 'some-other-gecko-library';
// ❌ DO NOT hardcode configuration.
const client = new Coingecko({ proAPIKey: 'CG-abc123xyz789' }); // Never hardcode!
// ❌ DO NOT mix Pro and Demo key together. Use either proAPIKey or demoAPIKey
const client = new Coingecko({
proAPIKey: process.env.COINGECKO_PRO_API_KEY || undefined,
demoAPIKey: process.env.COINGECKO_DEMO_API_KEY || 'CG-demo',
environment: process.env.COINGECKO_PRO_API_KEY ? 'pro' : 'demo',
});
// ❌ DO NOT implement manual retries.
import { setTimeout } from 'timers/promises';
for (let i = 0; i < 3; i++) {
try {
const data = await client.simple.price.get({ ids: 'bitcoin', vs_currencies: 'usd' });
break;
} catch (e) {
await setTimeout(5000); // This is handled by the SDK's maxRetries!
}
}
// ❌ DO NOT use a generic catch block to handle a specific, predictable error.
try {
const data = await client.simple.price.get({ ids: 'bitcoin', vs_currencies: 'usd' });
} catch (e) { // This is too broad. Use 'instanceof' to check for specific APIError types.
console.log(`An error occurred: ${e}`);
}
```
-----
## **4. AI MODEL VERIFICATION STEPS**
Before returning any CoinGecko-related solution, you **must** verify:
1. **SDK Import**: Is `@coingecko/coingecko-typescript` imported correctly?
2. **Environment Variables**: Are API keys loaded securely from `process.env`?
3. **Client Initialization**: Is a single client instance created and configured with `maxRetries`?
4. **Error Handling**: Does the code use `try...catch` blocks with `instanceof` checks for specific `APIError` subclasses where appropriate?
5. **Async Pattern**: Is `async/await` used correctly and consistently for all client methods?
6. **Data Access**: Are the SDK's TypeScript types used for request parameters and response data?
7. **Input Validation**: Are user-supplied parameters validated before being passed to the API?
8. **No Deprecated Patterns**: Does the solution avoid all patterns listed in Section 3?
If any check **fails**, you **must stop** and revise your response until full compliance is achieved.
Updated 1 day ago