# Introduction

The LianaAutomation REST API lets your applications bring events and contacts from external
systems to LianaAutomation, search and delete that data, export segments, manage channels, and read
automation reports. Responses are JSON.

## Regions

Send requests to `{API URL}/{endpoint}`, using the API URL of your region:

| Region      | API URL                                                            |
| ----------- | ------------------------------------------------------------------ |
| Integration | <CopyCode value="https://rest.automation.lianacloud.com/api/v1" /> |

For example, `pingpong` in the integration region is
`https://rest.automation.lianacloud.com/api/v1/pingpong`. If you are unsure which region your
integration uses, contact your account manager.

The Asia (`t.asia.lianacem.com`) and UAE (`t6.lianacem.com`) installations accept only the legacy
HMAC signature, not Bearer tokens, so this documentation does not cover them.

## Requests and responses

Every endpoint takes a `POST` request with a JSON body. Send `{}` when the endpoint takes no
parameters.

Most errors in the request, such as a missing parameter or a channel that does not exist, return
HTTP status 200 with `succeed: false` and a message:

```json title="Response"
{
  "succeed": false,
  "message": "Missing name."
}
```

So check `succeed`, not just the HTTP status. Other errors return an HTTP error status, with the
status repeated in the body:

```json title="Response"
{
  "message": "Not Found",
  "status": 404,
  "status_message": "Not Found"
}
```

A missing or invalid `Authorization` header returns 401, also for an endpoint under `/api/v1/` that
does not exist. A path whose first segment after `/api/` is not `v1` returns 404.

### Long-running requests

Database searches and deletes, exports and automation reports run in the background, in three
steps:

1. Start it with the `request` endpoint, for example
   [`database/search/request`](/automation/api/database). The response holds a `handle`.
1. Call the `ready` endpoint with the `handle` until it returns `"ready": true`.
1. Fetch the outcome from the `result` endpoint with the same `handle`.

A database search or delete, or an export, can fail or stop without finishing:

- If the `ready` response has `error`, the job failed. Stop polling and make a new request.
- Results and errors are kept for about an hour. After that, and for an unknown `handle`, `ready`
  returns `"ready": false` without `error`.
- A job that stops without finishing stays `"ready": false`, so set an overall deadline for
  polling.

An automation report returns `"ready": true` also when it fails, and the error is in the `result`
response.

## Make your first request

The [`pingpong`](/automation/api/ping) endpoint returns what you send it. Use it to check that your
credentials and the connection work.

<Stepper>

