Skip to main content

How to use HTTP outcalls: Intro

Advanced
Concept

This feature allows smart contracts to directly make calls to HTTP(S) servers external to the blockchain and use the response in the further processing of the smart contract, without the need for oracles.

Key concepts

Methods supported

The feature currently supports GET, HEAD, and POST methods for HTTP requests.

ICP management canister

In order for a canister to use HTTPS outcalls, it needs to call the system API of ICP. Canisters can call into the system API by sending messages to the the ICP management canister using the identifier "aaaaa-aa".

Cycles

  • Cycles used to pay for the call must be explicitly transferred with the call. They are not deducted from the caller's balance implicitly.

The API for sending HTTP outcalls

As per the Internet Computer interface specification, a canister can use the http_request method by following specification:

The request

The following parameters should be supplied within the request:

  • url: The requested URL that must be valid according to RFC-3986 and its length must not exceed 8192. The URL may specify a custom port number.

  • max_response_bytes: Optional; Specifies the maximal size of the response in bytes. If provided, the value must not exceed 2MB (2_000_000B). The call will be charged based on this parameter. If not provided, the maximum of 2MB will be used.

  • method: Currently, only GET, HEAD, and POST are supported.

  • headers: List of HTTP request headers and their corresponding values.

  • body: Optional; The content of the request's body.

  • transform: An optional function that transforms raw responses to sanitized responses, and a byte-encoded context that is provided to the function upon invocation, along with the response to be sanitized. If provided, the calling canister itself must export this function. An example written in Rust is shown below:

async fn transform(raw: CanisterHttpResponsePayload) -> CanisterHttpResponsePayload {
let mut sanitized = raw.clone();
sanitized.headers = vec![];
sanitized
}

The response

The returned response (and the response provided to the transform function, if specified) contains the following fields:

  • status: The response status (e.g., 200, 404).

  • headers: List of HTTP response headers and their corresponding values.

  • body: The response's body.

Sample code

Examples of making GET and POSTrequests in Motoko and Rust: