# SWebService

## Set up your web service

To setup your server for communication with space, in the root of your domain, on the port you are using, place a file named 'sinewave.space.scripting.txt' containing 'SPACE\_OK'. E.g. <http://somewhere.com/sinewave.space.scripting.txt> - if this file is not present, you will be unable to use scripting to communicate with the domain. *Note: you should use HTTPS for all API calls. You may also need to implement a CORS policy in your webserver headers.*

**Membres** 3

|          |                       |                                                                                                |
| -------- | --------------------- | ---------------------------------------------------------------------------------------------- |
| Fonction | [Get](#get)           | Performs an HTTP\[S] GET and invokes the callback with an SWebResponse containing the result.  |
| Fonction | [Post](#post)         | Performs an HTTP\[S] POST and invokes the callback with an SWebResponse containing the result. |
| Fonction | [GetImage](#getimage) | Returns a valid SResource for a image on a remote domain that can be used via e.g. SMaterial.  |

## Fonctions

### Get

void Get(string url, Closure onComplete, Table headers = null, float timeout = 0)

Performs an HTTP\[S] GET and invokes the callback with an [SWebResponse](/docs/fr/scripting/client-scripting-api-reference/types/swebresponse.md) containing the result.

Paramètres

| Paramètre  | Type             | Description                                                                                                          |
| ---------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |
| url        | string           | The absolute URL to request. Must pass the domain whitelist check.                                                   |
| onComplete | Closure          | Callback receiving a single [SWebResponse](/docs/fr/scripting/client-scripting-api-reference/types/swebresponse.md). |
| headers    | Table (optional) | Supported keys: `Content-Type`, `Bearer` (maps to `Authorization: Bearer <token>`).                                  |
| timeout    | float (optional) | Timeout in seconds. `0` disables timeout.                                                                            |

Valeurs de retour

`void`

Exemple

**Lua**

```lua
function OnResponseFunction(responseData)
--
end
Space.WebServices.Get('A URL', OnResponseFunction)

```

**Lua**

```lua
-- Example: Retrieve user-specific data from your integration endpoint

-- Typically retrieved dynamically, e.g., from Space.Scene.CurrentUser
local userID = "User123"

-- Identifier for the integrated service or application
local serviceID = "CRMApp"

-- Build the request URL with query parameters
local sentData = "http://www.yourdomain.net/getIntegrationData.php?id=" .. userID .. "&service=" .. serviceID

-- Callback function to handle the API response
local response = function(data)
  if data.Error == nil then
    -- Log the successful response
    Space.Log(data.Response)
  else 
    -- Log any error returned by the API
    Space.Log(data.Error)
  end
end

-- Make a GET request to your integration API
Space.WebServices.Get(sentData, response)

-- You can parse the response to extract and use relevant integration data


```

Note:

* This call automatically sends diagnostic headers: `X-Sinespace-Region-ID`, `X-Sinespace-Region-Name`, `X-Sinespace-Instance-ID`, `X-Sinespace-Script-Name`, `X-Sinespace-Runtime-Type`, `X-Sinespace-In-Editor`, and `X-Sinespace-Preview-Server`.
* Domains must host `/sinewave.space.scripting.txt` with the content `SPACE_OK` at the root for requests to proceed (see setup above).

### Post

void Post(string url, string data, Closure onComplete, Table headers = null, float timeout = 0)

Performs an HTTP\[S] POST and invokes the callback with an [SWebResponse](/docs/fr/scripting/client-scripting-api-reference/types/swebresponse.md) containing the result.

Paramètres

| Paramètre  | Type             | Description                                                                                                                           |
| ---------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| url        | string           | The absolute URL to POST to. Must pass the domain whitelist check.                                                                    |
| data       | string           | Request body. For JSON, provide a JSON string and set `Content-Type` accordingly.                                                     |
| onComplete | Closure          | Callback receiving a single [SWebResponse](/docs/fr/scripting/client-scripting-api-reference/types/swebresponse.md).                  |
| headers    | Table (optional) | Supported keys: `Content-Type` (defaults to `application/x-www-form-urlencoded`), `Bearer` (maps to `Authorization: Bearer <token>`). |
| timeout    | float (optional) | Timeout in seconds. `0` disables timeout.                                                                                             |

Valeurs de retour

`void`

Exemple

**Lua**

```lua
function OnResponseFunction(responseData)
--
end
local url = 'https://example.com/endpoint'
local data = 'key=value'
Space.WebServices.Post(url, data, OnResponseFunction)

```

**Lua**

```lua
-- Example: Send user-specific data to your integration endpoint via POST request

-- User identifier, typically retrieved dynamically
local userID = "User123"

-- Identifier for the integrated service or product
local serviceID = "CRMApp"

-- Target URL for the integration API
local url = "http://www.yourdomain.net/postIntegrationData.php"

-- Construct the payload for the POST request
local sentData = "id=" .. userID .. "&service=" .. serviceID

-- Define a callback to handle the API response
local response = function(data)
  if data.Error == nil then
    -- Log the successful response
    Space.Log(data.Response)
  else 
    -- Log any error returned by the API
    Space.Log(data.Error)
  end
end

-- Set the appropriate content-type for the POST request
local tableHeader = {["Content-Type"] = "text/plain"}

-- Send a POST request to your integration API
Space.WebServices.Post(url, sentData, response, tableHeader)


```

**Lua**

```lua
-- JSON POST with Bearer auth and timeout
local url = "https://api.example.com/widgets"
local body = '{"name":"My Widget","color":"blue"}'
local headers = { ["Content-Type"] = "application/json", ["Bearer"] = "YOUR_ACCESS_TOKEN" }

Space.WebServices.Post(url, body, function(data)
  if data.Error == nil then
    Space.Log("Created: " .. data.Response)
  else
    Space.Log("Error: " .. data.Error)
  end
end, headers, 15)

```

Note:

* For JSON: set `Content-Type = application/json` and send a JSON string body.
* The target domain must pass the whitelist check (`/sinewave.space.scripting.txt` with `SPACE_OK`).
* HTTPS is recommended; ensure the server sends appropriate CORS headers.

### GetImage

[SResource](/docs/fr/scripting/client-scripting-api-reference/types/sresource.md) GetImage(string url, Closure onComplete = null, Table header = null, float timeout = 0)

Returns a valid [*SResource*](/docs/fr/scripting/client-scripting-api-reference/types/sresource.md) for a image on a remote domain that can be used via e.g. [*SMaterial*](/docs/fr/scripting/client-scripting-api-reference/types/smaterial.md). While the image loads, it will be a white pixel that will be substituted with the real image once loaded.

Paramètres

| Paramètre  | Type               | Description                                                                                                         |
| ---------- | ------------------ | ------------------------------------------------------------------------------------------------------------------- |
| url        | string             | The absolute image URL to load.                                                                                     |
| onComplete | Closure (optional) | Callback receiving the resulting [SResource](/docs/fr/scripting/client-scripting-api-reference/types/sresource.md). |
| header     | Table (optional)   | Accepted but not used for images; pass `nil`. Reserved for future use.                                              |
| timeout    | float (optional)   | Accepted but not used for images; pass `0`. Reserved for future use.                                                |

Valeurs de retour

`SResource`

Exemple

**Lua**

```lua
resourceImage = Space.WebServices.GetImage('An Image URL')

```

**Lua**

```lua
-- Example: Load and apply a remote image from your integration media server

-- Image filename to retrieve from the media service
local imageFileName = "user_banner_1024.jpg"

-- Base URL of the content delivery server
local mediaServerUrl = "https://cdn.acme-integrations.com/assets/"

-- Reference to the 3D object where the image will be displayed
local displayObject = Space.Host.GetReference("profileDisplay")

-- Fetch the image from the server
local imageResource = Space.WebServices.GetImage(mediaServerUrl .. imageFileName)

-- Apply the image as a texture to the object's material
displayObject.Renderer.Material.SetTexture("_MainTex", imageResource)

```
