REST API Usage – Arma Reforger
Jump to navigation
Jump to search
The REST API (RestApi) is a simplified way to call REST requests and handle results/data, allowing to communicate with a web API. This page explains the terminology and how to use the scripting API.
Definitions
Context
The context is simply the website URL with which transactions will happen, e.g https://httpbin.org/.
A RestContext context can be created with the following:
Callback
A callback is a script class handling a request's success, error or timeout.
Once the request happens (asynchronously) the callback methods are called to process the received result.
The scripter is responsible for the callback object's lifetime. Inherit from RestCallback and implement the desired methods to create a custom callback:
Example
Declaration
Copy
class RestCallbackExample : RestCallback
{
//------------------------------------------------------------------------------------------------
override void OnError(int errorCode)
{
Print("OnError()");
};
//------------------------------------------------------------------------------------------------
override void OnTimeout()
{
Print("OnTimeout()");
};
//------------------------------------------------------------------------------------------------
override void OnSuccess(string data, int dataSize)
{
Print("OnSuccess() - data size = " + dataSize + " b");
if (dataSize > 0)
Print(data); // note that Print() will not output strings longer than 1024b to console, check the dataSize!
};
};
class HttpElement
{
protected ref RestCallbackExample m_callbackExample;
//------------------------------------------------------------------------------------------------
void ExecuteRequest()
{
if (!m_callbackExample)
m_callbackExample = new RestCallbackExample();
string contextURL = "https://httpbin.org/";
RestContext context = GetGame().GetRestApi().GetContext(contextURL);
// executed request is "get" in "https://httpbin.org/" context (i.e "https://httpbin.org/get")
// using the HTTP's GET method
context.GET(m_callbackExample, "get");
// it is possible to assemble a more complex request using arguments, like this:
// ctx.GET(m_callbackExample, "get?x=10&y=5");
}
};
Call
Copy
class HolderClass
{
protected ref HttpElement m_HttpElement;
void PerformGETRequest()
{
if (!m_HttpElement)
m_HttpElement = new HttpElement();
m_HttpElement.ExecuteRequest();
}
}