api-client-patterns
БесплатноБез исполняемых скриптовНе проверенHTTP client patterns, API integration, request/response handling, error handling, retry logic, axios usage. Use when building API clients, integrating…
от diegosouzapw★ 68 звёзд на GitHubОб этом скилле
API Client Patterns
Core Principles
- Single Responsibility - One client per service
- Centralized Configuration - Base URL, headers, timeouts in one place
- Comprehensive Error Handling - Catch and transform errors appropriately
- Type Safety - Define request/response interfaces
- Retry Logic - Handle transient failures gracefully
API Client Structure
CORRECT: Well-Structured API Client
// client/src/utils/api.js
import axios from 'axios';
// Configuration
const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:3001/api';
const TIMEOUT = 30000; // 30 seconds
// Create axios instance with defaults
const apiClient = axios.create({
baseURL: API_BASE,
timeout: TIMEOUT,
headers: {
'Content-Type': 'application/json'
}
});
// Request interceptor (optional - for auth, logging, etc.)
apiClient.interceptors.request.use(
(config) => {
// Add auth token if available
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Response interceptor (optional - for error transformation)
apiClient.interceptors.response.use(
(response) => response,
(error) => {
// Transform errors to consistent format
const message = error.response?.data?.error || error.message || 'Unknown error';
return Promise.reject(new Error(message));
}
);
// API Methods
/**
* Verify faculty password
*/
export const verifyPassword = async (password) => {
const response = await apiClient.post('/auth/verify', { password });
return response.data;
};
/**
* Generate or update instructional page
*/
export const generatePage = async (config, message, history = []) => {
const response = await apiClient.post('/generate', {
config,
message,
history
});
return response.data;
};
/**
* Generate AI image using DALL-E
*/
export const generateImage = async (prompt) => {
const response = await apiClient.post('/images/generate', { prompt });
return response.data;
};
/**
* Upload image to Cloudinary
*/
export const uploadImage = async (file) => {
const formData = new FormData();
formData.append('image', file);
const response = await apiClient.post('/images/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
return response.data;
};
export default apiClient;
WRONG: Scattered API Calls
// ❌ DON'T DO THIS: Direct axios calls scattered across components
import axios from 'axios';
// In Component 1
const handleLogin = async () => {
const res = await axios.post('http://localhost:3001/api/auth/verify', {
password: pwd
});
};
// In Component 2
const handleGenerate = async () => {
const res = await axios.post('http://localhost:3001/api/generate', data);
};
// ❌ Issues:
// - Repeated base URL strings
// - No centralized error handling
// - No configuration reuse
// - Hard to test
Error Handling Patterns
CORRECT: Comprehensive Error Handling
// API client with error transformation
export const generatePage = async (config, message, history) => {
try {
const response = await apiClient.post('/generate', {
config,
message,
history
});
return response.data;
} catch (error) {
// Check different error types
if (error.response) {
// Server responded with error status
const status = error.response.status;
const message = error.response.data?.error || 'Server error';
if (status === 400) {
throw new Error(`Validation error: ${message}`);
} else if (status === 401) {
throw new Error('Authentication failed');
} else if (status === 429) {
throw new Error('Rate limit exceeded. Please try again later.');
} else if (status >= 500) {
throw new Error('Server error. Please try again.');
} else {
throw new Error(message);
}
} else if (error.request) {
// Request made but no response received
throw new Error('Network error. Please check your connection.');
} else {
// Something else happened
throw new Error(error.message || 'Request failed');
}
}
};
Component Error Handling
// In component
export default function ChatInterface() {
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const handleSubmit = async () => {
setLoading(true);
setError(null);
try {
const result = await generatePage(config, message, history);
// Handle success
} catch (err) {
// Error is already transformed by API client
setError(err.message);
// Optional: Report to error tracking service
console.error('Generation failed:', err);
} finally {
setLoading(false);
}
};
return (
<div>
{error && (
<div classNam
Установить api-client-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobВложенные файлы
FAQ
Что делает скилл api-client-patterns?
HTTP client patterns, API integration, request/response handling, error handling, retry logic, axios usage. Use when building API clients, integrating external services, handling API errors, or making HTTP requests.
Как установить скилл api-client-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл api-client-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic