1. 创建 React 项目
如果你还没有 React 项目,可以使用 create-react-app
快速创建一个新的项目:
npx create-react-app deepseek-api-demo
cd deepseek-api-demo
2. 安装必要的依赖
你可能需要安装 axios
或 fetch
来发送 HTTP 请求。axios
是一个常用的 HTTP 客户端库。
npm install axios
3. 创建 API 服务文件
在 src
目录下创建一个 api
文件夹,并在其中创建一个 deepseekApi.js
文件,用于封装与 DeepSeek API 的交互。
// src/api/deepseekApi.js
import axios from 'axios';
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1'; // 替换为实际的 DeepSeek API URL
const deepseekApi = {
// 示例:获取某个资源
getResource: async (resourceId) => {
try {
const response = await axios.get(`${DEEPSEEK_API_URL}/resources/${resourceId}`);
return response.data;
} catch (error) {
console.error('Error fetching resource:', error);
throw error;
}
},
// 示例:创建某个资源
createResource: async (resourceData) => {
try {
const response = await axios.post(`${DEEPSEEK_API_URL}/resources`, resourceData);
return response.data;
} catch (error) {
console.error('Error creating resource:', error);
throw error;
}
},
// 其他 API 调用...
};
export default deepseekApi;
4. 在 React 组件中使用 API
你可以在 React 组件中使用 deepseekApi
来调用 DeepSeek API。例如,在 src/App.js
中:
import React, { useEffect, useState } from 'react';
import deepseekApi from './api/deepseekApi';
function App() {
const [resource, setResource] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchResource = async () => {
try {
const resourceId = '123'; // 替换为实际的资源 ID
const data = await deepseekApi.getResource(resourceId);
setResource(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchResource();
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div className="App">
<h1>DeepSeek Resource</h1>
{resource && (
<div>
<h2>{resource.name}</h2>
<p>{resource.description}</p>
</div>
)}
</div>
);
}
export default App;
5. 处理 API 认证
如果 DeepSeek API 需要认证(如 API Key 或 OAuth),你需要在请求头中添加认证信息。例如:
const DEEPSEEK_API_KEY = 'your-api-key'; // 替换为你的 API Key
const deepseekApi = {
getResource: async (resourceId) => {
try {
const response = await axios.get(`${DEEPSEEK_API_URL}/resources/${resourceId}`, {
headers: {
'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
},
});
return response.data;
} catch (error) {
console.error('Error fetching resource:', error);
throw error;
}
},
// 其他 API 调用...
};
6. 运行项目
确保你的 React 项目正在运行:
npm start
7. 测试和调试
打开浏览器,访问 http://localhost:3000
,查看你的应用是否正常工作。如果有任何问题,可以使用浏览器的开发者工具或 console.log
进行调试。
8. 部署
当你完成开发并测试通过后,可以使用以下命令构建生产版本:
npm run build
然后将 build
目录中的文件部署到你的服务器或静态网站托管服务上。