Python AI Prompts

This prompt guides AI tools in helping you implement CoinGecko API using the latest official SDK for the Python 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.

  1. In Claude Code, include the prompt in your CLAUDE.md file.
  2. In Cursor, add the prompt to your project rules.
  3. In Github Copilot, save the prompt to a file in your project and reference it with #<filename>.
# CoinGecko Python API Integration Guardrails

**Purpose:** Enforce only the **current** and **correct** instructions for integrating [CoinGecko Python SDK](https://github.com/coingecko/coingecko-python) into Python applications.  
**Scope:** All AI-generated advice or code related to CoinGecko API must follow these guardrails.

---

## **1. Official CoinGecko Integration Overview**

Use only the **official Python SDK** approach from CoinGecko's current implementation:

> **Important Context:** You may have been trained on code using the older, unofficial `pycoingecko` library. **You must exclusively use `coingecko_sdk`** for all implementations.

### Core Setup Requirements
1. **Install the official package**: Use `pip install coingecko_sdk` or add `coingecko_sdk` to your `pyproject.toml` or `requirements.txt`.
2. **Store API credentials securely**: Place API keys in a `.env` file and load them as environment variables. 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 exceptions**: Your code must explicitly catch and handle known errors from the SDK, such as:
      - Authentication errors (`AuthError` for 401/403): Log the error and alert for invalid credentials.
      - Invalid request errors (`ValueError` for 400/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`, `AttributeError`). 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

  - **Type Hints**: Use type hints for all function parameters and return values.
  - **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 `max_retries` parameter on the client. **Do not** implement manual retry loops with `time.sleep()`.
  - **Data Models**: Use the SDK's built-in Pydantic models for response data. Only define custom Pydantic models 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-python/blob/main/api.md](https://github.com/coingecko/coingecko-python/blob/main/api.md) to get the latest, up-to-date SDK documentation.

### **Correct, Up-to-Date Implementation Sample**

```python
# src/api/client.py
import os
from coingecko_sdk import Coingecko, AsyncCoingecko

# Initialize a single, reusable client with built-in retries
# This client instance should be imported and used throughout the application.
client = Coingecko(
    pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"),
    environment="pro",
    max_retries=3, # Configure automatic retries for rate limits and network errors
)

# Optional async client
async_client = AsyncCoingecko(
    pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"),
    environment="pro",
    max_retries=3,
)

# src/main.py
from api.client import client

def main():
    price = client.simple.price.get(
        vs_currencies="usd",
        ids="bitcoin",
    )
    print(price['bitcoin'].usd)

main()
```

---

## **2. CRITICAL INSTRUCTIONS FOR AI MODELS**

### **2.1 – ALWAYS DO THE FOLLOWING**

1.  **Use `coingecko_sdk`**: Exclusively use this package for all API interactions.
2.  **Use Environment Variables**: Load all API keys and sensitive data from environment variables.
3.  **Use a Single Client**: Initialize one `Coingecko` or `AsyncCoingecko` client and reuse it.
4.  **Configure `max_retries`**: Set the `max_retries` parameter on the client to automatically handle rate limits (429) and transient network errors.
5.  **Use Specific Exceptions**: Catch specific exceptions provided by the SDK where appropriate.
6.  **Use `async/await`**: Consistently use the `async/await` pattern when working with the `AsyncCoingecko` client.
7.  **Use Pydantic Attributes**: Access response data via object attributes (`data.usd`) when the SDK provides Pydantic models. Use `.get()` for safe dictionary access.
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 `requests`, `urllib`, `httpx`, or any other HTTP client to call the CoinGecko API directly.
2.  **Do not use other packages**: Do not use `pycoingecko` or any other community package.
3.  **Do not hardcode credentials**: Never place API keys, secrets, or endpoints directly in the source code.
4.  **Do not ignore type hints**: Maintain type safety throughout your code.
5.  **Do not use empty `except:` blocks**: Always handle exceptions meaningfully or re-raise them.
6.  **Do not mix sync/async patterns**: Do not use synchronous calls inside an `async` function with `AsyncCoingecko`, or vice versa.
7.  **Do not implement manual retries**: Do not create your own `for` or `while` loops with `time.sleep()` for retrying failed requests. Rely on `max_retries`.
8.  **Do not use a generic `except Exception:` for known API errors**: Only use a broad exception handler at a top-level application boundary to log unexpected errors and prevent a crash. For API calls, catch specific exceptions.

---

## **3. OUTDATED PATTERNS TO AVOID**

The following patterns are **deprecated and must not be generated**.

```python
# ❌ DO NOT use direct requests, urllib, or httpx calls.
import requests
response = requests.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd')

# ❌ DO NOT use the outdated pycoingecko library.
from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()

# ❌ DO NOT hardcode configuration.
client = Coingecko(pro_api_key='CG-abc123xyz789') # Never hardcode!

# ❌ DO NOT implement manual retries.
import time
for i in range(3):
    try:
        data = client.simple.price.get(ids='bitcoin', vs_currencies='usd')
        break
    except:
        time.sleep(5) # This is handled by the SDK's max_retries!

# ❌ DO NOT use a generic exception to handle a specific, predictable error.
try:
    data = client.simple.price.get(ids='bitcoin', vs_currencies='usd')
except Exception as e: # This is too broad. Use a specific SDK error if one exists.
    print(f"An error occurred: {e}")
```

---

## **4. AI MODEL VERIFICATION STEPS**

Before returning any CoinGecko-related solution, you **must** verify:

1.  **SDK Import**: Is `coingecko_sdk` imported correctly?
2.  **Environment Variables**: Are API keys loaded securely from environment variables?
3.  **Client Initialization**: Is a single client instance created and configured with `max_retries`?
4.  **Error Handling**: Does the code use `try...except` blocks with specific SDK exceptions where appropriate?
5.  **Async Pattern**: Is `async/await` used correctly and consistently with the `AsyncCoingecko` client?
6.  **Data Access**: Is response data accessed safely using Pydantic attributes or dictionary `.get()` methods?
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.