零度AI
进阶13 分钟阅读

Claude Code API 集成

学习如何集成外部 API,使用 Claude Code 处理 API 请求和数据

Claude CodeAPI数据获取外部服务HTTP

API 集成基础

API(应用程序编程接口)是不同系统之间通信的桥梁。Claude Code 可以帮助你:

  • 理解 API 文档
  • 生成 API 客户端
  • 处理请求和响应
  • 错误处理
  • 数据解析

HTTP 请求基础

1. GET 请求

帮我发送一个 GET 请求
javascript
// 使用 fetch 发送 GET 请求
const response = await fetch('https://api.example.com/data')
const data = await response.json()

2. POST 请求

帮我发送一个 POST 请求,包含 JSON 数据
javascript
const data = { name: '张三', email: 'zhangsan@example.com' }
const response = await fetch('https://api.example.com/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(data)
})

API 客户端生成

1. 使用 fetch

帮我创建一个 API 客户端
typescript
// src/services/api.ts
export async function fetchData<T>(url: string, options?: RequestInit): Promise<T> {
  const response = await fetch(url, {
    headers: {
      'Content-Type': 'application/json',
      ...options?.headers
    },
    ...options
  })

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`)
  }

  return response.json()
}

2. 使用 Axios

帮我配置 Axios
typescript
import axios from 'axios'

const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  headers: { 'Content-Type': 'application/json' }
})

export default api

数据解析与转换

1. 解析 JSON 数据

帮我解析这个 API 响应
typescript
interface ApiResponse {
  data: {
    id: number
    name: string
    price: number
    available: boolean
  }[]
  total: number
  page: number
  limit: number
}

const response = await fetchData<ApiResponse>('/products')
const products = response.data

2. 数据转换

帮我转换这些 API 数据格式
typescript
const apiData = [
  { id: 1, name: 'Product 1', price: 99.99 },
  { id: 2, name: 'Product 2', price: 199.99 }
]

const formattedData = apiData.map(item => ({
  ...item,
  price: `$${item.price.toFixed(2)}`,
  inStock: item.price > 0
}))

错误处理

1. 请求错误

typescript
try {
  const response = await fetchData('/data')
} catch (error) {
  if (error instanceof Error) {
    console.error('请求错误:', error.message)
  }
}

2. API 错误

typescript
if (response.status === 401) {
  throw new Error('认证失败')
}

if (response.status === 404) {
  throw new Error('资源未找到')
}

实战案例:GitHub API

获取仓库信息

帮我使用 GitHub API 获取用户仓库信息

获取用户仓库

javascript
async function getRepositories(username: string) {
  const url = `https://api.github.com/users/${username}/repos`
  const response = await fetch(url)

  if (!response.ok) {
    throw new Error('获取仓库信息失败')
  }

  return response.json()
}

解析数据

javascript
interface Repository {
  id: number
  name: string
  description?: string
  stargazers_count: number
  forks_count: number
  language?: string
  html_url: string
}

async function displayRepositories(username: string) {
  const repos = await getRepositories(username)
  const formattedRepos = repos.map((repo: any) => ({
    id: repo.id,
    name: repo.name,
    description: repo.description,
    stars: repo.stargazers_count,
    forks: repo.forks_count,
    language: repo.language,
    url: repo.html_url
  }))

  return formattedRepos
}

显示信息

javascript
const user = 'octocat'
const repos = await displayRepositories(user)
repos.forEach(repo => {
  console.log(`仓库: ${repo.name}`)
  console.log(`描述: ${repo.description}`)
  console.log(`Stars: ${repo.stars} | Forks: ${repo.forks}`)
  if (repo.language) {
    console.log(`语言: ${repo.language}`)
  }
  console.log(`链接: ${repo.url}`)
  console.log()
})

高级 API 集成

1. 分页

typescript
async function getProducts(page: number = 1, limit: number = 20) {
  const url = `/products?page=${page}&limit=${limit}`
  return fetchData<ApiResponse>(url)
}

2. 搜索

typescript
async function searchProducts(query: string) {
  const url = `/products?search=${encodeURIComponent(query)}`
  return fetchData<ApiResponse>(url)
}

3. 数据缓存

typescript
const cache = new Map<string, { data: any; timestamp: number }>()

async function fetchWithCache(url: string, options?: RequestInit) {
  const cacheKey = url + JSON.stringify(options)

  // 检查缓存(5分钟有效期)
  const cached = cache.get(cacheKey)
  if (cached && Date.now() - cached.timestamp < 5 * 60 * 1000) {
    return cached.data
  }

  const data = await fetchData(url, options)

  // 更新缓存
  cache.set(cacheKey, { data, timestamp: Date.now() })
  return data
}

GraphQL API

查询数据

javascript
async function fetchGraphQL(query: string, variables?: any) {
  const response = await fetch('/graphql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query, variables })
  })

  if (!response.ok) {
    throw new Error('GraphQL 请求失败')
  }

  return response.json()
}

使用 Apollo Client

帮我配置 Apollo Client

API 文档自动化

1. OpenAPI/Swagger

帮我使用 OpenAPI 文档

2. 自动生成类型

帮我从 API 响应生成 TypeScript 类型

安全注意事项

1. 密钥管理

帮我安全管理 API 密钥

2. CORS 处理

帮我解决 CORS 问题

下一步

掌握了 API 集成后,接下来可以学习:

  • Claude Code 数据可视化 - 数据展示和图表
  • Claude Code 实时数据 - WebSocket 和实时更新
  • Claude Code 状态管理 - 复杂应用状态管理

API 是应用的血管

API 集成是现代应用开发的核心技能。Claude Code 可以帮助你快速理解和集成各种 API,让应用具备强大的数据能力!