Skip to content

How to Use

Dickson Law edited this page Jul 2, 2021 · 4 revisions

How to Use

General Form

Verbs that don't have request bodies take a target URL and an options untyped struct:

  • xhr_get(url, options)
  • xhr_head(url, options)
  • xhr_options(url, options)
  • xhr_trace(url, options)

Verbs that have request bodies take a target URL, a request body, and an options untyped struct:

  • xhr_delete(url, body, options)
  • xhr_patch(url, body, options)
  • xhr_post(url, body, options)
  • xhr_put(url, body, options)

For the general case, you can also use xhr_request(verb, url, body, options).

A Quick Example with GET

Here is an example using xhr_get(url, options) looking up the latest news headlines from 100% Orange Juice on Steam's API.

xhr_get("https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/", {
	params: { appid: 282800, count: 1 },
	done: function(res) {
		show_message("Latest news from 100% Orange Juice: " + res.data.appnews.newsitems[0].title);
	},
	fail: function() {
		show_message("Can't fetch headlines from Steam.");
	}
});

The base URL is specified in the url parameter, and the ?appid=282800&count=1 in the options.params parameter. Notice that there is NO manual URL encoding --- Request Master handles this internally. The actions for success and failure are specified in the options.done and options.fail parameters respectively. You will learn more about these below.

The options Parameter

The options parameter is an untyped struct specifying additional properties for the request and what to do while handling the response. To begin, here are the most important ones:

Outgoing Request

  • params: If specified as an untyped struct, it will be URL-encoded and appended to the URL. For example, specifying {q: "Hello World"} here will append ?q=Hello%20World to the URL.
  • headers: Specify a map ID or array with pairwise header-value entries, and add those to the request's headers. For example, specifying [["Accept", "application/json"], ["Accept-Charset", "utf-8"]] here will ask the server to respond in UTF-8 JSON if able.

Incoming Response

  • done: Specify a callback method that accepts a XhrResponse struct and performs actions on it when successful.
  • fail: Specify a callback method that accepts a XhrResponse struct and performs actions on it when the request is unsuccessful and/or the decoder throws an exception.
  • progress: Specify a callback method that accepts the current download progress and the total size of the download, and performs actions on it when the request is in progress.
  • subject: Specify an instance ID to bind callback methods to. The daemon will also monitor its existence, and self-destruct if it no longer exists. If specified as noone, the daemon will not monitor anything else. Leave unspecified to use the default set by REQM_DEFAULT_SUBJECT.

The XhrResponse Class

The done and fail options take XhrResponse structs, which describe the outcome of the request. It has the following properties:

  • data: The decoded result of the response. If decode was unsuccessful, this will contain undefined.
  • decodeOk: Whether the decode was successful.
  • decodeException: (if decode failed) The exception thrown by the decoder.
  • handle: The asynchronous request ID.
  • headers: A map containing the headers of the response.
  • httpStatus: The HTTP status code of the response (e.g. 200).
  • url: The URL being requested.
  • isSuccessful(): Return whether the request and the decode were successful.

The body Parameter

When available (DELETE, PATCH, POST, PUT), the body parameter can accept any of the following:

  • A string
  • A buffer ID
  • An untyped struct (i.e. { ... }). If you specify this for the body, it will be internally transformed into a request body helper according to what you configured for REQM_DEFAULT_ENCODER)
  • A JsonStruct struct. This will behave like an untyped struct, except the keys can optionally contain characters not normally allowed in instance variable names (e.g. GML keywords, built-in variable/function names, non-alphanumeric-non-underscore characters). For more details on this type, please see JsonStruct's entry in JSON Struct Wiki.
  • A explicitly-typed request body helper (e.g. new MultipartBody({ ... })). If you specify one, this will override the type you configured for REQM_DEFAULT_ENCODER for the current request.

An Example POST Request

Here is an example for uploading an image to Imgur's image upload endpoint (API doc):

// Gather information
var imgurClientId = get_string("Enter Imgur client ID:", "");
var uploadImage = get_open_filename("JPG Image|*.jpg,*.jpeg|GIF Image|*.gif|PNG Image|*.png", "");
var uploadTitle = get_string("Enter the title of the image:", "No title");
var uploadDescription = get_string("Enter the description of the image:", "No description");

// Send the request
xhr_post("https://api.imgur.com/3/image.json", new MultipartBody({
	title: uploadTitle,
	description: uploadDescription,
	image: new FilePart(uploadImage)
}), {
	headers: [["Authorization", "Client-ID " + imgurClientId]],
	done: function(res) {
		var json = res.data;
		show_message("Upload successful. Here comes your image...");
		url_open(json.data.link);
	},
	fail: function(res) {
		show_message("Upload failed. Try again later.");
	}
});

This request uses an explicit MultipartBody, which is required for standard file uploads. It also adds an Authorization header required by the API endpoint.

Downloading Files

Starting with v1.2.0, you can also download files in a binary-safe way to a string path or a buffer using xhr_download(url, filename_or_buffer, options). It does not support encoding or decoding, but it optionally supports SHA1 validation for more critical files.

A Quick Download

xhr_download("http://web.archive.org/web/20060821000040im_/http://gamemaker.nl/images/header.jpg", working_directory + "gmlegacy.jpg", {
	done: function(res) {
		sprite_index = sprite_add(res.file, 1, false, false, 0, 0);
	},
	fail: function(res) {
		show_message("Failed to download the image!");
	}
});

Technical Note: This example does not work in the HTML5 export.

A SHA1-Validated Download

xhr_download supports validating the downloaded result by providing a known SHA1 value in the sha1 option key. If the SHA1 hash of the result does not match the one given, the fail callback is called, and if targeting a file, the file will not be written to.

xhr_download("http://web.archive.org/web/20060821000040im_/http://gamemaker.nl/images/header.jpg", working_directory + "gmlegacy.jpg", {
	sha1: "e49f3280aa16efb9955e123802b25d78bf5475e4",
	done: function(res) {
		sprite_index = sprite_add(res.file, 1, false, false, 0, 0);
	},
	fail: function(res) {
		if (res.httpStatus == 200) {
			if (!res.isSha1Validated()) {
				show_message("Hash mismatch!\nExpected: " + res.sha1Expected + "\nReceived: " + res.sha1Received);
			}
		} else {
			show_message("Failed to download the image!");
		}
	}
});

Technical Note: This example does not work in the HTML5 export.

The XhrDownloadResponse Class

The done and fail options in xhr_download take XhrDownloadResponse structs, which describe the outcome of the download. It has the following properties:

  • data: The buffer holding the full response. Notice: If the download targeted a file, this buffer will be freed after the callback is over.
  • file: The file being downloaded to. If the download didn't target a file, this will contain undefined.
  • handle: The asynchronous request ID returned by http_request.
  • headers: A map containing the headers of the response.
  • httpStatus: The HTTP status code of the response (e.g. 200).
  • url: The URL being requested.
  • sha1Expected: The SHA1 hash expected of the download (Available only when the sha1 option is given).
  • sha1Received: The SHA1 hash of the download (Available only when the sha1 option is given).
  • textMode: Specify whether to write the downloaded file's contents using file_text_write_string (true) or buffer_save_ext (false). On the HTML5 export, this must be set to true if you wish to use the resulting emulated file with text file functions or INI file functions. Default: false
  • isSuccessful(): Return whether the download and SHA1 validation (if given) were successful.
  • isSha1Validated(): Return whether the SHA1 hash is matched. If the sha1 option was not given, this always returns true.

Clone this wiki locally