> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chainstream.io/llms.txt
> Use this file to discover all available pages before exploring further.

# コードエクスポート

> GraphQL クエリからそのまま使える 7 言語のコードスニペットを生成

## 概要

Code Export 機能は、現在の GraphQL クエリを選択した言語の、そのまま使えるコードスニペットに変換します。生成コードには HTTP リクエスト一式 — エンドポイント URL、認証ヘッダー、クエリ本文、variables — が含まれるため、プロジェクトにそのまま貼り付けられます。

***

## 対応言語

<div style={{ overflowX: 'auto', width: '100%' }}>
  | 言語             | 形式               | 用途                         |
  | :------------- | :--------------- | :------------------------- |
  | **cURL**       | シェルコマンド          | ターミナルでの手早い検証、CI/CD スクリプト   |
  | **Python**     | `requests` ライブラリ | バックエンド、データパイプライン、Jupyter   |
  | **JavaScript** | `fetch` API      | ブラウザアプリ、Node.js サービス       |
  | **Go**         | `net/http`       | バックエンドのマイクロサービス、CLI        |
  | **Rust**       | `reqwest` crate  | 高スループットなサービス               |
  | **Ruby**       | `net/http`       | Rails アプリ、スクリプト            |
  | **PHP**        | `cURL` 拡張        | PHP バックエンド、WordPress プラグイン |
</div>

***

## エクスポート手順

<Steps>
  <Step title="クエリを書く">
    エディタにクエリを入力または読み込みます。エクスポート前に正常に実行できることを確認してください。
  </Step>

  <Step title="Export Code をクリック">
    ツールバーの **Export Code** をクリックします。言語選択と生成スニペットが表示されるモーダルが開きます。
  </Step>

  <Step title="言語を選ぶ">
    ドロップダウンから対象言語を選びます。スニペットはすぐに更新されます。
  </Step>

  <Step title="スニペットをコピー">
    **Copy** をクリックして生成コードをクリップボードにコピーします。
  </Step>
</Steps>

<Tip>
  エクスポートされたコードは、IDE で現在設定している GraphQL エンドポイントと API Key を使います。カスタムエンドポイントやヘッダーを設定している場合、その内容が生成スニペットに反映されます。
</Tip>

***

## スニペット例

次の例は、単純な DEXTrades クエリ — Solana の最新 10 件の DEX 取引 — をエクスポートしたものです。

```graphql theme={null}
query {
  Solana {
    DEXTrades(
      limit: {count: 10}
      orderBy: {descending: Block_Time}
    ) {
      Block { Time }
      Transaction { Hash }
      Trade {
        Buy { Currency { MintAddress } Amount PriceInUSD }
        Sell { Currency { MintAddress } Amount }
        Dex { ProtocolName }
      }
    }
  }
}
```

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X POST "https://graphql.chainstream.io/graphql" \
      -H "Content-Type: application/json" \
      -H "X-API-KEY: your_api_key" \
      -d '{
        "query": "{ Solana { DEXTrades(limit: {count: 10}, orderBy: {descending: Block_Time}) { Block { Time } Transaction { Hash } Trade { Buy { Currency { MintAddress } Amount PriceInUSD } Sell { Currency { MintAddress } Amount } Dex { ProtocolName } } } } }"
      }'
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    url = "https://graphql.chainstream.io/graphql"
    headers = {
        "Content-Type": "application/json",
        "X-API-KEY": "your_api_key",
    }
    query = """
    {
      Solana {
        DEXTrades(
          limit: {count: 10}
          orderBy: {descending: Block_Time}
        ) {
          Block { Time }
          Transaction { Hash }
          Trade {
            Buy { Currency { MintAddress } Amount PriceInUSD }
            Sell { Currency { MintAddress } Amount }
            Dex { ProtocolName }
          }
        }
      }
    }
    """

    response = requests.post(url, json={"query": query}, headers=headers)
    data = response.json()
    print(data)
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const response = await fetch("https://graphql.chainstream.io/graphql", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "your_api_key",
      },
      body: JSON.stringify({
        query: `{
          Solana {
            DEXTrades(
              limit: {count: 10}
              orderBy: {descending: Block_Time}
            ) {
              Block { Time }
              Transaction { Hash }
              Trade {
                Buy { Currency { MintAddress } Amount PriceInUSD }
                Sell { Currency { MintAddress } Amount }
                Dex { ProtocolName }
              }
            }
          }
        }`,
      }),
    });

    const data = await response.json();
    console.log(data);
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    package main

    import (
        "bytes"
        "encoding/json"
        "fmt"
        "io"
        "net/http"
    )

    func main() {
        payload := map[string]string{
            "query": `{ Solana { DEXTrades(limit: {count: 10}, orderBy: {descending: Block_Time}) { Block { Time } Transaction { Hash } Trade { Buy { Currency { MintAddress } Amount PriceInUSD } Sell { Currency { MintAddress } Amount } Dex { ProtocolName } } } } }`,
        }
        body, _ := json.Marshal(payload)

        req, _ := http.NewRequest("POST", "https://graphql.chainstream.io/graphql", bytes.NewBuffer(body))
        req.Header.Set("Content-Type", "application/json")
        req.Header.Set("X-API-KEY", "your_api_key")

        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            panic(err)
        }
        defer resp.Body.Close()

        result, _ := io.ReadAll(resp.Body)
        fmt.Println(string(result))
    }
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
    use serde_json::json;

    #[tokio::main]
    async fn main() -> Result<(), reqwest::Error> {
        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
        headers.insert("X-API-KEY", HeaderValue::from_static("your_api_key"));

        let body = json!({
            "query": r#"{ Solana { DEXTrades(limit: {count: 10}, orderBy: {descending: Block_Time}) { Block { Time } Transaction { Hash } Trade { Buy { Currency { MintAddress } Amount PriceInUSD } Sell { Currency { MintAddress } Amount } Dex { ProtocolName } } } } }"#
        });

        let client = reqwest::Client::new();
        let res = client
            .post("https://graphql.chainstream.io/graphql")
            .headers(headers)
            .json(&body)
            .send()
            .await?;

        println!("{}", res.text().await?);
        Ok(())
    }
    ```
  </Tab>
</Tabs>

***

## エクスポートコードに含まれるもの

生成される各スニペットには次が含まれます。

| 項目                 | 説明                                       |
| :----------------- | :--------------------------------------- |
| **Endpoint URL**   | `https://graphql.chainstream.io/graphql` |
| **Authentication** | IDE の Headers パネルの `X-API-KEY` ヘッダー      |
| **Content-Type**   | `application/json`                       |
| **Query body**     | エディタ上の GraphQL クエリ全文                     |
| **Variables**      | Variables パネルに値がある場合に含まれます               |

<Note>
  実行前に `your_api_key` を実際の API Key に置き換えてください。セキュリティのため、IDE はエクスポートスニペットに本物のキーを埋め込みません。
</Note>

***

## ヒント

* **エクスポート前にテスト** — まず IDE でクエリを実行し、動作を確認してください。エクスポートはクエリをそのままコピーします。
* **variables でパラメータ化** — ハードコードではなく GraphQL variables を使います。エクスポートコードにはクエリと並んで `variables` の JSON が含まれます。
* **依存関係の確認** — Python は `requests`、Rust は `reqwest`、Go は標準ライブラリを使います。プロジェクトに必要なパッケージが入っているか確認してください。
