To receive requests you need to install the Rest Server package, create a GameObject and add the RestServer component to it. This is described in the Install. After the installation the rest server is start up default on http://localhost:8080 and can receive requests.
Sub-paths under http://localhost:8080 can now be registered and extended with custom functionality.
Endpoint, or urls, that the server shall respond to, can be registered any time before or after the server has been started. Only after an endpoint has been registered, it can be called from a possible client.
An endpoint can be registered like this:
using RestServer;
using UnityEngine;
public class Example : MonoBehaviour {
// Reference to the RestServer instance
public RestServer.RestServer server;
private void Start() {
// Register the endpoint
server.EndpointCollection.RegisterEndpoint(HttpMethod.GET, "/position", (request) => {
// do work
// send information back
request.CreateResponse().SendAsync();
});
}
}
The library provides two methods to register an endpoint:
void RegisterEndpoint(HttpMethod, String, Action)
void RegisterEndpoint(HttpMethod, Regex, Action)
The first parameter describes to which Http Verb the endpoint should respond to (GET, PUT, POST, …) while the second
argument specifies the location of the endpoint. In the first overload, the string case, the endpoint is specified from
the server root. So the location "/ping"
will be accessible through http://localhost:8080/ping.
The second overload, the Regex case, allows to specify a regex the incoming location has to fulfill so to execute the
defined Action
.
The Action
is executed, when an incoming request matches both the HttpMethod
and the string
/Regex
. Action
s can
be specified with the Lambda syntax
server.EndpointCollection.RegisterEndpoint(HttpMethod.GET, "/position", (request) => {
// Action
request.CreateResponse().SendAsync();
});
or with a method reference
void Start()
{
server.EndpointCollection.RegisterEndpoint(HttpMethod.GET, "/position", Handler);
}
private void Handler(RestRequest request) {
// Action
request.CreateResponse().SendAsync();
}