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 Buffer "mo:base/Buffer";

type HeaderField = (Text, Text);

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

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

public query func http_request(req: HttpRequest): async (HttpResponse) {
let path = removeQuery(req.url);
if(path == "/hello") {
return {
status_code = 200,
headers = [],
body = Buffer.from('Hello, World!'),
};
};
return {
body = Text.encodeUtf8("404 Not found :");
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.