×
全部 > AI技术 > AI编程 > AI代码生成 > 总结AI生成API接口SDK代码的流程

总结AI生成API接口SDK代码的流程

claude3.5 sonnet 20241022(Anthropic)

### SDK Generation Overview This document outlines the generation of a TypeScript SDK for a frontend client using Axios as the HTTP library. The SDK is designed based on the provided OpenAPI specification and includes error handling and interceptors for enhanced functionality. ### SDK Directory Structure ``` /my-sdk │ ├── src │ ├── api │ │ ├── index.ts # Main API entry point │ │ ├── apiClient.ts # Axios client configuration │ │ └── endpoints.ts # API endpoint definitions │ │ │ ├── models │ │ └── responseModels.ts # TypeScript response models │ │ │ ├── utils │ │ └── errorHandler.ts # Error handling utilities │ │ │ └── interceptors │ └── requestInterceptor.ts # Axios request interceptor │ ├── tests │ └── api.test.ts # Unit tests for the API │ └── README.md # Usage documentation ``` ### Core SDK Code Files #### 1. `apiClient.ts` ```typescript import axios from 'axios'; const apiClient = axios.create({ baseURL: 'https://api.example.com', // Base URL from OpenAPI spec timeout: 10000, }); // Add request interceptors apiClient.interceptors.request.use( config => { // Add any custom logic here, e.g., adding tokens return config; }, error => { return Promise.reject(error); } ); export default apiClient; ``` #### 2. `endpoints.ts` ```typescript import apiClient from './apiClient'; import { MyResponseModel } from '../models/responseModels'; export const fetchData = async (params: any): Promise<MyResponseModel> => { try { const response = await apiClient.get('/data', { params }); return response.data; } catch (error) { // Handle error using the error handler throw error; } }; ``` #### 3. `errorHandler.ts` ```typescript export const handleError = (error: any) => { // Implement error handling logic console.error('API call failed:', error); throw new Error('An error occurred while fetching data.'); }; ``` ### Usage Example To use the generated SDK, follow the steps below: 1. Install the SDK: ```bash npm install my-sdk ``` 2. Import and use in your application: ```typescript import { fetchData } from 'my-sdk/src/api/endpoints'; const loadData = async () => { try { const data = await fetchData({ id: 123 }); console.log('Fetched data:', data); } catch (error) { console.error('Error loading data:', error); } }; loadData(); ``` ### Conclusion This SDK is structured to be modular and maintainable, adhering to best practices in TypeScript development. It includes essential features such as error handling and request interceptors, providing a robust solution for API interactions in a frontend application.

通义千问2.5-Coder-7B(阿里云百炼)

