# Claude 快速入门

进行您的第一次 Claude API 调用，并构建一个简单的网络搜索助手。

---

## 前提条件

- 一个 Anthropic [控制台账户](/)

## 调用 API

<Tabs>
  <Tab title="cURL">
    <Steps>
      <Step title="设置 API 密钥">
        从 [Claude 控制台](/settings/keys) 获取 API 密钥，并将其设置为环境变量：

        ```bash
        export ANTHROPIC_API_KEY='your-api-key-here'
        ```

        要在多个 shell 会话中持久保存密钥，请将该行添加到您的 shell 配置文件（如 `~/.zshrc` 或 `~/.bashrc`）。
      </Step>

      <Step title="进行第一次 API 调用">
        运行以下命令创建一个简单的网络搜索助手：

        ```bash cURL
        curl https://api.anthropic.com/v1/messages \
          -H "Content-Type: application/json" \
          -H "x-api-key: $ANTHROPIC_API_KEY" \
          -H "anthropic-version: 2023-06-01" \
          -d '{
            "model": "claude-opus-4-7",
            "max_tokens": 1000,
            "messages": [
              {
                "role": "user",
                "content": "What should I search for to find the latest developments in renewable energy?"
              }
            ]
          }'
        ```

        **示例输出：**
        ```json Output
        {
          "id": "msg_01HCDu5LRGeP2o7s2xGmxyx8",
          "type": "message",
          "role": "assistant",
          "content": [
            {
              "type": "text",
              "text": "Here are some effective search strategies to find the latest renewable energy developments:\n\n## Search Terms to Use:\n- \"renewable energy news 2024\"\n- \"clean energy breakthrough\"\n- \"solar/wind/battery technology advances\"\n- \"green energy innovations\"\n- \"climate tech developments\"\n- \"energy storage solutions\"\n\n## Best Sources to Check:\n\n**News & Industry Sites:**\n- Renewable Energy World\n- GreenTech Media (now Wood Mackenzie)\n- Energy Storage News\n- CleanTechnica\n- PV Magazine (for solar)\n- WindPower Engineering & Development..."
            }
          ],
          "model": "claude-opus-4-7",
          "stop_reason": "end_turn",
          "usage": {
            "input_tokens": 21,
            "output_tokens": 305
          }
        }
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="CLI">
    <Steps>
      <Step title="安装 CLI">
        使用 Homebrew 安装 Anthropic CLI：

        ```bash
        brew install anthropics/tap/ant
        ```

        其他安装方法请参阅 CLI 参考中的[安装](/docs/en/api/sdks/cli#installation)。
      </Step>

      <Step title="认证">
        使用 Anthropic 账户登录：

        ```bash
        ant auth login
        ```

        这将打开基于浏览器的 OAuth 流程。授权后，确认凭据：

        ```bash
        ant auth status
        ```

        在没有浏览器的远程主机上，传递 `--no-browser` 获取可在其他设备上打开的 URL，然后将返回的代码粘贴回终端。如果环境中设置了 `ANTHROPIC_API_KEY`，它将优先于登录凭据。有关 CI 等非交互式环境，请参阅[认证](/docs/en/api/sdks/cli#authentication)。
      </Step>

      <Step title="进行第一次 API 调用">
        运行以下命令创建一个简单的网络搜索助手：

        ```bash
        ant messages create \
          --model claude-opus-4-7 \
          --max-tokens 1000 \
          --message '{
            role: user,
            content: "What should I search for to find the latest developments in renewable energy?"
          }'
        ```

        **示例输出：**
        ```json Output
        {
          "id": "msg_01HCDu5LRGeP2o7s2xGmxyx8",
          "type": "message",
          "role": "assistant",
          "content": [
            {
              "type": "text",
              "text": "Here are some effective search strategies to find the latest renewable energy developments:\n\n## Search Terms to Use:\n- \"renewable energy news 2024\"\n- \"clean energy breakthrough\"\n- \"solar/wind/battery technology advances\"\n- \"green energy innovations\"\n- \"climate tech developments\"\n- \"energy storage solutions\"\n\n## Best Sources to Check:\n\n**News & Industry Sites:**\n- Renewable Energy World\n- GreenTech Media (now Wood Mackenzie)\n- Energy Storage News\n- CleanTechnica\n- PV Magazine (for solar)\n- WindPower Engineering & Development..."
            }
          ],
          "model": "claude-opus-4-7",
          "stop_reason": "end_turn",
          "usage": {
            "input_tokens": 21,
            "output_tokens": 305
          }
        }
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="Python">
    <Steps>
      <Step title="设置 API 密钥">
        从 [Claude 控制台](/settings/keys) 获取 API 密钥，并将其设置为环境变量：

        ```bash
        export ANTHROPIC_API_KEY='your-api-key-here'
        ```

        要在多个 shell 会话中持久保存密钥，请将该行添加到您的 shell 配置文件（如 `~/.zshrc` 或 `~/.bashrc`）。
      </Step>

      <Step title="安装 SDK">
        安装 Anthropic Python SDK：

        ```bash
        pip install anthropic
        ```
      </Step>

      <Step title="创建代码">
        将以下内容保存为 `quickstart.py`：

        ```python
        import anthropic

        client = anthropic.Anthropic()

        message = client.messages.create(
            model="claude-opus-4-7",
            max_tokens=1000,
            messages=[
                {
                    "role": "user",
                    "content": "What should I search for to find the latest developments in renewable energy?",
                }
            ],
        )
        print(message.content)
        ```
      </Step>

      <Step title="运行代码">
        ```bash
        python quickstart.py
        ```

        **示例输出：**
        ```text Output
        [
            TextBlock(
                text='Here are some effective search strategies for finding the latest renewable energy developments:\n\n**Search Terms to Use:**\n- "renewable energy news 2024"\n- "clean energy breakthroughs"\n- "solar/wind/battery technology advances"\n- "energy storage innovations"\n- "green hydrogen developments"\n- "renewable energy policy updates"\n\n**Reliable Sources to Check:**\n- **News & Analysis:** Reuters Energy, Bloomberg New Energy Finance, Greentech Media, Energy Storage News\n- **Industry Publications:** Renewable Energy World, PV Magazine, Wind Power Engineering\n- **Research Organizations:** International Energy Agency (IEA), National Renewable Energy Laboratory (NREL)\n- **Government Sources:** Department of Energy websites, EPA clean energy updates\n\n**Specific Topics to Explore:**\n- Perovskite and next-gen solar cells\n- Offshore wind expansion\n- Grid-scale battery storage\n- Green hydrogen production\n- Carbon capture technologies\n- Smart grid innovations\n- Energy policy changes and incentives...',
                type="text",
            )
        ]
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="TypeScript">
    <Steps>
      <Step title="设置 API 密钥">
        从 [Claude 控制台](/settings/keys) 获取 API 密钥，并将其设置为环境变量：

        ```bash
        export ANTHROPIC_API_KEY='your-api-key-here'
        ```

        要在多个 shell 会话中持久保存密钥，请将该行添加到您的 shell 配置文件（如 `~/.zshrc` 或 `~/.bashrc`）。
      </Step>

      <Step title="安装 SDK">
        安装 Anthropic TypeScript SDK：

        ```bash
        npm install @anthropic-ai/sdk
        ```
      </Step>

      <Step title="创建代码">
        将以下内容保存为 `quickstart.ts`：

```typescript
import Anthropic from "@anthropic-ai/sdk";

