Skip to main content

Serving an HTTP request

Advanced
Tutorial

Overview

Canisters can serve or handle an incoming HTTP request using the HTTP Gateway Protocol.

This allows developers to host web applications and APIs from a canister.

How it works

An HTTP request from a client gets intercepted by the HTTP Gateway Protocol, which identifies the target canister and encodes the request in Candid. This encoded request is then sent to the canister for processing. Once processed, the canister replies with an HTTP response. Finally, the HTTP Gateway Protocol decodes the response using Candid and sends it back to the client, completing the communication loop.

For detailed information on how it works, please refer to the HTTP Gateway Protocol specification.

How to make a request

The following example returns 'Hello, World!' in the body at the /hello endpoint.

import HashMap = "mo:base/HashMap";
import Blob = "mo:base/Blob";
import Text "mo:base/Text";
import Option "mo:base/Option";

actor {

public type HttpRequest = {
body: Blob;
headers: [HeaderField];
method: Text;
url: Text;
};

public type ChunkId = Nat;
public type SetAssetContentArguments = {
chunk_ids: [ChunkId];
content_encoding: Text;
key: Key;
sha256: ?Blob;
};
public type Path = Text;
public type Key = Text;

public type HttpResponse = {
body: Blob;
headers: [HeaderField];
status_code: Nat16;
};

public type HeaderField = (Text, Text);

private func removeQuery(str: Text): Text {
return Option.unwrap(Text.split(str, #char '?').next());
};

public query func http_request(req: HttpRequest): async (HttpResponse) {
let path = removeQuery(req.url);
if(path == "/hello") {
return {
body = Text.encodeUtf8("root page :" # path);
headers = [];
status_code = 200;
};
};

return {
body = Text.encodeUtf8("404 Not found :" # path);
headers = [];
status_code = 404;
};
};
}

Additional examples

The HTTP counter project is an example in Motoko of a 'counter' application that uses the http_request method to read the current counter value or access some pre-stored data and the http_request_update method to increment the counter and retrieve the updated value.