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:
-
For POST requests sending JSON data:
-
It also includes helpers for specific protocols like
http.jsonrpc(...)
andhttp.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 standardfetch
API directly in your actions if you prefer. However, using thehttp
helper gives you the automatic retry logic for free. - "How do I set custom headers (like Authorization)?" You can pass standard
fetch
options (likeheaders
) as the last argument to thehttp
methods (e.g.,http.get.json(url, params, { headers: { 'Authorization': 'Bearer ...' } })
).