async function main() {
  const anthropic = new Anthropic();

  const msg = await anthropic.messages.create({
    model: "claude-opus-4-7",
    max_tokens: 1000,
    messages: [
      {
        role: "user",
        content:
          "What should I search for to find the latest developments in renewable energy?"
      }
    ]
  });
  console.log(msg);
}

main().catch(console.error);
        ```
      </Step>

      <Step title="运行代码">
        ```bash
        npx tsx quickstart.ts
        ```

        **示例输出：**
        ```javascript Output hidelines={1..2}
        const _ =
          // output
          {
            id: "msg_01ThFHzad6Bh4TpQ6cHux9t8",
            type: "message",
            role: "assistant",
            model: "claude-opus-4-7",
            content: [
              {
                type: "text",
                text:
                  "Here are some effective search strategies to find the latest renewable energy developments:\n\n" +
                  "## Search Terms to Use:\n" +
                  '- "renewable energy news 2024"\n' +
                  '- "clean energy breakthroughs"\n' +
                  '- "solar wind technology advances"\n' +
                  '- "energy storage innovations"\n' +
                  '- "green hydrogen developments"\n' +
                  '- "offshore wind projects"\n' +
                  '- "battery technology renewable"\n\n' +
                  "## Best Sources to Check:\n\n" +
                  "**News & Industry Sites:**\n" +
                  "- Renewable Energy World\n" +
                  "- CleanTechnica\n" +
                  "- GreenTech Media (now Wood Mackenzie)\n" +
                  "- Energy Storage News\n" +
                  "- PV Magazine (for solar)..."
              }
            ],
            stop_reason: "end_turn",
            usage: {
              input_tokens: 21,
              output_tokens: 302
            }
          }
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="Java">
    <Steps>
      <Step title="设置 API 密钥">
        从 [Claude 控制台](/settings/keys) 获取 API 密钥，并将其设置为环境变量：

        ```bash
        export ANTHROPIC_API_KEY='your-api-key-here'
        ```

        要在多个 shell 会话中持久保存密钥，请将该行添加到您的 shell 配置文件（如 `~/.zshrc` 或 `~/.bashrc`）。
      </Step>

      <Step title="设置项目">
        您需要 JDK（25 或更高版本）和 [Gradle](https://gradle.org/install/) 或 [Maven](https://maven.apache.org/install.html) 在您的 `PATH` 中。为项目创建目录并包含 Java 源代码目录：

        ```bash
        mkdir -p claude-quickstart/src/main/java && cd claude-quickstart
        ```

        然后添加构建文件。在 [Maven Central](https://central.sonatype.com/artifact/com.anthropic/anthropic-java) 上查找当前 SDK 版本。

        <Tabs>
          <Tab title="Gradle">
            将以下内容保存为 `build.gradle.kts`：

            ```kotlin
            plugins {
                application
            }

            repositories {
                mavenCentral()
            }

            java {
                toolchain {
                    languageVersion = JavaLanguageVersion.of(25)
                }
            }

            dependencies {
                implementation("com.anthropic:anthropic-java:2.33.0")
            }

            application {
                mainClass = "QuickStart"
            }
            ```
          </Tab>
          <Tab title="Maven">
            将以下内容保存为 `pom.xml`：

            ```xml
            <project xmlns="http://maven.apache.org/POM/4.0.0">
              <modelVersion>4.0.0</modelVersion>
              <groupId>com.example</groupId>
              <artifactId>quickstart</artifactId>
              <version>1.0-SNAPSHOT</version>
              <properties>
                <maven.compiler.release>25</maven.compiler.release>
                <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
              </properties>
              <dependencies>
                <dependency>
                  <groupId>com.anthropic</groupId>
                  <artifactId>anthropic-java</artifactId>
                  <version>2.33.0</version>
                </dependency>
              </dependencies>
            </project>
            ```
          </Tab>
        </Tabs>
      </Step>

      <Step title="创建代码">
        将以下内容保存为 `QuickStart.java`，放在项目的 Java 源代码目录中（通常是 `src/main/java/`）：

        ```java
        import com.anthropic.client.okhttp.AnthropicOkHttpClient;
        import com.anthropic.models.messages.Message;
        import com.anthropic.models.messages.MessageCreateParams;
        import com.anthropic.models.messages.Model;

        static void main() {
            var client = AnthropicOkHttpClient.fromEnv();

            var params = MessageCreateParams.builder()
                .model(Model.CLAUDE_OPUS_4_7)
                .maxTokens(1000)
                .addUserMessage(
                    "What should I search for to find the latest developments in renewable energy?"
                )
                .build();

            Message message = client.messages().create(params);
            IO.println(message.content());
        }
        ```
      </Step>

      <Step title="运行代码">
        <Tabs>
          <Tab title="Gradle">
            ```bash
            gradle run
            ```
          </Tab>
          <Tab title="Maven">
            ```bash
            mvn compile exec:java -Dexec.mainClass=QuickStart
            ```
          </Tab>
        </Tabs>

        **示例输出：**
        ```text Output
        [ContentBlock{text=TextBlock{text=Here are some effective search strategies to find the latest renewable energy developments:

        ## Search Terms to Use:
        - "renewable energy news 2024"
        - "clean energy breakthroughs"
        - "solar/wind/battery technology advances"
        - "energy storage innovations"
        - "green hydrogen developments"
        - "renewable energy policy updates"

        ## Best Sources to Check:
        - **News & Analysis:** Reuters Energy, Bloomberg New Energy Finance, Greentech Media
        - **Industry Publications:** Renewable Energy World, PV Magazine, Wind Power Engineering
        - **Research Organizations:** International Energy Agency (IEA), National Renewable Energy Laboratory (NREL)
        - **Government Sources:** Department of Energy websites, EPA clean energy updates

        ## Specific Topics to Explore:
        - Perovskite and next-gen solar cells
        - Offshore wind expansion
        - Grid-scale battery storage
        - Green hydrogen production..., type=text}}]
        ```
      </Step>
    </Steps>
  </Tab>
</Tabs>

## 后续步骤

您已完成第一次 API 调用。接下来，学习您将在每次 Claude 集成中使用的 Messages API 模式。

<Card title="使用 Messages API" icon="messages" href="/docs/en/build-with-claude/working-with-messages">
  学习多轮对话、系统提示、停止原因和其他核心模式。
</Card>

熟悉基础知识后，进一步探索：

<CardGroup cols={3}>
  <Card title="模型概览" icon="brain" href="/docs/en/about-claude/models/overview">
    按能力和成本比较 Claude 模型。
  </Card>
  <Card title="功能概览" icon="list" href="/docs/en/build-with-claude/overview">
    浏览所有 Claude 功能：工具、上下文管理、结构化输出等。
  </Card>
  <Card title="客户端 SDK" icon="code-brackets" href="/docs/en/api/client-sdks">
    Python、TypeScript、Java 和其他客户端库的参考文档。
  </Card>
</CardGroup>
