JavaScript request API
Overview
To make API calls to ICP endpoints and canisters from a JavaScript program, the JavaScript agent (agent-js
) can be used. agent-js
provides call, query, and readState methods to an actor.
Install agent-js
To install agent-js
with npm
, use the command:
npm i --save @dfinity/agent
Import agent-js
in the browser
To import agent-js
in the browser, use the import statement:
import * as agent from "@dfinity/agent";
You can also use individual exports:
import { Actor, HttpAgent } from '@dfinity/agent';
Making API calls
To make API calls, agent-js
uses the fetch
API. Here is an example:
import fetch from 'isomorphic-fetch';
import { HttpAgent } from '@dfinity/agent';
const host = process.env.DFX_NETWORK === 'local' ? 'http://127.0.0.1:4943' : 'https://icp-api.io';
const agent = new HttpAgent({ fetch, host });
This example includes a host
option, since the agent will not be able to determine the host using the global context.
You can also pass fetchOptions
to the agent's constructor, such as a custom header:
import fetch from 'isomorphic-fetch';
import { HttpAgent } from '@dfinity/agent';
const host = process.env.DFX_NETWORK === 'local' ? 'http://127.0.0.1:4943' : 'https://ic0.app';
/**
* @type {RequestInit}
*/
const fetchOptions = {
headers: {
'X-Custom-Header': 'value',
},
};
const agent = new HttpAgent({ fetch, host, fetchOptions });
agent-js
documentation
To learn more about agent-js
, check out the agent-js
documentation page.
Resources
You can learn more about using agent-js
to make API calls in the agent-js
API documentation.