API Integration Auto-Generation
Engineering Delivery Boundary
Follow Engineering Boundary Protocol.
- Project first: inspect existing framework, router, state management, component library, styling, API client, and test stack before writing code; inherit by default.
- Design-system first: existing design system, component library, and brand rules override visual_policy unless the user explicitly asks to change them.
- Write scope: declare target directories and files before implementation; do not overwrite unrelated user code.
- Responsive acceptance: check desktop/mobile layout, text overflow, cramped controls, nested cards, accessibility basics, and design-token consistency.
- Verification record: report created/modified files, checks run, checks that could not run, and residual risks.
Code Write Boundary
Follow Engineering Boundary Protocol.
- Scan first: identify existing HTTP client, API directory structure, authentication mechanism, and data fetching library before writing code; inherit by default.
- Target scope: declare target directories and files before implementation; generated code must stay inside {project_dir}/src/api/ unless integration files are explicitly required.
- No overwrite: preserve existing API functions, type definitions, and mock data unless the user explicitly asks for replacement; when replacing page-builder fallback, maintain function signatures.
- Type safety: all request parameters and responses must have TypeScript types derived from API contracts; zero any types.
- Fallback replacement: when replacing page-builder fallback data layer, preserve type definitions (types.ts), only replace data fetch functions and mock data.
- Implementation report: list created/modified files, skipped files, checks run, failed checks, and residual risks.
Core Principles
- Contract-Driven -- API client code auto-generated from contracts, no hand-written request functions. When contracts are missing, infer from page data flows, but inference results must be human-confirmed
- Type Safety -- Request parameters and response types 100% derived from contracts, zero any types
- Defensive Programming -- Every API call has error handling, timeout, and retry; error handling strategy defined in layers
- Built-in Authentication -- Token management, refresh, expiration handling as infrastructure, never missed
- Developer Experience -- Mock data auto-generated, frontend and backend can develop in parallel, one-click switch between mock and real APIs
Interaction Mode
AI->Human AI suggests, human confirms
Input
| Input Item |
Type |
Required |
Source |
Description |
| API Contract |
YAML/JSON |
O |
output/backend-api-design/api-design-spec/openapi.yaml |
OpenAPI 3.0 specification (infer from page data flows when missing) |
| Authentication Scheme |
JSON |
O |
output/backend-api-design/api-design-spec/auth-scheme.json |
Backend API authentication design (JWT/OAuth2/SSO scheme, permission model, session management), takes priority over PRD non-functional requirements |
| Security Policy |
JSON |
O |
output/backend-api-design/api-design-spec/security-policy.json |
Backend API security policy (rate limiting rules, CORS policy, data masking rules), for frontend error handling and security policy alignment |
| Page Data Flows |
JSON |
Yes |
output/ui-frontend/page-builder/pages.json |
Page data fetching requirements |
| Target Framework |
string |
Yes |
Passed from upstream orchestrator |
React/Vue/Svelte |
| Target Language |
string |
O |
Passed from upstream orchestrator (default zh-CN) |
Target interface language, affects mock data and error message language |
| project_dir |
string |
Yes |
Passed from upstream orchestrator |
Project root directory absolute path |
| Auth Scheme |
string |
O |
PRD non-functional requirements / User provided |
JWT/OAuth2/Cookie/ApiKey (default JWT), used when auth-scheme.json is unavailable |
Execution Steps
Step 1: API Contract Parsing and Endpoint Planning
1a. Contract Parsing
If API contract input exists:
- Parse OpenAPI/Swagger specification, extract all endpoints (method/path/parameters/requestBody/responses)
- Extract authentication schemes (security schemes)
- Extract common error code definitions
- Mark deprecated endpoints
If API contract is missing:
- Infer API endpoints from pages.json data_flow fields
- Inference rule: each data_flow source corresponds to one API endpoint
- Inferred endpoints marked with
inferred: true
- Generate inference report, requires human confirmation
1b. Endpoint Classification and Directory Planning
| Classification Rule |
Directory Structure |
Example |
| By domain module |
src/api/{module}/ |
src/api/auth/, src/api/user/, src/api/product/ |
| Common endpoints |
src/api/shared/ |
Health check, config endpoints |
| Endpoints <=5 |
Single file src/api/index.ts |
Small projects without module separation |
1c. Authentication Scheme Planning
| Auth Type |
Implementation Strategy |
Token Storage |
| JWT |
Axios interceptor auto-inject Authorization header |
localStorage + memory cache |
| OAuth2 |
Authorization code flow + PKCE |
localStorage + memory cache |
| Cookie |
withCredentials configuration |
Browser auto-managed |
| ApiKey |
Request header/query parameter injection |
Environment variables |
Token refresh strategy:
- Auto-refresh 5 minutes before expiration (based on exp claim)
- Refresh failure -> redirect to login page
- Concurrent requests queue while refresh is in progress
Step 2: API Client Code Generation
2a. Type Definition Generation
Derive TypeScript types from contract schema:
type {Endpoint}Request = { /* derived from requestBody */ }
type {Endpoint}Response = { /* derived from 200 response schema */ }
type {Endpoint}Error = { /* derived from 4xx/5xx response schema */ }
type ApiResponse<T> = { code: number; data: T; message: string }
type PaginatedResponse<T> = { items: T[]; total: number; page: number; page_size: number }
2b. Request Function Generation
Generate one request function per endpoint:
export async function {endpointName}(params: {Endpoint}Request, config?: RequestConfig): Promise<{Endpoint}Response> {
return request.{method}<{Endpoint}Response>('{path}', params, config)
}
Generation rules:
- GET request parameters mapped as query parameters
- POST/PUT/PATCH request parameters mapped as request body
- Path parameters (e.g. /users/{id}) extracted from params
- Each function includes JSDoc comments (extracted from contract description/summary)
2c. Request Layer Infrastructure
| Infrastructure |
Implementation Content |
| HTTP Client |
Axios instance (React/Vue) or fetch wrapper (Svelte) |
| Request Interceptor |
Token injection + request ID + timestamp + request body serialization |
| Response Interceptor |
Unified error handling + token expiration auto-refresh + response unwrapping |
| Error Handling |
Network error/timeout(10s)/business error/auth expiration layered handling |
| Retry Strategy |
Network errors and 5xx retry 2 times, exponential backoff (1s/2s) |
| Cancellation Mechanism |
AbortController wrapper, auto-cancel on page unmount |
| Request Deduplication |
Merge concurrent requests with same URL+parameters |
2d. Error Handling Strategy
| Error Type |
Handling Method |
User Feedback |
| Network error |
Retry 2 times -> prompt network exception |
"Network connection error, please check your network and retry" |
| Timeout (>10s) |
Retry 1 time -> prompt response timeout |
"Request timed out, please try again later" |
| 401 Unauthorized |
Attempt token refresh -> redirect to login |
Auto-redirect to login page |
| 403 Forbidden |
Prompt no permission |
"You do not have permission to perform this action" |
| 404 Not Found |
Prompt resource not found |
"Requested resource not found" |
| 422 Validation Failed |
Extract field errors |
Display specific field error messages |
| 429 Rate Limited |
Wait then retry |
"Too many requests, please try again later" |
| 5xx Server Error |
Retry 2 times -> prompt server exception |
"Server error, please try again later" |
Step 3: Mock Data and Parallel Development
3a. Mock Data Generation
Generate mock data from contract response schema:
- String type: Infer content from field name (name->"John Doe", email->"test@example.com")
- Number type: Generate based on range constraints, use reasonable defaults when no constraints
- Array type: Generate 3-5 records
- Nested objects: Generate recursively
- Enum type: Randomly select one value
- When target language != en-US, mock data uses target language content
3b. Mock Switch Mechanism
export const useMock = import.meta.env.VITE_API_MOCK === 'true'
export async function getUser(id: string) {
if (useMock) return mockData.user
return request.get(`/users/${id}`)
}
3c. MSW Integration (Recommended)
Generate MSW (Mock Service Worker) handlers:
- One handler per endpoint
- Support request parameter matching
- Support delay simulation (200-500ms random delay)
- Support error scenario simulation (5% probability of returning 500 error)
Step 4: Data Layer Integration and Cache Strategy
4a. Data Preloading Configuration
| Framework |
Solution |
Configuration |
| React |
React Query (TanStack Query) |
staleTime/cacheTime/refetchOnWindowFocus |
| Vue |
Vue Query (TanStack Query) |
staleTime/cacheTime/refetchOnWindowFocus |
| Svelte |
svelte-query |
staleTime/cacheTime/refetchOnWindowFocus |
4b. Cache Strategy
| Data Type |
staleTime |
cacheTime |
Refetch Strategy |
| User info |
5min |
30min |
Window focus |
| List data |
2min |
10min |
Window focus |
| Detail data |
10min |
30min |
No auto-refresh |
| Config data |
30min |
60min |
No auto-refresh |
| Realtime data |
0 |
5min |
Polling (5s) |
4c. Optimistic Update Configuration
Generate optimistic update configuration for write operations (POST/PUT/PATCH):
- Update operations: Immediately update cache, rollback on failure
- Delete operations: Immediately remove from cache, restore on failure
- Create operations: Immediately add to cache (temporary ID), replace with real ID on success
4d. Replace page-builder Fallback Data Layer
When api-integration executes, replace page-builder generated fallback data layer:
- Locate all files annotated with
@api-integration
- Replace fallback functions with api-integration generated request functions
- Keep function signatures consistent (page-builder fallback signatures aligned with api-integration request function signatures)
- Delete no-longer-needed mock data files
- Verify page functionality after replacement
Output
Code File Output: {project_dir}/src/api/ (API client, type definitions, mock data directly written to project directory)
Metadata Output: output/ui-frontend-integration/api-integration/
Output Files: api-integration.json
Output Schema:
{
"type": "object",
"required": ["endpoints", "types", "mock_data", "auth_config", "cache_config", "error_handling", "project_dir"],
"properties": {
"endpoints": {
"type": "array",
"description": "API endpoint list",
"items": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Function name"},
"method": {"type": "string", "enum": ["GET","POST","PUT","PATCH","DELETE"]},
"path": {"type": "string", "description": "API path"},
"request_type": {"type": "string", "description": "Request type name"},
"response_type": {"type": "string", "description": "Response type name"},
"module": {"type": "string", "description": "Module"},
"inferred": {"type": "boolean", "description": "Whether inferred endpoint"},
"deprecated": {"type": "boolean", "description": "Whether deprecated"}
}
}
},
"types": {
"type": "array",
"description": "TypeScript type definition file list",
"items": {
"type": "object",
"properties": {
"file_path": {"type": "string", "description": "Type file path"},
"type_count": {"type": "number", "description": "Number of defined types"},
"endpoints_covered": {"type": "array", "description": "Covered endpoint list"}
}
}
},
"mock_data": {
"type": "array",
"description": "Mock data file list",
"items": {
"type": "object",
"properties": {
"file_path": {"type": "string", "description": "Mock data file path"},
"endpoint": {"type": "string", "description": "Corresponding endpoint"},
"record_count": {"type": "number", "description": "Mock data record count"}
}
}
},
"auth_config": {
"type": "object",
"description": "Authentication configuration",
"properties": {
"type": {"type": "string", "enum": ["JWT","OAuth2","Cookie","ApiKey","None"]},
"token_storage": {"type": "string", "description": "Token storage method"},
"refresh_enabled": {"type": "boolean", "description": "Whether auto-refresh is enabled"},
"login_redirect": {"type": "string", "description": "Unauthorized redirect path"}
}
},
"cache_config": {
"type": "object",
"description": "Cache strategy configuration",
"properties": {
"library": {"type": "string", "description": "Data request library"},
"strategies": {
"type": "array",
"items": {
"type": "object",
"properties": {
"data_type": {"type": "string", "description": "Data type (user_info/list_data/detail_data/config_data/realtime_data)"},
"stale_time": {"type": "string", "description": "Data freshness time"},
"cache_time": {"type": "string", "description": "Cache retention time"},
"refetch_strategy": {"type": "string", "description": "Refetch strategy (window_focus/polling/none)"}
}
}
}
}
},
"error_handling": {
"type": "object",
"description": "Error handling configuration",
"properties": {
"timeout_ms": {"type": "number", "description": "Request timeout (ms)"},
"retry_count": {"type": "number", "description": "Retry count"},
"retry_delay_ms": {"type": "number", "description": "Retry delay (ms)"},
"error_codes_mapped": {"type": "number", "description": "Number of mapped error codes"},
"error_strategies": {
"type": "array",
"items": {
"type": "object",
"properties": {
"error_type": {"type": "string", "description": "Error type (network/timeout/401/403/404/422/429/5xx)"},
"handling": {"type": "string", "description": "Handling method"},
"user_feedback": {"type": "string", "description": "User feedback text"}
}
}
}
}
},
"project_dir": {"type": "string", "description": "Project root directory path"}
}
}
Decision Rules
| Condition |
Decision |
| Target framework = React |
Use React Query + axios |
| Target framework = Vue |
Use Vue Query + axios |
| Target framework = Svelte |
Use svelte-query + fetch wrapper |
| API endpoints >20 |
Split files by domain module |
| Has pagination interfaces |
Generate generic pagination Hook |
| Has file upload interfaces |
Generate progress callback wrapper |
| Target language != en-US |
Mock data uses target language content |
| Auth scheme = JWT |
Auto-generate token refresh interceptor |
| Auth scheme missing |
Default JWT, mark as "auth scheme pending confirmation" |
| Inferred endpoints >50% |
Mark as "high inference ratio, recommend supplementing API contract" |
Quality Checks
P0 (Must pass, blocks output if not):
P1 (Recommended, mark as "pending fix" if not):
Degradation Strategy
| Missing Upstream Input |
Degradation Plan |
Output Impact |
| API contract missing |
Infer API requirements from page data flows, inferred endpoints marked inferred:true |
API functions are skeletons, need human confirmation to supplement contract details |
| Page data flows missing |
Generate independent functions for all API endpoints, no page-level preloading |
Missing page-level data preloading and cache configuration |
| Auth scheme missing |
Default JWT scheme, mark as "auth scheme pending confirmation" |
Token refresh logic may need adjustment |
| Security policy missing |
Skip security policy alignment, mark as "pending security policy supplement" |
CORS/rate limiting and other frontend security policies not aligned |
| project_dir missing |
Output to output/ directory only |
Code needs manual copying |
Upstream Change Response
Upstream Change Impact Table
| Upstream Change |
Impact Scope |
Response Strategy |
| API contract change (endpoint add/remove/parameter change/response structure change/auth scheme change) |
Request functions, type definitions, mock data, auth configuration |
Mark affected endpoints and types, recommend regenerating corresponding request functions, mock data, and auth interceptors |
| Page data flow change (data fetching method/cache strategy change) |
Data preloading configuration, cache strategy, request deduplication |
Mark affected page data flows, recommend updating React Query/Vue Query/svelte-query configuration |
| Target framework change |
Request layer technology selection (React Query/Vue Query/svelte-query) |
Mark data request layer solution needing replacement, recommend regenerating |
| Auth scheme change |
Token injection/refresh/expiration handling logic |
Mark auth interceptor needing replacement, recommend regenerating auth infrastructure |
Downstream Notification Mechanism Table
| This Skill Output Change |
Notify Downstream Skill |
Notification Content |
Trigger Condition |
| API endpoint add/remove |
production-ready |
Affected tests and build configuration |
endpoints list change |
| Type definition change |
production-ready |
Affected type-related tests |
types structure change |
| Mock data change |
production-ready |
Affected test mocks |
mock_data file change |
| Request layer technology selection change |
production-ready |
Dependency and build configuration change |
Target framework or request library change |
| Auth configuration change |
production-ready |
Auth-related test and dependency change |
auth_config change |
| Cache strategy change |
production-ready |
Data layer related test change |
cache_config change |
| Error handling change |
production-ready |
Error handling related test change |
error_handling change |
1---2name: api-integration3description: "Use when integrating frontend with backend APIs. Auto-generates frontend request layer code from API contracts, including type-safe API clients, request/response interceptors, error handling, and mock data. Keywords: API integration, interface debugging, request layer, API client, frontend-backend integration, connect API, call API."4metadata:5 source: https://skillmd.com/skills/luckyonetwothree/api-integration6 module: "UI Design & Frontend Development"7 sub-module: "Frontend Integration"8 type: "pipeline"9 version: "2.0"10 domain_tags: ["Internet", "General"]11 trigger_examples:12 - "Integrate with backend API"13 - "Generate request layer code"14 - "Call API"15 interaction_mode: "ai_suggest_human_approve"16---1718# API Integration Auto-Generation1920## Engineering Delivery Boundary2122Follow [Engineering Boundary Protocol](../../../codex-templates/engineering-boundary-protocol.md).23241. Project first: inspect existing framework, router, state management, component library, styling, API client, and test stack before writing code; inherit by default.252. Design-system first: existing design system, component library, and brand rules override visual_policy unless the user explicitly asks to change them.263. Write scope: declare target directories and files before implementation; do not overwrite unrelated user code.274. Responsive acceptance: check desktop/mobile layout, text overflow, cramped controls, nested cards, accessibility basics, and design-token consistency.285. Verification record: report created/modified files, checks run, checks that could not run, and residual risks.2930## Code Write Boundary3132Follow [Engineering Boundary Protocol](../../../codex-templates/engineering-boundary-protocol.md).33341. Scan first: identify existing HTTP client, API directory structure, authentication mechanism, and data fetching library before writing code; inherit by default.352. Target scope: declare target directories and files before implementation; generated code must stay inside {project_dir}/src/api/ unless integration files are explicitly required.363. No overwrite: preserve existing API functions, type definitions, and mock data unless the user explicitly asks for replacement; when replacing page-builder fallback, maintain function signatures.374. Type safety: all request parameters and responses must have TypeScript types derived from API contracts; zero any types.385. Fallback replacement: when replacing page-builder fallback data layer, preserve type definitions (types.ts), only replace data fetch functions and mock data.396. Implementation report: list created/modified files, skipped files, checks run, failed checks, and residual risks.4041## Core Principles42431. **Contract-Driven** -- API client code auto-generated from contracts, no hand-written request functions. When contracts are missing, infer from page data flows, but inference results must be human-confirmed442. **Type Safety** -- Request parameters and response types 100% derived from contracts, zero any types453. **Defensive Programming** -- Every API call has error handling, timeout, and retry; error handling strategy defined in layers464. **Built-in Authentication** -- Token management, refresh, expiration handling as infrastructure, never missed475. **Developer Experience** -- Mock data auto-generated, frontend and backend can develop in parallel, one-click switch between mock and real APIs4849## Interaction Mode5051AI->Human AI suggests, human confirms5253## Input5455| Input Item | Type | Required | Source | Description |56|--------|------|------|------|------|57| API Contract | YAML/JSON | O | output/backend-api-design/api-design-spec/openapi.yaml | OpenAPI 3.0 specification (infer from page data flows when missing) |58| Authentication Scheme | JSON | O | output/backend-api-design/api-design-spec/auth-scheme.json | Backend API authentication design (JWT/OAuth2/SSO scheme, permission model, session management), takes priority over PRD non-functional requirements |59| Security Policy | JSON | O | output/backend-api-design/api-design-spec/security-policy.json | Backend API security policy (rate limiting rules, CORS policy, data masking rules), for frontend error handling and security policy alignment |60| Page Data Flows | JSON | Yes | output/ui-frontend/page-builder/pages.json | Page data fetching requirements |61| Target Framework | string | Yes | Passed from upstream orchestrator | React/Vue/Svelte |62| Target Language | string | O | Passed from upstream orchestrator (default zh-CN) | Target interface language, affects mock data and error message language |63| project_dir | string | Yes | Passed from upstream orchestrator | Project root directory absolute path |64| Auth Scheme | string | O | PRD non-functional requirements / User provided | JWT/OAuth2/Cookie/ApiKey (default JWT), used when auth-scheme.json is unavailable |6566## Execution Steps6768### Step 1: API Contract Parsing and Endpoint Planning6970**1a. Contract Parsing**7172If API contract input exists:731. Parse OpenAPI/Swagger specification, extract all endpoints (method/path/parameters/requestBody/responses)742. Extract authentication schemes (security schemes)753. Extract common error code definitions764. Mark deprecated endpoints7778If API contract is missing:791. Infer API endpoints from pages.json data_flow fields802. Inference rule: each data_flow source corresponds to one API endpoint813. Inferred endpoints marked with `inferred: true`824. Generate inference report, requires human confirmation8384**1b. Endpoint Classification and Directory Planning**8586| Classification Rule | Directory Structure | Example |87|---------|---------|------|88| By domain module | src/api/{module}/ | src/api/auth/, src/api/user/, src/api/product/ |89| Common endpoints | src/api/shared/ | Health check, config endpoints |90| Endpoints <=5 | Single file src/api/index.ts | Small projects without module separation |9192**1c. Authentication Scheme Planning**9394| Auth Type | Implementation Strategy | Token Storage |95|---------|---------|----------|96| JWT | Axios interceptor auto-inject Authorization header | localStorage + memory cache |97| OAuth2 | Authorization code flow + PKCE | localStorage + memory cache |98| Cookie | withCredentials configuration | Browser auto-managed |99| ApiKey | Request header/query parameter injection | Environment variables |100101Token refresh strategy:102- Auto-refresh 5 minutes before expiration (based on exp claim)103- Refresh failure -> redirect to login page104- Concurrent requests queue while refresh is in progress105106### Step 2: API Client Code Generation107108**2a. Type Definition Generation**109110Derive TypeScript types from contract schema:111112```typescript113type {Endpoint}Request = { /* derived from requestBody */ }114type {Endpoint}Response = { /* derived from 200 response schema */ }115type {Endpoint}Error = { /* derived from 4xx/5xx response schema */ }116117type ApiResponse<T> = { code: number; data: T; message: string }118type PaginatedResponse<T> = { items: T[]; total: number; page: number; page_size: number }119```120121**2b. Request Function Generation**122123Generate one request function per endpoint:124125```typescript126export async function {endpointName}(params: {Endpoint}Request, config?: RequestConfig): Promise<{Endpoint}Response> {127 return request.{method}<{Endpoint}Response>('{path}', params, config)128}129```130131Generation rules:132- GET request parameters mapped as query parameters133- POST/PUT/PATCH request parameters mapped as request body134- Path parameters (e.g. /users/{id}) extracted from params135- Each function includes JSDoc comments (extracted from contract description/summary)136137**2c. Request Layer Infrastructure**138139| Infrastructure | Implementation Content |140|---------|---------|141| HTTP Client | Axios instance (React/Vue) or fetch wrapper (Svelte) |142| Request Interceptor | Token injection + request ID + timestamp + request body serialization |143| Response Interceptor | Unified error handling + token expiration auto-refresh + response unwrapping |144| Error Handling | Network error/timeout(10s)/business error/auth expiration layered handling |145| Retry Strategy | Network errors and 5xx retry 2 times, exponential backoff (1s/2s) |146| Cancellation Mechanism | AbortController wrapper, auto-cancel on page unmount |147| Request Deduplication | Merge concurrent requests with same URL+parameters |148149**2d. Error Handling Strategy**150151| Error Type | Handling Method | User Feedback |152|---------|---------|---------|153| Network error | Retry 2 times -> prompt network exception | "Network connection error, please check your network and retry" |154| Timeout (>10s) | Retry 1 time -> prompt response timeout | "Request timed out, please try again later" |155| 401 Unauthorized | Attempt token refresh -> redirect to login | Auto-redirect to login page |156| 403 Forbidden | Prompt no permission | "You do not have permission to perform this action" |157| 404 Not Found | Prompt resource not found | "Requested resource not found" |158| 422 Validation Failed | Extract field errors | Display specific field error messages |159| 429 Rate Limited | Wait then retry | "Too many requests, please try again later" |160| 5xx Server Error | Retry 2 times -> prompt server exception | "Server error, please try again later" |161162### Step 3: Mock Data and Parallel Development163164**3a. Mock Data Generation**165166Generate mock data from contract response schema:167- String type: Infer content from field name (name->"John Doe", email->"test@example.com")168- Number type: Generate based on range constraints, use reasonable defaults when no constraints169- Array type: Generate 3-5 records170- Nested objects: Generate recursively171- Enum type: Randomly select one value172- When target language != en-US, mock data uses target language content173174**3b. Mock Switch Mechanism**175176```typescript177export const useMock = import.meta.env.VITE_API_MOCK === 'true'178179export async function getUser(id: string) {180 if (useMock) return mockData.user181 return request.get(`/users/${id}`)182}183```184185**3c. MSW Integration (Recommended)**186187Generate MSW (Mock Service Worker) handlers:188- One handler per endpoint189- Support request parameter matching190- Support delay simulation (200-500ms random delay)191- Support error scenario simulation (5% probability of returning 500 error)192193### Step 4: Data Layer Integration and Cache Strategy194195**4a. Data Preloading Configuration**196197| Framework | Solution | Configuration |198|------|------|------|199| React | React Query (TanStack Query) | staleTime/cacheTime/refetchOnWindowFocus |200| Vue | Vue Query (TanStack Query) | staleTime/cacheTime/refetchOnWindowFocus |201| Svelte | svelte-query | staleTime/cacheTime/refetchOnWindowFocus |202203**4b. Cache Strategy**204205| Data Type | staleTime | cacheTime | Refetch Strategy |206|---------|-----------|-----------|------------|207| User info | 5min | 30min | Window focus |208| List data | 2min | 10min | Window focus |209| Detail data | 10min | 30min | No auto-refresh |210| Config data | 30min | 60min | No auto-refresh |211| Realtime data | 0 | 5min | Polling (5s) |212213**4c. Optimistic Update Configuration**214215Generate optimistic update configuration for write operations (POST/PUT/PATCH):216- Update operations: Immediately update cache, rollback on failure217- Delete operations: Immediately remove from cache, restore on failure218- Create operations: Immediately add to cache (temporary ID), replace with real ID on success219220**4d. Replace page-builder Fallback Data Layer**221222When api-integration executes, replace page-builder generated fallback data layer:2231. Locate all files annotated with `@api-integration`2242. Replace fallback functions with api-integration generated request functions2253. Keep function signatures consistent (page-builder fallback signatures aligned with api-integration request function signatures)2264. Delete no-longer-needed mock data files2275. Verify page functionality after replacement228229## Output230231**Code File Output**: {project_dir}/src/api/ (API client, type definitions, mock data directly written to project directory)232233**Metadata Output**: output/ui-frontend-integration/api-integration/234235**Output Files**: api-integration.json236237**Output Schema**:238239```json240{241 "type": "object",242 "required": ["endpoints", "types", "mock_data", "auth_config", "cache_config", "error_handling", "project_dir"],243 "properties": {244 "endpoints": {245 "type": "array",246 "description": "API endpoint list",247 "items": {248 "type": "object",249 "properties": {250 "name": {"type": "string", "description": "Function name"},251 "method": {"type": "string", "enum": ["GET","POST","PUT","PATCH","DELETE"]},252 "path": {"type": "string", "description": "API path"},253 "request_type": {"type": "string", "description": "Request type name"},254 "response_type": {"type": "string", "description": "Response type name"},255 "module": {"type": "string", "description": "Module"},256 "inferred": {"type": "boolean", "description": "Whether inferred endpoint"},257 "deprecated": {"type": "boolean", "description": "Whether deprecated"}258 }259 }260 },261 "types": {262 "type": "array",263 "description": "TypeScript type definition file list",264 "items": {265 "type": "object",266 "properties": {267 "file_path": {"type": "string", "description": "Type file path"},268 "type_count": {"type": "number", "description": "Number of defined types"},269 "endpoints_covered": {"type": "array", "description": "Covered endpoint list"}270 }271 }272 },273 "mock_data": {274 "type": "array",275 "description": "Mock data file list",276 "items": {277 "type": "object",278 "properties": {279 "file_path": {"type": "string", "description": "Mock data file path"},280 "endpoint": {"type": "string", "description": "Corresponding endpoint"},281 "record_count": {"type": "number", "description": "Mock data record count"}282 }283 }284 },285 "auth_config": {286 "type": "object",287 "description": "Authentication configuration",288 "properties": {289 "type": {"type": "string", "enum": ["JWT","OAuth2","Cookie","ApiKey","None"]},290 "token_storage": {"type": "string", "description": "Token storage method"},291 "refresh_enabled": {"type": "boolean", "description": "Whether auto-refresh is enabled"},292 "login_redirect": {"type": "string", "description": "Unauthorized redirect path"}293 }294 },295 "cache_config": {296 "type": "object",297 "description": "Cache strategy configuration",298 "properties": {299 "library": {"type": "string", "description": "Data request library"},300 "strategies": {301 "type": "array",302 "items": {303 "type": "object",304 "properties": {305 "data_type": {"type": "string", "description": "Data type (user_info/list_data/detail_data/config_data/realtime_data)"},306 "stale_time": {"type": "string", "description": "Data freshness time"},307 "cache_time": {"type": "string", "description": "Cache retention time"},308 "refetch_strategy": {"type": "string", "description": "Refetch strategy (window_focus/polling/none)"}309 }310 }311 }312 }313 },314 "error_handling": {315 "type": "object",316 "description": "Error handling configuration",317 "properties": {318 "timeout_ms": {"type": "number", "description": "Request timeout (ms)"},319 "retry_count": {"type": "number", "description": "Retry count"},320 "retry_delay_ms": {"type": "number", "description": "Retry delay (ms)"},321 "error_codes_mapped": {"type": "number", "description": "Number of mapped error codes"},322 "error_strategies": {323 "type": "array",324 "items": {325 "type": "object",326 "properties": {327 "error_type": {"type": "string", "description": "Error type (network/timeout/401/403/404/422/429/5xx)"},328 "handling": {"type": "string", "description": "Handling method"},329 "user_feedback": {"type": "string", "description": "User feedback text"}330 }331 }332 }333 }334 },335 "project_dir": {"type": "string", "description": "Project root directory path"}336 }337}338```339340## Decision Rules341342| Condition | Decision |343|------|------|344| Target framework = React | Use React Query + axios |345| Target framework = Vue | Use Vue Query + axios |346| Target framework = Svelte | Use svelte-query + fetch wrapper |347| API endpoints >20 | Split files by domain module |348| Has pagination interfaces | Generate generic pagination Hook |349| Has file upload interfaces | Generate progress callback wrapper |350| Target language != en-US | Mock data uses target language content |351| Auth scheme = JWT | Auto-generate token refresh interceptor |352| Auth scheme missing | Default JWT, mark as "auth scheme pending confirmation" |353| Inferred endpoints >50% | Mark as "high inference ratio, recommend supplementing API contract" |354355## Quality Checks356357**P0 (Must pass, blocks output if not)**:358- [ ] 100% of API endpoints have corresponding request functions359- [ ] 100% of request parameters and responses have TypeScript types (zero any)360- [ ] Authentication scheme configured (token injection + refresh + expiration handling)361- [ ] Interceptor configuration complete (token injection + error handling + response unwrapping)362- [ ] API code quality audit score >=70 (called by orchestrator via ext-impeccable audit)363364**P1 (Recommended, mark as "pending fix" if not)**:365- [ ] Every API call has error handling and timeout configuration366- [ ] Mock data covers all endpoints367- [ ] Cache strategy configured (at least 3 data types)368- [ ] Optimistic updates configured (write operations)369- [ ] Inferred endpoints human-confirmed370371## Degradation Strategy372373| Missing Upstream Input | Degradation Plan | Output Impact |374|---------------|---------|---------|375| API contract missing | Infer API requirements from page data flows, inferred endpoints marked inferred:true | API functions are skeletons, need human confirmation to supplement contract details |376| Page data flows missing | Generate independent functions for all API endpoints, no page-level preloading | Missing page-level data preloading and cache configuration |377| Auth scheme missing | Default JWT scheme, mark as "auth scheme pending confirmation" | Token refresh logic may need adjustment |378| Security policy missing | Skip security policy alignment, mark as "pending security policy supplement" | CORS/rate limiting and other frontend security policies not aligned |379| project_dir missing | Output to output/ directory only | Code needs manual copying |380381## Upstream Change Response382383### Upstream Change Impact Table384385| Upstream Change | Impact Scope | Response Strategy |386|----------|----------|----------|387| API contract change (endpoint add/remove/parameter change/response structure change/auth scheme change) | Request functions, type definitions, mock data, auth configuration | Mark affected endpoints and types, recommend regenerating corresponding request functions, mock data, and auth interceptors |388| Page data flow change (data fetching method/cache strategy change) | Data preloading configuration, cache strategy, request deduplication | Mark affected page data flows, recommend updating React Query/Vue Query/svelte-query configuration |389| Target framework change | Request layer technology selection (React Query/Vue Query/svelte-query) | Mark data request layer solution needing replacement, recommend regenerating |390| Auth scheme change | Token injection/refresh/expiration handling logic | Mark auth interceptor needing replacement, recommend regenerating auth infrastructure |391392### Downstream Notification Mechanism Table393394| This Skill Output Change | Notify Downstream Skill | Notification Content | Trigger Condition |395|---------------|-------------|---------|---------|396| API endpoint add/remove | production-ready | Affected tests and build configuration | endpoints list change |397| Type definition change | production-ready | Affected type-related tests | types structure change |398| Mock data change | production-ready | Affected test mocks | mock_data file change |399| Request layer technology selection change | production-ready | Dependency and build configuration change | Target framework or request library change |400| Auth configuration change | production-ready | Auth-related test and dependency change | auth_config change |401| Cache strategy change | production-ready | Data layer related test change | cache_config change |402| Error handling change | production-ready | Error handling related test change | error_handling change |