Tags: Unity API requests, UnityWebRequest wrapper, HTTP request builder for Unity
The APIBuilder class is a fluent-style API request builder for Unity, using UnityWebRequest to handle HTTP requests. It allows developers to create, configure, and send requests in an organized and structured manner.
Ensure that your Unity project has access to UnityEngine.Networking before using APIBuilder.
using Maphatar.UnityAPI;To create a new request, use the static Make method and provide an endpoint URL:
var request = APIBuilder.Make("https://api.example.com/data");Headers can be added using the SetHeaderRequest method:
request.SetHeaderRequest("Authorization", "Bearer YOUR_TOKEN");You can set a timeout duration (in seconds) for the request:
request.SetTimeout(10);Specify the HTTP method using one of the following:
request.Get(); // For GET requests
request.Post(); // For POST requests
request.Put(); // For PUT requestsAlternatively, use SetMethod for custom methods:
request.SetMethod("DELETE");For requests that require a body (e.g., POST, PUT), use:
request.BodyData("{\"key\":\"value\"}");Define success and error handlers using OnSuccess and OnError:
request
.OnSuccess(response => Debug.Log("Success: " + response.downloadHandler.text))
.OnError(response => Debug.LogError("Error: " + response.error));To prevent duplicate requests, use the StackPrevention method with a unique key:
request.StackPrevention("UniqueKey");If a request with the same key is still in progress, subsequent requests will not be sent.
Once the request is configured, send it using:
request.SendRequest();APIBuilder.Make("https://api.example.com/data")
.SetHeaderRequest("Content-Type", "application/json")
.Post()
.BodyData("{\"name\":\"John\"}")
.OnSuccess(response => Debug.Log("Response: " + response.downloadHandler.text))
.OnError(response => Debug.LogError("Request failed: " + response.error))
.StackPrevention("UserCreation")
.SendRequest();Send request with IEnumerator. Suitable for scenarios that requires to run multiple coroutines in proper order.
public IEnumerator StandardRequest(){
yield return APIBuilder.Make("https://mynedpoint.com/endpoint")
.Get()
.OnSuccess((res) =>
{
Debug.Log("message: " + res.downloadHandler.text);
})
.OnError(res => {
Debug.LogError($"Error: {res.error}");
}).SendRequestRoutine();
}Send request without IEnumerator or invoking yield. Can be called in Non-MonoBehavior classes.
APIBuilder.Make("https://mynedpoint.com/endpoint")
.Get()
.OnSuccess((res) =>
{
Debug.Log("message: " + res.downloadHandler.text);
})
.OnError(res => {
Debug.LogError($"Error: {res.error}");
}).SendRequest();