Skip to content

Making API Calls

Learn how to make HTTP requests from your agents using context.fetch().

Basic Usage

js
const response = await context.fetch(url, options);

GET Request

js
async function handler(input, context) {
  const response = await context.fetch(
    'https://api.example.com/data'
  );
  
  if (!response.ok) {
    return { error: true, message: `Request failed: ${response.status}` };
  }
  
  const data = JSON.parse(response.body);
  return data;
}

POST Request with JSON

js
const response = await context.fetch('https://api.example.com/items', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'New Item',
    value: 42,
  }),
});

Adding Headers

js
const response = await context.fetch('https://api.example.com/protected', {
  headers: {
    'Authorization': `Bearer ${context.secrets.API_TOKEN}`,
    'X-Custom-Header': 'value',
  },
});

Response Object

js
{
  ok: boolean,      // true if status 200-299
  status: number,   // HTTP status code (200, 404, 500, etc.)
  body: string,     // Response body as string
}

Error Handling

Always handle potential failures:

js
async function handler(input, context) {
  try {
    const response = await context.fetch('https://api.example.com/data');
    
    // Check HTTP status
    if (!response.ok) {
      // Try to parse error message
      try {
        const error = JSON.parse(response.body);
        return { error: true, message: error.message || `HTTP ${response.status}` };
      } catch {
        return { error: true, message: `HTTP ${response.status}` };
      }
    }
    
    // Parse successful response
    const data = JSON.parse(response.body);
    return data;
    
  } catch (error) {
    // Network error, timeout, etc.
    return { error: true, message: error.message || 'Request failed' };
  }
}

URL Encoding

Always encode user input in URLs:

js
const query = encodeURIComponent(input.searchTerm);
const response = await context.fetch(
  `https://api.example.com/search?q=${query}`
);

Form Data

For application/x-www-form-urlencoded:

js
const params = new URLSearchParams({
  username: 'user',
  password: 'pass',
});

const response = await context.fetch('https://api.example.com/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: params.toString(),
});

Limits

LimitValue
Requests per execution10
Request timeout30 seconds
Response body size10 MB

Multiple API Calls

Make multiple requests (up to the limit):

js
async function handler(input, context) {
  const { ids } = input;
  
  const results = [];
  
  for (const id of ids.slice(0, 10)) {
    const response = await context.fetch(
      `https://api.example.com/items/${id}`
    );
    
    if (response.ok) {
      results.push(JSON.parse(response.body));
    }
  }
  
  return { items: results, count: results.length };
}

Common Patterns

REST API

js
// GET list
await context.fetch('https://api.example.com/items');

// GET single
await context.fetch(`https://api.example.com/items/${id}`);

// POST create
await context.fetch('https://api.example.com/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(newItem),
});

// PUT update
await context.fetch(`https://api.example.com/items/${id}`, {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(updatedItem),
});

// DELETE
await context.fetch(`https://api.example.com/items/${id}`, {
  method: 'DELETE',
});

GraphQL

js
const response = await context.fetch('https://api.example.com/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${context.secrets.API_TOKEN}`,
  },
  body: JSON.stringify({
    query: `
      query GetUser($id: ID!) {
        user(id: $id) {
          name
          email
        }
      }
    `,
    variables: { id: input.userId },
  }),
});

const { data, errors } = JSON.parse(response.body);

Debugging

Log responses during development:

js
const response = await context.fetch(url);
console.log('Status:', response.status);
console.log('Body:', response.body.substring(0, 500));

Note: console.log is available in the sandbox but output may be limited.

Built with VitePress