1. **Get a Bearer token**

   Create a client ID and secret in [LianaAccount](https://account.lianacloud.com/), and
   [request a token](/authentication#request-an-access-token) with them. The examples request the
   scope `automation-api`, which is optional. The token is valid for 15 minutes.

1. **Send the request**

   <CodeTabs syncKey="language">

   ```bash title="cURL"
   curl --request POST 'https://rest.automation.lianacloud.com/api/v1/pingpong' \
     --header 'Authorization: Bearer <token>' \
     --header 'Content-Type: application/json' \
     --data '{"ping":"pong"}'
   ```

   ```javascript title="JavaScript"
   // Request a Bearer token
   const tokenResponse = await fetch("https://tokens.lianacloud.com/token", {
     method: "POST",
     body: new URLSearchParams({
       grant_type: "client_credentials",
       client_id: clientId,
       client_secret: clientSecret,
       scope: "automation-api",
     }),
   });
   const token = (await tokenResponse.json()).access_token;

   // Send the request with the token
   const response = await fetch(
     "https://rest.automation.lianacloud.com/api/v1/pingpong",
     {
       method: "POST",
       headers: {
         Authorization: `Bearer ${token}`,
         "Content-Type": "application/json",
       },
       body: JSON.stringify({ ping: "pong" }),
     },
   );
   const ret = await response.json();
   ```

   ```python title="Python"
   import requests

   # Request a Bearer token
   token = requests.post(
       "https://tokens.lianacloud.com/token",
       data={
           "grant_type": "client_credentials",
           "client_id": client_id,
           "client_secret": client_secret,
           "scope": "automation-api",
       },
   ).json()["access_token"]

   # Send the request with the token. json= also sets Content-Type: application/json.
   ret = requests.post(
       "https://rest.automation.lianacloud.com/api/v1/pingpong",
       headers={"Authorization": f"Bearer {token}"},
       json={"ping": "pong"},
   ).json()
   ```

   ```php title="PHP"
   <?php
   // Request a Bearer token
   $ch = curl_init('https://tokens.lianacloud.com/token');
   curl_setopt_array($ch, [
       CURLOPT_POST => true,
       CURLOPT_POSTFIELDS => http_build_query([
           'grant_type' => 'client_credentials',
           'client_id' => $client_id,
           'client_secret' => $client_secret,
           'scope' => 'automation-api',
       ]),
       CURLOPT_RETURNTRANSFER => true,
   ]);
   $token = json_decode(curl_exec($ch), true)['access_token'];

   // Send the request with the token
   $ch = curl_init('https://rest.automation.lianacloud.com/api/v1/pingpong');
   curl_setopt_array($ch, [
       CURLOPT_POST => true,
       CURLOPT_POSTFIELDS => json_encode(['ping' => 'pong']),
       CURLOPT_HTTPHEADER => [
           "Authorization: Bearer {$token}",
           'Content-Type: application/json',
       ],
       CURLOPT_RETURNTRANSFER => true,
   ]);
   $ret = json_decode(curl_exec($ch), true);
   ```

   ```java title="Java"
   // Uses java.net.*, java.net.http.*, java.nio.charset.StandardCharsets, java.util.Map and Jackson
   HttpClient http = HttpClient.newHttpClient();
   ObjectMapper json = new ObjectMapper();

   // Request a Bearer token
   HttpRequest tokenRequest = HttpRequest.newBuilder()
       .uri(URI.create("https://tokens.lianacloud.com/token"))
       .header("Content-Type", "application/x-www-form-urlencoded")
       .POST(HttpRequest.BodyPublishers.ofString("grant_type=client_credentials"
           + "&client_id=" + URLEncoder.encode(clientId, StandardCharsets.UTF_8)
           + "&client_secret=" + URLEncoder.encode(clientSecret, StandardCharsets.UTF_8)
           + "&scope=automation-api"))
       .build();
   String token = json.readTree(http.send(tokenRequest, HttpResponse.BodyHandlers.ofString()).body())
       .get("access_token").asText();

   // Send the request with the token
   HttpRequest request = HttpRequest.newBuilder()
       .uri(URI.create("https://rest.automation.lianacloud.com/api/v1/pingpong"))
       .header("Authorization", "Bearer " + token)
       .header("Content-Type", "application/json")
       .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(Map.of("ping", "pong"))))
       .build();
   JsonNode ret = json.readTree(http.send(request, HttpResponse.BodyHandlers.ofString()).body());
   ```

   ```csharp title="C#"
   using System.Net.Http.Headers;
   using System.Text;
   using System.Text.Json;

   var http = new HttpClient();

   // Request a Bearer token
   using var tokenResponse = await http.PostAsync("https://tokens.lianacloud.com/token",
       new FormUrlEncodedContent(new Dictionary<string, string>
       {
           ["grant_type"] = "client_credentials",
           ["client_id"] = clientId,
           ["client_secret"] = clientSecret,
           ["scope"] = "automation-api",
       }));
   var token = JsonSerializer.Deserialize<JsonElement>(await tokenResponse.Content.ReadAsStringAsync())
       .GetProperty("access_token").GetString();

   // Send the request with the token
   using var request = new HttpRequestMessage(HttpMethod.Post,
       "https://rest.automation.lianacloud.com/api/v1/pingpong")
   {
       Content = new StringContent(JsonSerializer.Serialize(new { ping = "pong" }),
           Encoding.UTF8, "application/json"),
   };
   request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
   using var response = await http.SendAsync(request);
   var ret = JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStringAsync());
   ```

   ```go title="Go"
   // Uses bytes, encoding/json, log, net/http and net/url

   // Request a Bearer token
   res, err := http.PostForm("https://tokens.lianacloud.com/token", url.Values{
   	"grant_type":    {"client_credentials"},
   	"client_id":     {clientID},
   	"client_secret": {clientSecret},
   	"scope":         {"automation-api"},
   })
   if err != nil {
   	log.Fatal(err)
   }
   defer res.Body.Close()

   var token struct {
   	AccessToken string `json:"access_token"`
   }
   if err := json.NewDecoder(res.Body).Decode(&token); err != nil {
   	log.Fatal(err)
   }

   // Send the request with the token
   req, err := http.NewRequest("POST", "https://rest.automation.lianacloud.com/api/v1/pingpong",
   	bytes.NewBufferString(`{"ping":"pong"}`))
   if err != nil {
   	log.Fatal(err)
   }
   req.Header.Set("Authorization", "Bearer "+token.AccessToken)
   req.Header.Set("Content-Type", "application/json")

   res, err = http.DefaultClient.Do(req)
   if err != nil {
   	log.Fatal(err)
   }
   defer res.Body.Close()

   var ret map[string]any
   if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
   	log.Fatal(err)
   }
   ```

   </CodeTabs>

1. **Check the response**

   ```json title="Response"
   {
     "pong": "pong"
   }
   ```

   A failed request returns an HTTP error status. See
   [Requests and responses](#requests-and-responses).

</Stepper>

## Next steps

Start with the basics:

1. [Authorization](./authorization): getting a Bearer token.

Then browse the endpoints:

<Cards>
  <Card title="Import" href="/automation/api/import">
    Bring events and contacts to LianaAutomation from external systems.
  </Card>
  <Card title="Database" href="/automation/api/database">
    Search events and contacts, and delete them.
  </Card>
  <Card title="Export" href="/automation/api/export">
    Export the contents of a segment.
  </Card>
  <Card title="Segment" href="/automation/api/segment">
    List the segments.
  </Card>
  <Card title="Channel" href="/automation/api/channel">
    List, create, edit and delete channels, the sources of imported data.
  </Card>
  <Card title="Report" href="/automation/api/report">
    Reports on automations and their messages.
  </Card>
  <Card title="Form" href="/automation/api/form">
    List the forms.
  </Card>
  <Card title="Info" href="/automation/api/info">
    Information about the installation.
  </Card>
</Cards>
