在当今的软件开发中,调用外部API接口已经成为了一个非常普遍的需求。TypeScript作为JavaScript的一个超集,提供了静态类型检查和编译时类型安全,使得我们在调用API时更加优雅和高效。下面,我将一步步教你如何用TypeScript调用外部API接口。
1. 准备工作
首先,确保你的开发环境已经安装了Node.js和npm。然后,创建一个新的TypeScript项目:
mkdir my-api-project
cd my-api-project
npm init -y
npm install typescript @types/node
tsc --init
在tsconfig.json中,我们可以添加以下配置,以便编译TypeScript代码:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true
}
}
2. 安装axios库
为了方便地发送HTTP请求,我们可以使用axios库。在项目中安装axios:
npm install axios
3. 定义接口类型
在TypeScript中,我们可以定义接口来约束API返回的数据结构。例如,假设我们正在调用一个天气API,我们可以定义以下接口:
interface WeatherResponse {
success: boolean;
data: {
temperature: number;
description: string;
};
}
4. 发送请求
接下来,我们可以编写一个函数来发送请求并处理响应。以下是一个简单的示例:
import axios from 'axios';
const getWeather = async (city: string): Promise<WeatherResponse> => {
try {
const response = await axios.get<WeatherResponse>(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${city}`);
return response.data;
} catch (error) {
console.error('Error fetching weather data:', error);
throw error;
}
};
在这个示例中,我们使用axios.get方法发送GET请求,并将响应类型指定为WeatherResponse接口。这样,TypeScript编译器就会在编译时检查我们返回的数据是否符合接口定义。
5. 使用axios请求拦截器
为了更好地管理API请求,我们可以使用axios的请求拦截器。以下是一个简单的示例,用于在所有请求中添加一个通用的header:
axios.interceptors.request.use(config => {
config.headers['Authorization'] = 'Bearer YOUR_ACCESS_TOKEN';
return config;
}, error => {
return Promise.reject(error);
});
6. 错误处理
在实际应用中,我们经常会遇到网络错误、服务器错误等情况。因此,我们需要对错误进行处理。以下是一个示例,演示了如何处理错误:
const getWeather = async (city: string): Promise<WeatherResponse> => {
try {
const response = await axios.get<WeatherResponse>(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${city}`);
return response.data;
} catch (error) {
if (error.response) {
console.error('Server responded with status code:', error.response.status);
console.error('Error data:', error.response.data);
} else if (error.request) {
console.error('No response received from server');
} else {
console.error('Error setting up request:', error.message);
}
throw error;
}
};
7. 总结
通过以上步骤,我们已经学会了如何用TypeScript优雅地调用外部API接口。在实际开发中,你可以根据自己的需求进行扩展,例如添加更多的接口、处理更复杂的业务逻辑等。希望这篇文章对你有所帮助!
