Skip to main content

JavaScript request API

Intermediate
JavaScript
Concept

Overview

To make API calls to ICP endpoints and canisters from a JavaScript program, the ICP JavaScript agent can be used. It provides call, query, and readState methods to an actor.

Install the ICP JavaScript agent

To install the ICP JavaScript agent with npm, use the command:

npm i --save @dfinity/agent

Import the ICP JavaScript agent in the browser

To import the ICP JavaScript agent 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, the ICP JavaScript agent 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 });

ICP JavaScript agent documentation

To learn more about the ICP JavaScript agent, check out the ICP JavaScript agent documentation page.

Resources

You can learn more about using the ICP JavaScript agent to make API calls in the API documentation.