API Examples

API Examples

Common API patterns and use cases with code examples in multiple languages.

Create and Run an Agent

cURL

AGENT_ID=...

# Run the agent
curl -X POST https://api.seclai.com/agents/$AGENT_ID/runs \
  -H "X-API-Key:  $SECLAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "input": "Research the latest developments in AI agents"
  }'

Python

import requests

api_key = "YOUR_API_KEY"
headers = {
    "X-API-Key": api_key,
    "Content-Type": "application/json"
}

agent_id = "..."

# Run agent
run_response = requests.post(
    f"https://api.seclai.com/agents/{agent_id}/runs",
    headers=headers,
    json={"input": "Research the latest developments in AI agents"}
)
run = run_response.json()
print(run)

JavaScript

const apiKey = "YOUR_API_KEY";
const headers = {
  "X-API-Key": apiKey,
  "Content-Type": "application/json",
};

const agent_id = "...";

// Run agent
const runResponse = await fetch(
  `https://api.seclai.com/agents/${agent_id}/runs`,
  {
    method: "POST",
    headers,
    body: JSON.stringify({
      input: "Research the latest developments in AI agents",
    }),
  }
);
const run = await runResponse.json();
console.log(run);

Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    apiKey := "YOUR_API_KEY"
    baseURL := "https://api.seclai.com"

    agentId := "..."

    // Run agent
    runData := map[string]string{
        "input": "Research the latest developments in AI agents",
    }
    runJSON, _ := json.Marshal(runData)

    runReq, _ := http.NewRequest("POST",
        fmt.Sprintf("%s/agents/%s/runs", baseURL, agent_id),
        bytes.NewBuffer(runJSON))
    runReq.Header.Set("X-API-Key", apiKey)
    runReq.Header.Set("Content-Type", "application/json")

    runResp, _ := client.Do(runReq)
    defer runResp.Body.Close()

    var run map[string]interface{}
    json.NewDecoder(runResp.Body).Decode(&run)
    fmt.Printf("%+v\n", run)
}

Webhook Handler

Node.js + Express

import express from "express";

const app = express();
app.use(express.json());

app.post("/my-webhook-endpoint", (req, res) => {
  const payload = JSON.stringify(req.body);

  // process payload

  res.status(200).send("OK");
});

app.listen(3000);

Python + FastAPI

from fastapi import FastAPI, Request, HTTPException
import hmac
import hashlib
import os

app = FastAPI()

@app.post("/my-webhook-endpoint")
async def handle_webhook(request: Request):
    payload = await request.body()

    # process payload

    return {"status": "ok"}

Pagination

def get_all_agents(api_key):
    """Fetch all agents using pagination"""
    headers = {
        "X-API-Key": api_key,
        "Content-Type": "application/json"
    }

    all_agents = []
    offset = 0
    limit = 100

    while True:
        response = requests.get(
            f"https://api.seclai.com/agents?limit={limit}&offset={offset}",
            headers=headers
        )
        data = response.json()

        all_agents.extend(data["data"])

        if not data["has_more"]:
            break

        offset += limit

    return all_agents

Error Handling

async function createAgentWithRetry(agentData, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch("https://api.seclai.com/agents", {
        method: "POST",
        headers: {
          X-API-Key: process.env.SECLAI_API_KEY,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(agentData),
      });

      if (response.status === 429) {
        // Rate limited - wait and retry
        const retryAfter = response.headers.get("retry-after") || 60;
        await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
        continue;
      }

      if (!response.ok) {
        const error = await response.json();
        throw new Error(`API Error: ${error.error.message}`);
      }

      return await response.json();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      // Exponential backoff
      await new Promise((resolve) =>
        setTimeout(resolve, Math.pow(2, i) * 1000)
      );
    }
  }
}

Batch Operations

import asyncio
import aiohttp

async def run_multiple_agents(agent_ids, input_text):
    """Run multiple agents concurrently"""
    async with aiohttp.ClientSession() as session:
        tasks = []

        for agent_id in agent_ids:
            task = run_agent(session, agent_id, input_text)
            tasks.append(task)

        results = await asyncio.gather(*tasks)
        return results

async def run_agent(session, agent_id, input_text):
    url = f"https://api.seclai.com/agents/{agent_id}/runs"
    headers = {
        "X-API-Key": os.getenv('SECLAI_API_KEY'),
        "Content-Type": "application/json"
    }

    async with session.post(url, headers=headers, json={"input": input_text}) as resp:
        return await resp.json()

# Usage
results = asyncio.run(run_multiple_agents(
    ["agent_1", "agent_2", "agent_3"],
    "Analyze this data"
))

Next Steps