> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fieldfunded.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK & Integration Guide

> Official TypeScript SDK and multi-language integration patterns for FieldFunded API

FieldFunded is built on standard REST/JSON architecture, making it compatible with every modern programming language.

<Note>
  **No SDK account required.** You only need your **API Key** (X-API-Key or X-RapidAPI-Key) to start building. The SDKs and code examples below are tools to help you use your key more efficiently.
</Note>

## Official SDKs

| Language            | Package                                                                                                 | Status          | Documentation                             |
| ------------------- | ------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------- |
| **TypeScript / JS** | [![npm](https://img.shields.io/npm/v/@fieldfunded/sdk)](https://www.npmjs.com/package/@fieldfunded/sdk) | ✅ Stable        | [View Guide](#typescript-sdk)             |
| **Python**          | PyPI                                                                                                    | 🛠️ Coming Soon | [Manual Integration](#manual-integration) |
| **Java**            | Maven                                                                                                   | 🛠️ Coming Soon | [Manual Integration](#manual-integration) |
| **Go**              | GitHub                                                                                                  | 🛠️ Coming Soon | [Manual Integration](#manual-integration) |

***

## TypeScript SDK

The fastest way to integrate for Web, Mobile, and Backend (Node.js/Bun/Deno).

### Requirements

* **Node.js 18+**, Deno, Bun, or any modern browser with `fetch()` support
* No native dependencies — works in serverless environments (AWS Lambda, Vercel, Cloudflare Workers)

### Features

* **25 typed methods** covering every API endpoint
* **Zero dependencies** — uses native `fetch()`
* **Full TypeScript support** — intellisense, autocompletion, type safety
* **Auto-retry** on 429/500 errors with exponential backoff
* **Dual-mode auth** — works with RapidAPI or direct API keys
* **Works everywhere** — Node.js 18+, Deno, Bun, browsers

### Installation

```bash theme={null}
npm install @fieldfunded/sdk
```

### Initialization

<CodeGroup>
  ```typescript RapidAPI (default) theme={null}
  import { FieldFundedSDK } from '@fieldfunded/sdk';

  const client = new FieldFundedSDK({
      apiKey: 'YOUR_RAPIDAPI_KEY',
  });
  ```

  ```typescript Direct API theme={null}
  import { FieldFundedSDK } from '@fieldfunded/sdk';

  const client = new FieldFundedSDK({
      apiKey: 'YOUR_API_KEY',
      baseUrl: 'https://api.fieldfunded.com/v1',
  });
  ```
</CodeGroup>

### Configuration

```typescript theme={null}
const client = new FieldFundedSDK({
    apiKey: 'YOUR_KEY',         // Required
    host: 'custom-host.com',    // RapidAPI host (optional)
    baseUrl: 'https://...',     // Direct API URL (overrides host)
    timeout: 20000,             // Request timeout in ms (default: 20000)
    retries: 2,                 // Retries on 429/500 (default: 1)
});
```

<Note>
  The default timeout is 20s to accommodate server-side index construction on high-volume endpoints (like `/settlements`). Most requests return in \<200ms.
</Note>

***

## Usage Examples

### List Sports & Leagues

```typescript theme={null}
const sports = await client.getSports();
console.log(sports.sports);
// [{ key: 'soccer', name: 'Soccer', active_events: 142, is_esport: false }, ...]

const leagues = await client.getLeagues({ sport: 'soccer' });
console.log(leagues.leagues);
// [{ slug: 'premier-league', name: 'Premier League', country: 'England', active_events: 10, live_events: 3 }, ...]
```

### Get Events (with filters)

```typescript theme={null}
// All live soccer in England
const events = await client.getEvents({
    sport: 'soccer',
    country: 'england',
    status: 'live',
});

// Games starting in the next 2 hours
const upcoming = await client.getEvents({
    starts_within: '2h',
    sport: 'basketball',
});

// Events on a specific date
const tomorrow = await client.getEvents({
    date: '2026-04-16',
    league: 'premier-league',
});

// American odds format
const american = await client.getEvents({
    sport: 'soccer',
    odds_format: 'american',
});
```

### Event Detail

```typescript theme={null}
const detail = await client.getEvent('12345678');
console.log(detail.markets);     // Full markets array (1,000+ on major events)
console.log(detail.scoreboard);  // Period/set/map scores
console.log(detail.sport_data);  // Serving indicators, power play, etc.
```

### Live Scores (lightweight polling)

```typescript theme={null}
// Optimized endpoint — use for frequent polling (every 5-10s)
const scores = await client.getScores({ sport: 'soccer' });
for (const game of scores.scores) {
    console.log(`${game.home_team} ${game.score.home}-${game.score.away} ${game.away_team}`);
}
```

### Search by Team Name

```typescript theme={null}
const results = await client.search('Barcelona', { limit: 5 });
console.log(results.events); // All upcoming/live Barcelona games
```

### Batch Events (max 20 IDs)

```typescript theme={null}
const batch = await client.getEventsBatch(['123', '456', '789']);
console.log(batch.events);     // Record<id, EventDetail>
console.log(batch.found);      // Number of events found (e.g. 2)
console.log(batch.requested);  // Number of IDs you sent (e.g. 3)
```

### Bet Check

```typescript theme={null}
const result = await client.checkBet({
    selections: [{
        event_id: '123',
        market: 'Match Winner',
        outcome: 'Home',
        odds: 1.85,
        stake: 10,              // currency-agnostic — any numeric amount
        market_id: 340168,      // primary — recommended for 100% accuracy
        selection_id: 1824650,  // primary — recommended for 100% accuracy
    }],
});
console.log(result.results[0].result);  // 'won' | 'lost' | 'refund' | 'pending'
console.log(result.results[0].payout);  // 18.50 (when won, = stake × odds)
```

### Parlay / Accumulator Check

```typescript theme={null}
const parlay = await client.checkParlay({
    legs: [
        { event_id: '123', market: 'Match Winner', outcome: 'Home', odds: 1.85, market_id: 340168, selection_id: 1824650 },
        { event_id: '456', market: 'Over/Under 2.5', outcome: 'Over', odds: 1.92 },
    ],
    stake: 10,
});
console.log(parlay.payout.combined_odds);
console.log(parlay.payout.payout);
```

### Settlements & Results (Fully Automatic)

<Warning>
  **Settlement is fully automatic.** Markets resolve without developer intervention as soon as a game ends. Poll `getSettlements()` regularly after the game ends to capture all market resolutions as they arrive gradually.
</Warning>

```typescript theme={null}
// Check settlements every 60 seconds
const settlements = await client.getSettlements({ limit: 10 });
for (const s of settlements.settlements) {
    console.log(`${s.event_id}: ${s.settlement_status} — ${s.resolved_markets_count}/${s.total_markets_count ?? '?'} markets (${s.pending_markets_count ?? '?'} pending)`);
}

// Get official result for a specific event (score-only)
const result = await client.getEventResult('12345678');
console.log(`Status: ${result.status}`); // 'ended', 'walkover', 'retired', etc.
if (result.score) {
    console.log(`Final Score: ${result.score.home}-${result.score.away}`);
}

// For market-level resolutions, use getSettlements()
const eventSettlements = await client.getSettlements({ event_id: '12345678' });

// Outright/futures settlements (also automatic)
const outrightSettlements = await client.getOutrightSettlements({ sport: 'soccer' });
```

### Outrights / Futures

```typescript theme={null}
// List tournaments with outright markets
const outrights = await client.getOutrights({ sport_id: '124' });

// Get selections and odds (supports odds_format)
const detail = await client.getOutright('12345', { odds_format: 'american' });
console.log(detail.events[0].markets[0].selections[0].odds);
```

### Usage & Quota

```typescript theme={null}
const usage = await client.getUsage();
console.log(`${usage.current.this_month} / ${usage.limits.per_month} requests used`);
console.log(`${usage.current.month_remaining} remaining`);

// Per-endpoint breakdown
const endpoints = await client.getUsageEndpoints();
console.log(endpoints.endpoints);
// [{ path: '/events', count: 142 }, { path: '/live', count: 58 }, ...]

// Active warnings
const warnings = await client.getUsageWarnings();
if (warnings.warnings.length > 0) {
    console.warn('[!]', warnings.warnings[0].message);
}
```

### System Health (quota-free)

These endpoints do not count against your monthly quota.

```typescript theme={null}
const ping = await client.ping();       // { pong: true, timestamp: 1234567890 }
const health = await client.health();   // System health, data freshness
const status = await client.status();   // Live/prematch counts
```

***

## Error Handling

The SDK provides typed error classes for clean error handling:

```typescript theme={null}
import {
    FieldFundedSDK,
    RateLimitError,
    AuthenticationError,
    NotFoundError,
    BadRequestError,
    ServiceUnavailableError,
} from '@fieldfunded/sdk';

try {
    const events = await client.getEvents();
} catch (err) {
    if (err instanceof RateLimitError) {
        console.log(`Rate limited. Retry in ${err.retryAfter}s`);
    } else if (err instanceof ServiceUnavailableError) {
        console.log(`Service degraded (${err.component}). Retry in ${err.retryAfter}s`);
    } else if (err instanceof AuthenticationError) {
        console.log('Invalid API key');
    } else if (err instanceof NotFoundError) {
        console.log('Event not found');
    } else if (err instanceof BadRequestError) {
        console.log(`Invalid request: ${err.message}`);
    }
}
```

***

## All Methods

| Method                          | Endpoint                        | Description                 |
| ------------------------------- | ------------------------------- | --------------------------- |
| `ping()`                        | `GET /v1/ping`                  | Latency check (quota-free)  |
| `health()`                      | `GET /v1/health`                | System health (quota-free)  |
| `status()`                      | `GET /v1/status`                | API status (quota-free)     |
| `getUsage()`                    | `GET /v1/usage`                 | Quota & consumption stats   |
| `getUsageEndpoints()`           | `GET /v1/usage/endpoints`       | Per-endpoint breakdown      |
| `getUsageWarnings()`            | `GET /v1/usage/warnings`        | Active quota warnings       |
| `getSports()`                   | `GET /v1/sports`                | List sports                 |
| `getLeagues(opts?)`             | `GET /v1/leagues`               | List leagues with slugs     |
| `getMarkets(opts?)`             | `GET /v1/markets`               | List market types           |
| `getEvents(opts?)`              | `GET /v1/events`                | List events (all filters)   |
| `getLive(opts?)`                | `GET /v1/live`                  | Live events                 |
| `getFeatured(opts?)`            | `GET /v1/featured`              | Featured games              |
| `getScores(opts?)`              | `GET /v1/scores`                | Live scores                 |
| `search(q, opts?)`              | `GET /v1/search`                | Search by team/league       |
| `getEvent(id, opts?)`           | `GET /v1/events/{id}`           | Event detail                |
| `getEventOdds(id, opts?)`       | `GET /v1/events/{id}/odds`      | Event odds                  |
| `getEventResult(id)`            | `GET /v1/events/{id}/result`    | Score result                |
| `getEventsBatch(ids, opts?)`    | `POST /v1/events/batch`         | Multiple events (max 20)    |
| `checkBet(req)`                 | `POST /v1/bets/check`           | Single bet check            |
| `checkParlay(req)`              | `POST /v1/bets/check-parlay`    | Parlay check                |
| `getSettlements(opts?)`         | `GET /v1/settlements`           | Settlement feed             |
| `getOutrightSettlements(opts?)` | `GET /v1/settlements/outrights` | Outright settlements        |
| `getOutrights(opts?)`           | `GET /v1/outrights`             | Outright markets            |
| `getOutrightSports()`           | `GET /v1/outrights/sports`      | Outright sports             |
| `getOutright(id, opts?)`        | `GET /v1/outrights/{id}`        | Specific outright with odds |

***

<div id="manual-integration" />

## Manual Integration (Universal)

If you are using a language without an official SDK yet, use standard HTTP libraries. Our API is standard REST/JSON — any language with HTTP support works.

### Python (using `requests`)

```python theme={null}
import requests

def get_live_scores(api_key):
    url = "https://api.fieldfunded.com/v1/live"
    headers = { "X-API-Key": api_key }
    response = requests.get(url, headers=headers)
    return response.json()

# Settlement polling
def poll_settlements(api_key, limit=20):
    url = f"https://api.fieldfunded.com/v1/settlements?limit={limit}"
    headers = { "X-API-Key": api_key }
    response = requests.get(url, headers=headers)
    data = response.json()
    for s in data.get("settlements", []):
        print(f"{s['event_id']}: {s['settlement_status']} — {s['resolved_markets_count']}/{s.get('total_markets_count', '?')} markets ({s.get('pending_markets_count', '?')} pending)")
    return data
```

### Go (using `net/http`)

```go theme={null}
package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {
    apiKey := "YOUR_API_KEY"
    url := "https://api.fieldfunded.com/v1/live"

    req, _ := http.NewRequest("GET", url, nil)
    req.Header.Set("X-API-Key", apiKey)

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}
```

***

## Technical Support

Need help with a specific language or interested in early access to our Python/Java SDKs? Reach out at [support@fieldfunded.com](mailto:support@fieldfunded.com).
