navan-sdk-patterns
Build a typed API wrapper around Navan REST endpoints since no official SDK exists. Use when you need production-grade API access with auto token refresh, retry logic, and typed responses. Trigger with "navan sdk patterns", "navan api wrapper", "navan client class", "navan typed client".
What this skill does
# Navan SDK Patterns
## Overview
Build a typed API wrapper around Navan REST endpoints since no official SDK exists (`@navan/sdk` is not a real package). These patterns provide automatic token lifecycle management, typed responses, retry middleware, and centralized error handling.
**Purpose:** Create a reusable NavanAPI class encapsulating authentication, request handling, and error recovery.
## Prerequisites
- Completed `navan-install-auth` with working OAuth 2.0 credentials
- TypeScript 5+ project with `dotenv` installed
- Familiarity with the Navan endpoints from `navan-hello-world`
## Instructions
### Step 1: Define Response Interfaces
Type the known API response shapes so every call returns structured data:
```typescript
// navan-types.ts
export interface NavanTrip {
uuid: string;
traveler_name: string;
origin: string;
destination: string;
departure_date: string;
return_date: string;
booking_status: string;
booking_type: 'flight' | 'hotel' | 'car';
}
export interface NavanUser {
id: string;
email: string;
first_name: string;
last_name: string;
department: string;
role: string;
}
export interface NavanApiError {
status: number;
message: string;
endpoint: string;
timestamp: string;
}
```
### Step 2: Build the NavanAPI Wrapper Class
Create a singleton client with automatic token management:
```typescript
// navan-client.ts
import 'dotenv/config';
import type { NavanTrip, NavanUser, NavanApiError } from './navan-types';
export class NavanAPI {
private baseUrl: string;
private clientId: string;
private clientSecret: string;
private accessToken: string | null = null;
private tokenExpiry: number = 0;
constructor() {
this.baseUrl = process.env.NAVAN_BASE_URL ?? 'https://api.navan.com';
this.clientId = process.env.NAVAN_CLIENT_ID ?? '';
this.clientSecret = process.env.NAVAN_CLIENT_SECRET ?? '';
if (!this.clientId || !this.clientSecret) {
throw new Error('NAVAN_CLIENT_ID and NAVAN_CLIENT_SECRET must be set');
}
}
/** Acquire or refresh the OAuth 2.0 bearer token */
private async authenticate(): Promise<string> {
if (this.accessToken && Date.now() < this.tokenExpiry) {
return this.accessToken;
}
const response = await fetch(`${this.baseUrl}/ta-auth/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: this.clientId,
client_secret: this.clientSecret,
}),
});
if (!response.ok) {
throw this.toApiError(response.status, 'Authentication failed', '/ta-auth/oauth/token');
}
const data = await response.json();
this.accessToken = data.access_token;
// Buffer 60 seconds before actual expiry
this.tokenExpiry = Date.now() + (data.expires_in - 60) * 1000;
return this.accessToken!;
}
/** Core request method with auth, retries, and error handling */
private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
const token = await this.authenticate();
const url = `${this.baseUrl}${endpoint}`;
for (let attempt = 0; attempt < 3; attempt++) {
const response = await fetch(url, {
...options,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (response.ok) return response.json() as Promise<T>;
// Retry on 429 (rate limit) and 503 (maintenance)
if ((response.status === 429 || response.status === 503) && attempt < 2) {
const delay = Math.pow(2, attempt + 1) * 1000; // 2s, 4s
await new Promise((r) => setTimeout(r, delay));
continue;
}
// Re-auth on 401 (expired token)
if (response.status === 401 && attempt < 2) {
this.accessToken = null;
this.tokenExpiry = 0;
continue;
}
throw this.toApiError(response.status, await response.text(), endpoint);
}
throw this.toApiError(0, 'Max retries exceeded', endpoint);
}
private toApiError(status: number, message: string, endpoint: string): NavanApiError {
return { status, message, endpoint, timestamp: new Date().toISOString() };
}
// --- Public API methods ---
async getBookings(page = 0, size = 50): Promise<NavanTrip[]> {
const data = await this.request<{ data: NavanTrip[] }>(`/v1/bookings?page=${page}&size=${size}`);
return data.data ?? [];
}
async getUsers(): Promise<NavanUser[]> {
const data = await this.request<{ data: NavanUser[] }>('/v1/users');
return data.data ?? [];
}
}
```
### Step 3: Implement a Singleton Factory
Ensure one client instance per process to reuse the token:
```typescript
// navan-singleton.ts
import { NavanAPI } from './navan-client';
let instance: NavanAPI | null = null;
export function getNavanClient(): NavanAPI {
if (!instance) instance = new NavanAPI();
return instance;
}
// Usage
const navan = getNavanClient();
const bookings = await navan.getBookings();
const users = await navan.getUsers();
```
### Step 4: Add Error Handling Middleware
Wrap API calls with structured error handling for calling code:
```typescript
// navan-safe.ts
import type { NavanApiError } from './navan-types';
type Result<T> = { ok: true; data: T } | { ok: false; error: NavanApiError };
export async function safeCall<T>(fn: () => Promise<T>): Promise<Result<T>> {
try {
const data = await fn();
return { ok: true, data };
} catch (err) {
const apiError = err as NavanApiError;
console.error(`Navan API error [${apiError.status}] ${apiError.endpoint}: ${apiError.message}`);
return { ok: false, error: apiError };
}
}
// Usage
const result = await safeCall(() => navan.getUserTrips());
if (result.ok) {
console.log(`Found ${result.data.length} trips`);
} else {
console.error(`Failed: ${result.error.message}`);
}
```
### Step 5: Python Equivalent Pattern
```python
# navan_client.py
import os
import time
import requests
from dataclasses import dataclass
from dotenv import load_dotenv
load_dotenv()
@dataclass
class NavanAPIError(Exception):
status: int
message: str
endpoint: str
class NavanAPI:
def __init__(self):
self.base_url = os.environ.get("NAVAN_BASE_URL", "https://api.navan.com")
self.client_id = os.environ["NAVAN_CLIENT_ID"]
self.client_secret = os.environ["NAVAN_CLIENT_SECRET"]
self._token: str | None = None
self._token_expiry: float = 0
def _authenticate(self) -> str:
if self._token and time.time() < self._token_expiry:
return self._token
resp = requests.post(f"{self.base_url}/ta-auth/oauth/token", data={
"grant_type": "client_credentials",
"client_id": self.client_id,
"client_secret": self.client_secret,
})
resp.raise_for_status()
data = resp.json()
self._token = data["access_token"]
self._token_expiry = time.time() + data.get("expires_in", 3600) - 60
return self._token
def _request(self, method: str, endpoint: str, **kwargs) -> dict:
token = self._authenticate()
for attempt in range(3):
resp = requests.request(method, f"{self.base_url}{endpoint}",
headers={"Authorization": f"Bearer {token}"}, **kwargs)
if resp.ok:
return resp.json()
if resp.status_code in (429, 503) and attempt < 2:
time.sleep(2 ** (attempt + 1))
continue
if resp.status_code == 401 and attempt < 2:
self._token = None
token = self._authenticate()
continue
raise NavanAPIError(resp.status_code, resp.text, endpoint)
raise NavanAPIError(0, "Max retries exceeded", endpoint)
def get_bookings(self, page: int = 0, size: int = 50) -> list[dRelated 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.