flexport-sdk-patterns
Apply production-ready Flexport API patterns for TypeScript and Python. Use when building typed HTTP clients, implementing pagination, or establishing team coding standards for Flexport logistics integration. Trigger: "flexport SDK patterns", "flexport best practices", "flexport client wrapper".
What this skill does
# Flexport SDK Patterns
## Overview
Production-ready patterns for the Flexport REST API v2. Since Flexport has no official npm/pip SDK, you build typed HTTP clients. Key patterns: singleton client, paginated iteration, retry wrapper, and Zod response validation.
## Instructions
### Pattern 1: Singleton Client with Auto-Retry
```typescript
// src/flexport/client.ts
import { z } from 'zod';
class FlexportClient {
private static instance: FlexportClient | null = null;
private base = 'https://api.flexport.com';
private headers: Record<string, string>;
private constructor(apiKey: string) {
this.headers = {
'Authorization': `Bearer ${apiKey}`,
'Flexport-Version': '2',
'Content-Type': 'application/json',
};
}
static getInstance(): FlexportClient {
if (!this.instance) {
const key = process.env.FLEXPORT_API_KEY;
if (!key) throw new Error('Missing FLEXPORT_API_KEY');
this.instance = new FlexportClient(key);
}
return this.instance;
}
async request<T>(path: string, options: RequestInit = {}): Promise<T> {
const res = await fetch(`${this.base}${path}`, { ...options, headers: { ...this.headers, ...options.headers } });
if (res.status === 429) {
const retryAfter = parseInt(res.headers.get('Retry-After') || '60');
await new Promise(r => setTimeout(r, retryAfter * 1000));
return this.request(path, options); // Retry once
}
if (!res.ok) {
const body = await res.text();
throw new FlexportAPIError(res.status, body, path);
}
return res.json();
}
}
class FlexportAPIError extends Error {
constructor(public status: number, public body: string, public path: string) {
super(`Flexport ${status} on ${path}: ${body}`);
this.name = 'FlexportAPIError';
}
}
```
### Pattern 2: Paginated Iterator
```typescript
// Iterate all pages of a Flexport list endpoint
async function* paginate<T>(path: string, perPage = 25): AsyncGenerator<T> {
const client = FlexportClient.getInstance();
let page = 1;
while (true) {
const separator = path.includes('?') ? '&' : '?';
const res = await client.request<{ data: { records: T[]; total_count: number } }>(
`${path}${separator}page=${page}&per=${perPage}`
);
for (const record of res.data.records) yield record;
if (res.data.records.length < perPage) break;
page++;
}
}
// Usage: iterate all shipments
for await (const shipment of paginate<Shipment>('/shipments')) {
console.log(shipment.id, shipment.status);
}
```
### Pattern 3: Zod Response Validation
```typescript
const ShipmentSchema = z.object({
id: z.string(),
status: z.enum(['booked', 'in_transit', 'arrived', 'delivered']),
freight_type: z.enum(['ocean', 'air', 'trucking']),
origin_port: z.object({ code: z.string(), name: z.string() }),
destination_port: z.object({ code: z.string(), name: z.string() }),
cargo_ready_date: z.string(),
estimated_arrival_date: z.string().nullable(),
});
type Shipment = z.infer<typeof ShipmentSchema>;
async function getShipment(id: string): Promise<Shipment> {
const client = FlexportClient.getInstance();
const res = await client.request<{ data: unknown }>(`/shipments/${id}`);
return ShipmentSchema.parse(res.data); // Throws ZodError on mismatch
}
```
### Pattern 4: Python Typed Client
```python
import os, requests
from dataclasses import dataclass
from typing import Iterator
@dataclass
class Shipment:
id: str
status: str
freight_type: str
class FlexportClient:
BASE = 'https://api.flexport.com'
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {os.environ["FLEXPORT_API_KEY"]}',
'Flexport-Version': '2',
})
def list_shipments(self, per: int = 25) -> Iterator[Shipment]:
page = 1
while True:
r = self.session.get(f'{self.BASE}/shipments', params={'page': page, 'per': per})
r.raise_for_status()
records = r.json()['data']['records']
for rec in records:
yield Shipment(id=rec['id'], status=rec['status'], freight_type=rec['freight_type'])
if len(records) < per:
break
page += 1
```
## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| Singleton | All API calls | One instance, consistent config |
| Paginator | List endpoints | No data loss from pagination |
| Zod validation | Response parsing | Catches API contract changes early |
| Error class | All failures | Structured error data for logging |
## Resources
- [Flexport API Reference](https://apidocs.flexport.com/)
- [Zod Documentation](https://zod.dev/)
## Next Steps
Apply patterns in `flexport-core-workflow-a` for real-world usage.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.