Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/generating-api-sdks

@820dfc8
Run it yourself

Generate client SDKs in multiple languages from OpenAPI specifications. Use when generating client libraries for API consumption. Trigger with phrases like "generate SDK", "create client library", or "build API SDK".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/generating-api-sdks

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesexamples.md

≈1.7k tokens on demand. Your agent reads this file only when SKILL.md points to it.

API SDK Generation Examples

Generated TypeScript SDK Client

// sdk/typescript/src/client.ts
export class APIClient {
  private baseUrl: string;
  private token: string;
  private maxRetries: number;

  constructor(config: { baseUrl: string; token: string; maxRetries?: number }) {
    this.baseUrl = config.baseUrl;
    this.token = config.token;
    this.maxRetries = config.maxRetries ?? 3;
  }

  private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
    for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
      const res = await fetch(`${this.baseUrl}${path}`, {
        method,
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json',
        },
        body: body ? JSON.stringify(body) : undefined,
      });

      if (res.status === 429 || res.status >= 500) {
        if (attempt < this.maxRetries) {
          const delay = Math.pow(2, attempt) * 1000;
          await new Promise(r => setTimeout(r, delay));
          continue;
        }
      }

      if (!res.ok) {
        const error = await res.json();
        throw new APIError(res.status, error.detail || 'Request failed');
      }
      return res.json() as T;
    }
    throw new APIError(500, 'Max retries exceeded');
  }

  async listUsers(params?: { page?: number; limit?: number }): Promise<UserListResponse> {
    const query = new URLSearchParams();
    if (params?.page) query.set('page', String(params.page));
    if (params?.limit) query.set('limit', String(params.limit));
    return this.request('GET', `/users?${query}`);
  }

  async getUser(id: string): Promise<User> {
    return this.request('GET', `/users/${id}`);
  }

  async createUser(data: CreateUserRequest): Promise<User> {
    return this.request('POST', '/users', data);
  }

  async deleteUser(id: string): Promise<void> {
    await this.request('DELETE', `/users/${id}`);
  }

  async *listAllUsers(pageSize = 20): AsyncGenerator<User> {
    let page = 1;
    while (true) {
      const res = await this.listUsers({ page, limit: pageSize });
      for (const user of res.data) yield user;
      if (res.data.length < pageSize) break;
      page++;
    }
  }
}

TypeScript Type Definitions

// sdk/typescript/src/models/user.ts
export interface User {
  id: string;
  name: string;
  email: string;
  status: 'active' | 'inactive' | 'suspended';
  createdAt: string;
}

export interface CreateUserRequest {
  name: string;
  email: string;
  role?: 'user' | 'admin';
}

export interface UserListResponse {
  data: User[];
  pagination: { page: number; limit: number; total: number };
}

export class APIError extends Error {
  constructor(public status: number, message: string) {
    super(message);
    this.name = 'APIError';
  }
}

SDK Usage (TypeScript)

const client = new APIClient({
  baseUrl: 'https://api.example.com',
  token: 'sk_live_abc123',
});

// List users
const users = await client.listUsers({ page: 1, limit: 20 });
console.log(users.pagination.total);

// Create user
const user = await client.createUser({ name: 'Alice', email: 'alice@example.com' });

// Paginate all users with async iterator
for await (const user of client.listAllUsers()) {
  console.log(user.name);
}

Python SDK with Async Support

# sdk/python/client.py
import httpx
from dataclasses import dataclass
from typing import AsyncIterator, Optional

@dataclass
class User:
    id: str
    name: str
    email: str
    status: str
    created_at: str

class APIClient:
    def __init__(self, base_url: str, token: str, max_retries: int = 3):
        self.base_url = base_url
        self.token = token
        self.max_retries = max_retries

    def _headers(self):
        return {"Authorization": f"Bearer {self.token}"}

    def list_users(self, page: int = 1, limit: int = 20) -> dict:
        resp = httpx.get(f"{self.base_url}/users",
            params={"page": page, "limit": limit}, headers=self._headers())
        resp.raise_for_status()
        return resp.json()

    def create_user(self, name: str, email: str, role: str = "user") -> User:
        resp = httpx.post(f"{self.base_url}/users",
            json={"name": name, "email": email, "role": role}, headers=self._headers())
        resp.raise_for_status()
        data = resp.json()
        return User(**data)

    def get_user(self, user_id: str) -> User:
        resp = httpx.get(f"{self.base_url}/users/{user_id}", headers=self._headers())
        resp.raise_for_status()
        return User(**resp.json())

class AsyncAPIClient:
    def __init__(self, base_url: str, token: str):
        self.client = httpx.AsyncClient(
            base_url=base_url, headers={"Authorization": f"Bearer {token}"})

    async def list_users(self, page: int = 1) -> dict:
        resp = await self.client.get("/users", params={"page": page})
        resp.raise_for_status()
        return resp.json()

    async def iter_all_users(self, page_size: int = 20) -> AsyncIterator[User]:
        page = 1
        while True:
            data = await self.list_users(page)
            for u in data["data"]:
                yield User(**u)
            if len(data["data"]) < page_size:
                break
            page += 1

SDK Generation with OpenAPI Generator

# Generate TypeScript SDK
npx openapi-generator-cli generate \
  -i openapi.yaml -g typescript-fetch \
  -o sdk/typescript --additional-properties=supportsES6=true

# Generate Python SDK
npx openapi-generator-cli generate \
  -i openapi.yaml -g python \
  -o sdk/python --additional-properties=packageName=myapi_client

# Validate generated SDK against mock server
cd sdk/typescript && npm test
cd sdk/python && pytest

SDK Test Against Mock

describe('SDK', () => {
  const client = new APIClient({ baseUrl: 'http://localhost:4010', token: 'test' });

  it('lists users', async () => {
    const result = await client.listUsers();
    expect(result.data.length).toBeGreaterThan(0);
    expect(result.pagination.page).toBe(1);
  });

  it('creates user', async () => {
    const user = await client.createUser({ name: 'Test', email: 'test@example.com' });
    expect(user.id).toMatch(/^usr_/);
  });

  it('retries on 429', async () => {
    // Mock returns 429 first, then 200
    const user = await client.getUser('usr_test');
    expect(user.id).toBe('usr_test');
  });

  it('paginates all users', async () => {
    const all = [];
    for await (const user of client.listAllUsers(5)) {
      all.push(user);
    }
    expect(all.length).toBeGreaterThan(5);
  });
});

Tons of Skills by Intent Solutions | jeremylongshore.com

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill generates client SDKs from OpenAPI specifications. It involves downloading standard generation tools and executing tests on generated code. Users should ensure that OpenAPI specifications provided to the skill are from trusted sources, as malicious content in the specification could influence the agent's behavior.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 820dfc8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated last month
What it can do
Reads files Edits files Runs commands
version
1.23.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
[
  "api",
  "api-sdks"
]
All 6 allowed tools
ReadWriteEditGrepGlobBash(api:sdk-*)
Other metadata
compatibility
Designed for Claude Code

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/generating-api-sdks