```markdown # SDK Generation Overview This SDK is generated based on the provided OpenAPI specification using TypeScript and Axios for HTTP requests. It includes error handling and an interceptor for better management of API calls. # SDK Directory Structure ``` sdk/ ├── src/ │ ├── api.ts │ ├── models/ │ │ ├── User.ts │ │ └── ... │ ├── services/ │ │ ├── UserService.ts │ │ └── ... │ ├── interceptors/ │ │ ├── requestInterceptor.ts │ │ └── responseInterceptor.ts │ └── index.ts ├── tests/ │ ├── api.test.ts │ └── ... ├── package.json └── README.md ``` # Core SDK Code Files ## src/api.ts ```typescript import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; const defaultConfig: AxiosRequestConfig = { baseURL: 'https://api.example.com', timeout: 5000, }; export const client: AxiosInstance = axios.create(defaultConfig); client.interceptors.request.use( (config: AxiosRequestConfig) => { // Add token to headers or other common configurations return config; }, (error) => Promise.reject(error) ); client.interceptors.response.use( (response: AxiosResponse) => { if (response.status >= 200 && response.status < 300) { return response.data; } else { throw new Error(`HTTP error! status: ${response.status}`); } }, (error) => Promise.reject(error) ); ``` ## src/services/UserService.ts ```typescript import { client } from '../api'; import { User } from '../models/User'; export class UserService { public static async getUser(userId: string): Promise<User> { try { const response = await client.get(`/users/${userId}`); return response as User; } catch (error) { throw new Error(`Failed to get user: ${error.message}`); } } public static async createUser(user: User): Promise<User> { try { const response = await client.post('/users', user); return response as User; } catch (error) { throw new Error(`Failed to create user: ${error.message}`); } } } ``` ## src/models/User.ts ```typescript export interface User { id: string; name: string; email: string; } ``` ## src/index.ts ```typescript export * from './services'; export * from './models'; ``` # Usage Example To use this SDK in your project, follow these steps: 1. Install the dependencies: ```bash npm install axios typescript @types/node ``` 2. Import and use the SDK in your code: ```typescript import { UserService } from './sdk'; async function main() { try { const user = await UserService.getUser('123'); console.log(user); } catch (error) { console.error(error); } } main(); ``` This example demonstrates how to fetch a user using the `UserService`. Make sure to replace `'123'` with the actual user ID you want to retrieve. ```

gpt-4.1(OpenAI)

SDK Generation Overview 本次根据输入参数,自动生成以 TypeScript 为开发语言,适用于前端环境、基于 Axios 实现的API接口SDK,并集成了错误处理(ErrorHandling)及统一拦截器(Interceptor)。SDK完成了主要请求逻辑的封装,对参数、返回值均进行了类型定义,保证了可扩展性和类型安全性,非常适用于现代前端应用的开发和集成。 SDK Directory Structure sdk/ ├── api/ │ └── <模块文件>.ts # 按分组自动拆分API实现 ├── core/ │ ├── httpClient.ts # Axios请求统一封装与拦截器 │ └── error.ts # 错误类型与处理模块 ├── types/ │ └── index.ts # 响应、请求类型定义 └── index.ts # SDK主入口导出 核心SDK代码文件 sdk/core/httpClient.ts import axios, { AxiosInstance, AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios'; import { ApiError } from './error'; const instance: AxiosInstance = axios.create({ baseURL: process.env.API_BASE_URL || '', // 可通过环境变量注入 timeout: 10000, headers: { 'Content-Type': 'application/json', }, }); // 请求拦截器(添加token、日志等扩展功能) instance.interceptors.request.use( config => { // token注入示例 const token = localStorage.getItem('ACCESS_TOKEN'); if (token) { config.headers['Authorization'] = `Bearer ${token}`; } // ... 其他前置处理 return config; }, error => Promise.reject(error) ); // 统一响应拦截与错误处理 instance.interceptors.response.use( (response: AxiosResponse) => response, (error: AxiosError) => { // 统一包装为ApiError return Promise.reject(ApiError.fromAxios(error)); } ); export default instance; sdk/core/error.ts export class ApiError extends Error { status?: number; code?: string | number; data?: any; constructor(message: string, status?: number, code?: string | number, data?: any) { super(message); this.name = 'ApiError'; this.status = status; this.code = code; this.data = data; } static fromAxios(error: any): ApiError { if (error.response) { // 服务端响应错误 const { status, data } = error.response; return new ApiError( data?.message || 'API Error', status, data?.code, data ); } if (error.request) { // 请求已发出但无响应 return new ApiError('No response received from server'); } // 其他错误 return new ApiError(error.message); } } sdk/types/index.ts // 以下内容根据openApiSpec自动生成,示例: export interface User { id: number; name: string; email: string; } export interface LoginRequest { username: string; password: string; } export interface LoginResponse { token: string; user: User; } sdk/api/auth.ts import httpClient from '../core/httpClient'; import { LoginRequest, LoginResponse } from '../types'; /** * 用户登录 * @param data */ export async function login(data: LoginRequest): Promise<LoginResponse> { try { const response = await httpClient.post<LoginResponse>('/auth/login', data); return response.data; } catch (e) { throw e; } } /** * 获取当前用户信息 */ export async function getProfile(): Promise<User> { try { const response = await httpClient.get<User>('/auth/profile'); return response.data; } catch (e) { throw e; } } sdk/index.ts export * as AuthAPI from './api/auth'; // ... 其他分组导出 使用示例 (Usage Example) import { AuthAPI } from 'your-sdk-path'; async function doLogin() { try { const loginResp = await AuthAPI.login({ username: 'testuser', password: '123456' }); console.log('User Info:', loginResp.user); const profile = await AuthAPI.getProfile(); console.log('Current Profile:', profile); } catch (error) { if (error.name === 'ApiError') { // 统一错误处理 console.error(`[${error.status}] ${error.message}`, error.data); } else { console.error('Unknown error:', error); } } } 最佳实践建议 - 支持灵活注入 baseURL/token,便于多环境切换 - 通过 centralized error 统一API错误格式 - 各模块函数附带注释与类型定义,便于IDE提示及维护 - 拦截器可扩展实现统一 Loading、日志、权限校验等前置/后置逻辑 定制化说明 以上为标准SDK骨架。若需自动生成全部API函数、类型定义、批量导出等,可输入具体的 openApiSpec 文档内容,将按照文档结构生成所有接口、模型、参数定义,并可灵活扩展,如自动分页封装、全局配置自定义等。 如需进一步详细全量SDK源码生成,请补充OpenAPI/Swagger文档具体内容。

DeepSeek V3(Deepseek)

由于您提供的输入中缺少具体的OpenAPI文档内容(`openApiSpec`为空),我将基于一个假设的RESTful API规范来生成TypeScript+Axios的前端SDK。以下是完整输出: --- # SDK Generation Overview - **Target**: Frontend TypeScript SDK - **HTTP Library**: Axios with interceptors - **Features**: - Type-safe API calls - Custom error handling - Request/Response interceptors - Auto-inject JWT tokens # SDK Directory Structure ``` /src /api ├── client.ts # Axios instance & core setup ├── error.ts # Custom error classes ├── models.ts # Type definitions ├── auth.interceptor.ts # Auth token injector └── apis/ # Generated API modules ├── petApi.ts # Example resource module └── storeApi.ts # Example resource module ``` # Core SDK Code Files ## 1. `client.ts` (Axios基础配置) ```typescript import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'; import { ApiError, NotFoundError, AuthError } from './error'; import { setupAuthInterceptor } from './auth.interceptor'; const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'https://api.example.com'; const instance: AxiosInstance = axios.create({ baseURL: BASE_URL, timeout: 10000, headers: { 'Content-Type': 'application/json', }, }); // Error interceptor instance.interceptors.response.use( (response) => response, (error) => { if (error.response) { const { status, data } = error.response; const message = data?.message || 'API request failed'; switch (status) { case 401: throw new AuthError(message); case 404: throw new NotFoundError(message); default: throw new ApiError(message, status); } } throw new ApiError('Network error', 0); } ); // Setup auth interceptor setupAuthInterceptor(instance); export default instance; ``` ## 2. `error.ts` (自定义错误处理) ```typescript export class ApiError extends Error { constructor( public message: string, public statusCode: number, public details?: any ) { super(message); Object.setPrototypeOf(this, ApiError.prototype); } } export class NotFoundError extends ApiError { constructor(message = 'Resource not found') { super(message, 404); Object.setPrototypeOf(this, NotFoundError.prototype); } } export class AuthError extends ApiError { constructor(message = 'Authentication failed') { super(message, 401); Object.setPrototypeOf(this, AuthError.prototype); } } ``` ## 3. `auth.interceptor.ts` (JWT注入) ```typescript import { AxiosInstance } from 'axios'; export function setupAuthInterceptor(instance: AxiosInstance) { instance.interceptors.request.use((config) => { const token = localStorage.getItem('authToken'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); } ``` ## 4. `apis/petApi.ts` (示例API模块) ```typescript import client from '../client'; import type { Pet, ApiResponse } from '../models'; export const petApi = { /** * Get pet by ID * @param petId ID of pet to return * @throws {NotFoundError} When pet not found */ getPetById: async (petId: number): Promise<Pet> => { const res = await client.get<Pet>(`/pets/${petId}`); return res.data; }, /** * Add a new pet * @param pet Pet object that needs to be added */ addPet: async (pet: Omit<Pet, 'id'>): Promise<ApiResponse> => { const res = await client.post<ApiResponse>('/pets', pet); return res.data; }, // ...其他方法 }; ``` # Usage Example ## 基本调用 ```typescript import { petApi } from './api/apis/petApi'; async function fetchPet() { try { const pet = await petApi.getPetById(123); console.log('Pet data:', pet); } catch (error) { if (error instanceof NotFoundError) { alert('Pet not found!'); } else { console.error('API error:', error.message); } } } ``` ## 带认证的请求 ```typescript // 登录后存储token localStorage.setItem('authToken', 'your_jwt_token'); // 后续请求会自动携带Authorization头 await petApi.addPet({ name: 'Fluffy', category: 'cat' }); ``` ## 错误处理 ```typescript import { ApiError, AuthError } from './api/error'; try { // API调用... } catch (err) { if (err instanceof AuthError) { // 跳转到登录页 } else if (err instanceof ApiError) { // 显示通用错误提示 alert(`Error ${err.statusCode}: ${err.message}`); } } ``` --- 如需生成针对您具体API规范的SDK,请提供完整的OpenAPI文档内容。以上示例展示了基于TypeScript+Axios的最佳实践实现,包含: 1. 强类型接口定义 2. 模块化API组织 3. 集中式错误处理 4. 自动化的JWT注入 5. 可扩展的拦截器机制

模型名称 模型提供商 响应总时长(s) 生成 token 数 首 token 延迟(s) 生成速率(tokens/s)
15.32
响应最快
0
2.26
0
16.67
696
0.47
延迟最小
41.76
23.97
1314
内容最多
2.76
54.83
速度最快
58.69
1239
2.29
21.11
AI文本生成
38家服务商提供服务
AI深度推理
11家服务商提供服务
AI代码生成
11家服务商提供服务
AI数学模型
10家服务商提供服务