iT邦幫忙

2026 iThome 鐵人賽

0
ChatGPT & Codex

從 Prompt Engineering 到 Copilot / Codex 實務 30 天系列 第 21 篇

Day 21:【前後端串接輔助】讓 AI 解析 API 規格書並自動產出對應的請求函式(Axios / TypeScript 代碼)

  • 分享至 

  • xImage
  •  

在過去兩天中,我們完成了 OpenAPI 3.0 規格定義,並透過 AI 產生了逼真的 Mock Data。合約有了、假資料有了,接下來前端工程師最核心的工作就是——「將 API 真正串接進前端系統」。

在傳統的前端開發流程中,撰寫 API 請求代碼是一件重複且容易出錯的勞動:

  1. 手動對照後端文件,複製貼上 Endpoint URL 與 HTTP Method。
  2. 手動定義 TypeScript 介面(Interface / Type)。
  3. 手刻 Axios 封裝、Query 參數拼裝、Request Body 與錯誤捕獲。

一旦後端欄位改了名字(例如 user_id 改成 userId),前端只要漏改一個地方,在運行時就會悄悄產生 undefined。今天我們就來示範:如何讓 ChatGPT 扮演全端串接助手,直接讀取 OpenAPI 規格,全自動產出具備強型別約束(Type-safe)的 Axios 請求模組!


一、API 請求代碼生成提示詞模板(API Client Prompting)

想要讓 AI 產出直接能在 Vue 3 / React 專案中開箱即用的 API 模組,請使用以下結構化模板:

【API Client 生成提示詞範本】
請扮演資深前端架構師。請依據以下 OpenAPI 規格或後端端點說明,產出標準的 TypeScript + Axios 請求模組:

[貼上 OpenAPI YAML / JSON 或端點定義]

生成要求如下:

  1. 嚴格型別定義:為每個 Request Query/Body 與 Response Data 定義完整的 TypeScript Interface。
  2. Axios 函式封裝:採用具名導出(Named Exports),函式命名符合語意(如 fetchUserList, createProduct)。
  3. 錯誤處理與攔截器整合:使用共用的 apiClient 實例,函式內部需具備標準的 Promise 回傳型別(Promise)。
  4. JSDoc 註解:在函式上方附帶簡要說明,標註參數型別與端點用途,方便 IDE 提供自動補全提示。

二、實戰案例:電商商品模組自動化串接

假設我們後端提供了以下兩個標準端點:

  1. GET /api/v1/products(取得商品分頁列表,支援關鍵字與分類過濾)
  2. POST /api/v1/products(建立新商品)

將 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 / React 範例)

產出上述模組後,前端工程師在元件內部調用時,將享受到極致的型別防禦體驗:

[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 文件!

四、工程師的進階反思與自動化延伸

  1. 避免「型別漂移(Type Drift)」:
    人工維護前端 Interface 最容易發生「後端改了型別,前端忘了同步更新」。利用 AI 批次轉譯,可以在每次後端更新 OpenAPI 規格後,幾秒鐘內重新生成最新的型別定義。
  2. 與 CLI 工具結合(如 openapi-typescript-codegen):
    在更大型的企業專案中,除了使用 ChatGPT 快速處理單一模組,也可以在文章中介紹開源的 CodeGen CLI 工具,讓讀者了解「AI 輔助靈活微調」與「腳本批次生成」的互補優勢。
  3. 錯誤攔截器統一處理:
    在 AI 產出的 apiClient 骨架基礎上,可追加 axios.interceptors.response 統一攔截 401(未授權跳轉登入)與 500(伺服器錯誤通知),將錯誤處理邏輯與業務組件完全抽離。

今日小結與預告

今天我們示範了如何利用 AI 解析 API 規格書,全自動產出兼具強型別保障與乾淨架構的 TypeScript + Axios 串接模組,大幅消除了手刻請求函式的人為失誤。


上一篇
Day 20:【假資料生成】前端切版免煩惱:讓 AI 生成真實感十足的結構化 Mock Data
下一篇
Day 22:【Git 協作輔助】自動撰寫 Conventional Commits 與專業 PR 摘要描述
系列文
從 Prompt Engineering 到 Copilot / Codex 實務 30 天 共 29 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言