Daydreams Logo
Extra reading

http.ts

This file provides a convenient helper object named http for making network requests to external APIs or web services from within your agent's actions. It's essentially a smarter version of the standard web fetch command.

How to Use

When you write an action handler that needs to fetch data from or send data to an external API, you can import and use this http object.

  • For simple GET requests expecting JSON data:

    import { http } from "@daydreamsai/core";
     
    // Inside an action handler:
    try {
      const data = await http.get.json<{ someField: string }>(
        "https://api.example.com/data?id=123"
      );
      console.log(data.someField);
      return { success: true, result: data };
    } catch (error) {
      console.error("API call failed:", error);
      return { success: false, error: "API failed" };
    }
  • For POST requests sending JSON data:

    import { http } from "@daydreamsai/core";
     
    // Inside an action handler:
    const payload = { name: "Widget", value: 42 };
    try {
      const response = await http.post.json(
        "https://api.example.com/create",
        payload
      );
      return { success: true, id: response.id };
    } catch (error) {
      // ... handle error ...
    }
  • It also includes helpers for specific protocols like http.jsonrpc(...) and http.graphql(...).

Benefit

  • Automatic Retries: The key benefit is built-in automatic retries. If a network request fails due to a temporary network issue or a specific server error (like 500 or 503), the http helper will automatically wait a bit and try the request again a few times before giving up. This makes your actions more resilient to temporary glitches.
  • Convenience: Provides shortcuts for common tasks like setting JSON headers, parsing JSON responses, and adding query parameters (params option).

Anticipated Questions

  • "Do I have to use this instead of fetch?" No, you can still use the standard fetch API directly in your actions if you prefer. However, using the http helper gives you the automatic retry logic for free.
  • "How do I set custom headers (like Authorization)?" You can pass standard fetch options (like headers) as the last argument to the http methods (e.g., http.get.json(url, params, { headers: { 'Authorization': 'Bearer ...' } })).

On this page