home / skills / ntaksh42 / agents / rest-client-generator

rest-client-generator skill

/.claude/skills/rest-client-generator

This skill generates REST API client code in multiple languages with error handling for API client libraries and SDKs.

npx playbooks add skill ntaksh42/agents --skill rest-client-generator

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
3.0 KB
---
name: rest-client-generator
description: Generate REST API client code in multiple languages with error handling. Use when creating API client libraries or SDK code.
---

# REST Client Generator Skill

REST API クライアントコードを生成するスキルです。

## 主な機能

- **Axios クライアント**: JavaScript/TypeScript
- **Fetch API**: モダンJavaScript
- **Requests**: Python
- **HTTPClient**: Java

## Axios (TypeScript)

```typescript
import axios, { AxiosInstance } from 'axios';

class UserAPI {
  private client: AxiosInstance;

  constructor(baseURL: string) {
    this.client = axios.create({
      baseURL,
      timeout: 5000,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    this.setupInterceptors();
  }

  private setupInterceptors() {
    this.client.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('token');
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      }
    );

    this.client.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response?.status === 401) {
          // Handle unauthorized
        }
        return Promise.reject(error);
      }
    );
  }

  async getUsers(): Promise<User[]> {
    const { data } = await this.client.get('/users');
    return data;
  }

  async createUser(user: CreateUserDTO): Promise<User> {
    const { data } = await this.client.post('/users', user);
    return data;
  }

  async updateUser(id: string, user: UpdateUserDTO): Promise<User> {
    const { data } = await this.client.put(`/users/${id}`, user);
    return data;
  }

  async deleteUser(id: string): Promise<void> {
    await this.client.delete(`/users/${id}`);
  }
}

export const userAPI = new UserAPI('https://api.example.com');
```

## Python (requests)

```python
import requests
from typing import List, Optional

class UserAPI:
    def __init__(self, base_url: str, api_key: str):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        })

    def get_users(self) -> List[dict]:
        response = self.session.get(f'{self.base_url}/users')
        response.raise_for_status()
        return response.json()

    def create_user(self, user_data: dict) -> dict:
        response = self.session.post(
            f'{self.base_url}/users',
            json=user_data
        )
        response.raise_for_status()
        return response.json()

    def update_user(self, user_id: str, user_data: dict) -> dict:
        response = self.session.put(
            f'{self.base_url}/users/{user_id}',
            json=user_data
        )
        response.raise_for_status()
        return response.json()

    def delete_user(self, user_id: str) -> None:
        response = self.session.delete(f'{self.base_url}/users/{user_id}')
        response.raise_for_status()
```

## バージョン情報
- Version: 1.0.0

Overview

This skill generates ready-to-use REST API client libraries in multiple languages with built-in error handling and common configuration. It produces idiomatic code for Axios (TypeScript/JavaScript), Fetch (modern JavaScript), Python requests, and Java HTTP clients to accelerate SDK or client library development. The output focuses on authentication hooks, retries, timeouts, and clear request/response patterns.

How this skill works

The generator inspects a provided API surface (endpoints, methods, schemas, and auth requirements) and emits language-specific client classes or modules. Each client includes configuration for base URL, headers, timeouts, and error handling plus helpers for common operations (GET/POST/PUT/DELETE). It can add interceptors or middleware for auth tokens, response mapping, and status-based error handling.

When to use it

  • Bootstrapping SDKs for public or internal APIs
  • Creating language-specific client libraries for microservices
  • Generating sample client code for API documentation
  • Rapid prototyping of client implementations for front-end or backend teams
  • Standardizing API access patterns across projects

Best practices

  • Provide a clear API specification (OpenAPI/Swagger or endpoint list) to generate accurate clients
  • Prefer typed outputs (TypeScript types or Pydantic models) when schemas are available
  • Wire a single auth strategy centrally (interceptor/middleware) to avoid duplicating token logic
  • Add retries and exponential backoff for idempotent requests and network instability
  • Review and customize generated error mapping to align with your API’s error model

Example use cases

  • Generate a TypeScript Axios SDK with interceptors for token refresh and typed DTOs
  • Produce a Python requests client for backend services with session reuse and raise_for_status handling
  • Create a Fetch-based JavaScript client for single-page apps with centralized timeout and JSON parsing
  • Output a Java HTTP client wrapper for microservices with configurable timeouts and status handling
  • Quickly scaffold client code for API demos, tests, or documentation samples

FAQ

Which languages and HTTP libraries are supported?

Supported outputs include Axios (TypeScript/JavaScript), Fetch (modern JavaScript), Python using requests, and a Java HTTPClient wrapper.

Does the generated code handle authentication and retries?

Yes. Clients include hooks for auth (headers or token interceptors) and can include retry/backoff logic for idempotent calls; these behaviors are configurable in the generated code.