Skip to content

API Reference

AQaddora edited this page May 3, 2025 · 3 revisions

API Reference

This reference guide provides detailed information about REST Express's features, components, and generated code.

Table of Contents

API Importer Window

Collection Management

  • Import Collection: Imports Postman collections (.json)
  • Collection Tree: Hierarchical view of requests
  • Context Menu: Right-click actions for requests/folders
  • Search: Filter requests by name/URL

Request Testing

  • URL Field: Edit request URL
  • Method Selector: Choose HTTP method
  • Headers: Add/edit request headers
  • Query Parameters: URL parameters
  • Request Body: JSON/Form data input
  • File Upload: Handle file attachments
  • Send Button: Execute request
  • Response View: View formatted response

Variable Support

  • Collection Variables: From Postman collection
  • Environment Variables: Local overrides
  • Variable Substitution: {{variable}} syntax
  • Variable Management: Add/edit/delete

Script Generator Window

Configuration Options

  • Script Name: Output class name
  • Collection: Source collection
  • Output Path: Generated file location

Generated Features

  • Singleton Pattern: Automatic instance management
  • MonoBehaviour Integration: Unity lifecycle support
  • Coroutine-based Requests: Unity-friendly async operations
  • Form Data Handling: WWWForm support
  • Error Handling: Callback-based error management
  • Documentation: XML comments

Generated Code Structure

Base Class

using UnityEngine;
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;

public class ApiClient : MonoBehaviour
{
    private static ApiClient instance;
    public static ApiClient Instance
    {
        get
        {
            if (instance == null)
            {
                var go = new GameObject("ApiClient");
                instance = go.AddComponent<ApiClient>();
                DontDestroyOnLoad(go);
            }
            return instance;
        }
    }

    private void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);
    }

    // Collection Variables
    private const string baseUrl = "http://localhost:3000";
    private const string userId = "0001";
    private const string levelId = "1";
}

Request Methods

// Example generated method
public void CreateUser(string username = "simple_yet_efficient", 
    string email = "[email protected]", 
    string password = "123456", 
    Action<string> onSuccess = null, 
    Action<string> onError = null)
{
    string requestUrl = $"{baseUrl}/users";
    var form = new WWWForm();
    form.AddField("username", username);
    form.AddField("email", email);
    form.AddField("password", password);
    SendFormRequest(requestUrl, "POST", onSuccess, onError, form, null);
}

Request Types

GET Request

public void GetUserProfile(Action<string> onSuccess = null, Action<string> onError = null)
{
    string requestUrl = $"{baseUrl}/users/{userId}";
    SendRequest(requestUrl, "GET", onSuccess, onError, null, null);
}

POST Request with Form Data

public void SaveLevelProgress(string levelId = "{{levelId}}", 
    string score = "1000", 
    string stars = "3", 
    string timeSpent = "120", 
    Action<string> onSuccess = null, 
    Action<string> onError = null)
{
    string requestUrl = $"{baseUrl}/progress/level";
    var form = new WWWForm();
    form.AddField("levelId", levelId);
    form.AddField("score", score);
    form.AddField("stars", stars);
    form.AddField("timeSpent", timeSpent);
    SendFormRequest(requestUrl, "POST", onSuccess, onError, form, null);
}

File Upload

public void UploadMediaFiles(string audio = "", 
    string image = "", 
    string description = "Media upload description", 
    Action<string> onSuccess = null, 
    Action<string> onError = null)
{
    string requestUrl = $"{baseUrl}/media/upload";
    var form = new WWWForm();
    form.AddField("description", description);
    
    if (!string.IsNullOrEmpty(audio) && System.IO.File.Exists(audio))
    {
        byte[] fileData = System.IO.File.ReadAllBytes(audio);
        string fileName = System.IO.Path.GetFileName(audio);
        form.AddBinaryData("audio", fileData, fileName);
    }
    
    if (!string.IsNullOrEmpty(image) && System.IO.File.Exists(image))
    {
        byte[] fileData = System.IO.File.ReadAllBytes(image);
        string fileName = System.IO.Path.GetFileName(image);
        form.AddBinaryData("image", fileData, fileName);
    }
    
    SendFormRequest(requestUrl, "POST", onSuccess, onError, form.data, null);
}

Response Handling

Success Callback

ApiClient.Instance.GetUserProfile(
    onSuccess: (response) => {
        Debug.Log($"User profile: {response}");
        // Handle success
    },
    onError: (error) => {
        Debug.LogError($"Error: {error}");
        // Handle error
    }
);

Error Handling

private IEnumerator SendRequestCoroutine(string url, string method, 
    Action<string> onSuccess = null, 
    Action<string> onError = null, 
    string jsonBody = null, 
    Dictionary<string, string> headers = null)
{
    using (UnityWebRequest request = new UnityWebRequest(url, method))
    {
        request.downloadHandler = new DownloadHandlerBuffer();
        
        if (!string.IsNullOrEmpty(jsonBody))
        {
            var bodyRaw = Encoding.UTF8.GetBytes(jsonBody);
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.SetRequestHeader("Content-Type", "application/json");
        }
        
        yield return request.SendWebRequest();
        
        if (request.result == UnityWebRequest.Result.ConnectionError || 
            request.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.LogError($"Request error ({request.responseCode}): {request.error}");
            onError?.Invoke($"Status: {request.responseCode}, Error: {request.error}");
        }
        else
        {
            Debug.Log($"Request successful: {method} {url}");
            onSuccess?.Invoke(request.downloadHandler.text);
        }
    }
}

For more detailed examples, check the Examples page.

Clone this wiki locally