在過去兩天中,我們完成了 OpenAPI 3.0 規格定義,並透過 AI 產生了逼真的 Mock Data。合約有了、假資料有了,接下來前端工程師最核心的工作就是——「將 API 真正串接進前端系統」。
在傳統的前端開發流程中,撰寫 API 請求代碼是一件重複且容易出錯的勞動:
一旦後端欄位改了名字(例如 user_id 改成 userId),前端只要漏改一個地方,在運行時就會悄悄產生 undefined。今天我們就來示範:如何讓 ChatGPT 扮演全端串接助手,直接讀取 OpenAPI 規格,全自動產出具備強型別約束(Type-safe)的 Axios 請求模組!
想要讓 AI 產出直接能在 Vue 3 / React 專案中開箱即用的 API 模組,請使用以下結構化模板:
【API Client 生成提示詞範本】
請扮演資深前端架構師。請依據以下 OpenAPI 規格或後端端點說明,產出標準的 TypeScript + Axios 請求模組:
[貼上 OpenAPI YAML / JSON 或端點定義]
生成要求如下:
假設我們後端提供了以下兩個標準端點:
將 OpenAPI 規格提供給 AI 後,生成的 TypeScript 代碼結構極其嚴謹:
[AI 生成的 TypeScript 請求模組:productApi.ts]
import axios from 'axios';
// 1. 建立共用 Axios 實例(支援統一 BaseURL 與 Token 攔截)
export const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || 'https://api.example.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// 2. TypeScript 型別定義
export interface ProductItem {
productId: string;
title: string;
description: string | null;
price: number;
stock: number;
tags: string[];
imageUrl: string | null;
discountRate: number | null;
}
export interface GetProductsQuery {
page?: number;
pageSize?: number;
keyword?: string;
categoryId?: string;
}
export interface ProductListResponse {
items: ProductItem[];
total: number;
currentPage: number;
totalPages: number;
}
export interface CreateProductPayload {
title: string;
description?: string;
price: number;
stock: number;
tags?: string[];
imageUrl?: string;
discountRate?: number;
}
// 3. API 請求函式封裝
/**
* 查詢商品列表(支援分頁與多條件篩選)
* @param query 查詢條件參數
* @returns 商品分頁列表資料
*/
export async function getProductList(query?: GetProductsQuery): Promise<ProductListResponse> {
const response = await apiClient.get<ProductListResponse>('/api/v1/products', {
params: query,
});
return response.data;
}
/**
* 建立全新商品
* @param payload 商品建立資料
* @returns 建立成功後的商品完整資訊
*/
export async function createProduct(payload: CreateProductPayload): Promise<ProductItem> {
const response = await apiClient.post<ProductItem>('/api/v1/products', payload);
return response.data;
}
產出上述模組後,前端工程師在元件內部調用時,將享受到極致的型別防禦體驗:
[Vue 3 <script setup> 調用範例]
import { ref, onMounted } from 'vue';
import { getProductList, type ProductItem } from '@/api/productApi';
const products = ref<ProductItem[]>([]);
const isLoading = ref<boolean>(false);
const errorMessage = ref<string>('');
async function loadData() {
isLoading.value = true;
errorMessage.value = '';
try {
const res = await getProductList({ page: 1, pageSize: 10, keyword: '辦公椅' });
products.value = res.items;
} catch (err: any) {
errorMessage.value = err?.response?.data?.message || '資料載入失敗,請稍後再試';
} finally {
isLoading.value = false;
}
}
onMounted(() => {
loadData();
});
當工程師在 VS Code 中鍵入 res.items[0]. 時,IDE 會自動跳出 price、title、stock 等補全建議,完全不需要切換視窗對照 API 文件!
今天我們示範了如何利用 AI 解析 API 規格書,全自動產出兼具強型別保障與乾淨架構的 TypeScript + Axios 串接模組,大幅消除了手刻請求函式的人為失誤。