HTTPS Outcalls on ICP: Calling External APIs Without Building an Oracle
Thomas ·
One of the more unusual things an ICP backend can do is make an HTTPS request directly from canister code. That means a canister can fetch an exchange rate, query a public REST API, call an AI service, check an external account, or send a webhook without putting a conventional server between the canister and the internet. That sounds like ordinary backend development, but the execution model is very different. On a normal application subnet, a replicated HTTPS outcall can cause every replica to contact the same server independently, and those replicas then have to agree on what the server returned. A timestamp in a response header, a request-specific ID in the JSON, or a non-idempotent POST can therefore turn an otherwise ordinary API integration into a consensus or accounting problem. ICP now also supports non-replicated HTTPS outcalls, which changes some of those tradeoffs considerably. The result is that choosing between replicated and non-replicated mode has become part of the security design rather than an implementation detail. This guide builds a Motoko outcall using the current ic package, then focuses on the decisions that matter in production: transforms, response limits, POST idempotency, rate limits, cycle costs, user-controlled URLs, caching, API credentials, and deciding when you actually want consensus over an external response. Start with the current Motoko API Older HTTPS-outcall examples commonly call the management canister manually and calculate a cycle amount themselves. I would not start new Motoko code that way. The current tooling uses the compiler-provided management-canister interface together with the ic Mops package. Call.httpRequest calculates the required cost through the system API and attaches the appropriate cycles automatically, which is both easier and safer than maintaining a hardcoded cycle calculation. Current ICP guidance requires core 2.x and ic 2.1.0 or newer for this pattern. A minimal mops.toml can therefore include: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff [ dependencies ] core = "2.6.1" ic = "2.1.0" As with the earlier guides, I would pin the project's Motoko compiler through Mops as well rather than allowing developer machines and CI to silently compile with different toolchains. The management canister itself is available as aaaaa-aa on every subnet, so there is no separate HTTP gateway canister to deploy. A basic replicated GET Suppose we want to retrieve a small public JSON document. The Motoko side can look like this: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff import Blob "mo:core/Blob" ; import Text "mo:core/Text" ; import IC "ic:aaaaa-aa" ; import Call "mo:ic/Call" ; persistent actor ExternalApi { public query func transform ({ context : Blob ; response : IC . http_request_result ; }) : async IC . http_request_result { { response with headers = []; }; }; public func fetchStatus () : async Text { let request : IC . HttpRequestArgs = { url = "https://example.com/api/status" ; max_response_bytes = ? 10_000 ; headers = [ { name = "Accept" ; value = "application/json" ; } ]; body = null ; method = #get; transform = ?{ function = transform; context = Blob . fromArray ([]); }; is_replicated = ? true ; }; let response = await Call . httpRequest (request); switch ( Text . decodeUtf8 (response. body )) { case (?text) text; case null "Response was not valid UTF-8" ; }; }; }; There are three details here that I would consider part of the production design rather than boilerplate: max_response_bytes , the transform function, and is_replicated . The URL is almost the easy part. What replicated mode actually means With is_replicated = ?true , the request does not behave like a request from a normal cloud server. The subnet records the pending outcall, then each replica independently contacts the external server. On a typical 13-node subnet, that can mean approximately 13 nearly simultaneous requests, after which each replica transforms its response and the subnet needs at least a two-thirds agreement on the transformed result before your canister receives it. That architecture removes the need to trust one node as an oracle. If one malicious replica tries to substitute a different price or API response, it cannot simply dictate what the canister sees. But consensus creates a new requirement: honest replicas must receive responses that can be made identical. That is the job of the transform. Why perfectly valid APIs can fail Imagine every replica requests the same endpoint and receives the same JSON body, but the HTTP responses contain: Date: Sat, 12 Sep 2026 12:15:01 GMT and: Date: Sat, 12 Sep 2026 12:15:02 GMT . Those are perfectly legitimate HTTP responses, but they are not byte-for-byte identical. Cookies, CDN headers, request IDs, server timing, cache metadata, and IP-dependent headers can create the same problem. If enough transformed responses do not agree, the subnet cannot produce a result and the outcall eventually fails. You still pay for the failed request, so this is not something I would leave to trial and error in production. For many JSON APIs, the first thing I do is simply remove all response headers: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff public query func transform ({ context : Blob ; response : IC . http_request_result ; }) : async IC . http_request_result { { response with headers = []; }; }; That eliminates a large source of nondeterminism without affecting an application that only cares about the body. Stripping headers does not make the body deterministic Suppose an API returns: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff { "price": 4.72, "request_id": "2d7b8a", "generated_at": 1789215312 } Every replica may agree on price while receiving a different request_id or generated_at . Removing the HTTP headers therefore does not solve the problem. The stronger transform pattern is to parse the body, extract only the fields your application needs, and serialize those fields into one deterministic representation. ICP's current HTTPS-outcall guidance recommends this approach because the transformed response becomes smaller and there are fewer nondeterministic fields left to overlook. If all I need is the price, I want the consensus layer comparing a normalized representation of the price, not an entire third-party telemetry object. That also makes the trust boundary easier to audit. When the application later uses the response in financial logic, I can point to exactly which external data reached consensus. JSON object ordering can bite you too Even when two responses contain logically identical JSON, they are not necessarily identical byte sequences. One server might return: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff { "symbol": "ICP", "price": 4.72 } while another response could be: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff { "price": 4.72, "symbol": "ICP" } Those objects mean the same thing to a JSON parser, but the bodies differ as bytes. If the API or its infrastructure can vary object ordering, parse the relevant values and produce your own canonical output in the transform instead of passing the raw body through. This is conceptually similar to the canonical-serialization issue from Certified Queries on ICP: How to Make Fast Reads You Can Actually Trust . Cryptographic and consensus systems ultimately compare concrete data, not what a developer informally considers "the same JSON." The transform must be a query A transform function is executed locally by replicas while processing the HTTP response, so it must be exported as a query method. It should also be deterministic and should not attempt to mutate application state. I keep transforms small for that reason. Their responsibility is normalization, not business logic. The update method should receive the agreed result and decide what that result means to the application. That separation gives you a useful architecture: the transform answers "what exact external response can the subnet agree upon?", while the update logic answers "what should my application do with it?" Local testing can give you false confidence This is one of the more important HTTPS-outcall testing problems. A local ICP environment can successfully execute an outcall without exposing a broken transform because the local replica does not have a subnet full of independent replicas receiving slightly different responses. Current ICP documentation specifically warns that local testing can therefore pass even when a mainnet deployment will fail to reach consensus. That means I would not test a transform only by calling the real API locally. Instead, take several realistic raw responses containing different dates, request IDs, header ordering, JSON ordering, and other variable fields, pass them through the transform, and require identical transformed output. If response A and response B are semantically equivalent for your application, then transform(A) and transform(B) should be exactly equivalent for consensus purposes. That is the test that matters. max_response_bytes is both a safety limit and a pricing decision Every outcall should set max_response_bytes deliberately. The hard response limit is currently 2,000,000 bytes, including the response body plus HTTP header names and values. If max_response_bytes is omitted, the IC assumes that full 2 MB maximum when calculating the outcall cost. On a 13-node subnet, leaving the default can make even a tiny response cost roughly 20.85 billion cycles because pricing is based on the declared maximum response size rather than the number of bytes the server eventually sends. So if the API normally returns about 2 KB, I might allow 5 KB or 10 KB depending on its documented behavior. I would not casually allow 2 MB. This is one of those rare optimizations where a single request field can reduce cost dramatically without changing application behavior. Do not set the cap too tightly either Suppose an API normally returns 2,400 bytes, so you set max_response_bytes = 2_500 . Then the provider adds one harmless field and the response becomes 2,700 bytes. Your integration breaks. The goal is not to predict the exact response length; it is to choose a reasonable upper bound based on the contract you expect from the provider. If response size varies substantially and the provider supports HEAD , that can also be useful for learning the resource size before retrieving the body. ICP supports GET , HEAD , and POST in replicated mode. I generally prefer APIs that already expose narrow endpoints, though. Fetching a 1.8 MB document so a transform can keep 30 bytes is poor API selection even if it technically works. A transform cannot rescue an oversized raw response This is subtle enough to call out separately. The response-size limit is checked when the raw HTTP response arrives and again after transformation. That means a 3 MB response cannot be accepted by saying, "my transform reduces it to 200 bytes." The first size check already failed. Size max_response_bytes for the actual incoming headers and body, not for the transformed result. If the provider only exposes a response larger than the ICP limit, you need another endpoint, pagination, a narrower request, or an intermediary service designed to return bounded data. Replicated mode is not always the right choice anymore The newer is_replicated option makes