# Introduction

The [LianaMailer](https://www.lianamailer.com) REST API lets your applications manage contacts and
mailing lists, send newsletters and transactional mail, and read delivery reports and tracking
events. Responses are JSON.

## API versions

The API has three versions. They cover different tasks rather than replacing each other, and they
all use the same credentials.

| Version | Requests                                         | Use it for                                                          |
| ------- | ------------------------------------------------ | ------------------------------------------------------------------- |
| v1      | `POST` with a JSON body, e.g. `/v1/getRecipient` | Account, sites, contacts, mailing lists, deliveries and reports     |
| v2      | `POST` with a JSON body                          | Importing mailing lists, and sending batch, event and web page mail |
| v3      | `GET` with query parameters                      | Paged lists of delivery openers and clickers, and tracking events   |

See [Parameters](./parameters) for how each version takes its parameters.

## Regions

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

| Region | API URL                                                |
| ------ | ------------------------------------------------------ |
| EU     | <CopyCode value="https://rest.lianamailer.com" />      |
| Asia   | <CopyCode value="https://rest.asia.lianamailer.com" /> |
| Dubai  | <CopyCode value="https://rest.me.lianamailer.com" />   |

For example, `getRecipient` in the EU region is `https://rest.lianamailer.com/api/v1/getRecipient`.

## Make your first request

The v1 [`echoMessage`](/api/system#echo-message) endpoint returns the message you send. 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 `mailer-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.lianamailer.com/api/v1/echoMessage' \
     --header 'Authorization: Bearer <token>' \
     --header 'Content-Type: application/json' \
     --data '{"msg":"hello"}'
   ```

   ```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: "mailer-api",
     }),
   });
   const token = (await tokenResponse.json()).access_token;

   // Send the request with the token
   const response = await fetch("https://rest.lianamailer.com/api/v1/echoMessage", {
     method: "POST",
     headers: {
       Authorization: `Bearer ${token}`,
       "Content-Type": "application/json",
     },
     body: JSON.stringify({ msg: "hello" }),
   });
   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": "mailer-api",
       },
   ).json()["access_token"]

   # Send the request with the token. json= also sets Content-Type: application/json.
   ret = requests.post(
       "https://rest.lianamailer.com/api/v1/echoMessage",
       headers={"Authorization": f"Bearer {token}"},
       json={"msg": "hello"},
   ).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' => 'mailer-api',
       ]),
       CURLOPT_RETURNTRANSFER => true,
   ]);
   $token = json_decode(curl_exec($ch), true)['access_token'];

   // Send the request with the token
   $ch = curl_init('https://rest.lianamailer.com/api/v1/echoMessage');
   curl_setopt_array($ch, [
       CURLOPT_POST => true,
       CURLOPT_POSTFIELDS => json_encode(['msg' => 'hello']),
       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=mailer-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.lianamailer.com/api/v1/echoMessage"))
       .header("Authorization", "Bearer " + token)
       .header("Content-Type", "application/json")
       .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(Map.of("msg", "hello"))))
       .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"] = "mailer-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.lianamailer.com/api/v1/echoMessage")
   {
       Content = new StringContent(JsonSerializer.Serialize(new { msg = "hello" }),
           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":         {"mailer-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.lianamailer.com/api/v1/echoMessage",
   	bytes.NewBufferString(`{"msg":"hello"}`))
   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"
   {
     "succeed": true,
     "result": "hello"
   }
   ```

   In v1 and v2, a successful response has `succeed` set to `true` and the data in `result`. When
   a request fails, `succeed` is `false` and `message` describes the error, and the HTTP status is
   usually still 200. See [Errors](./errors) for v3 and for handling errors.

</Stepper>

## Next steps

Start with the basics, in this order:

1. [Authorization](./authorization): getting a Bearer token.
1. [Parameters](./parameters): how v1, v2 and v3 take their parameters, and paging in v3.
1. [Restrictions](./restrictions): request rate limits and reserved property names.
1. [Errors](./errors): how each version reports errors, and how to handle them.

Then pick the guide for what you are building:

<Cards>
  <Card title="Contact lifecycle" href="/mailer/guide/contact-lifecycle" icon="users">
    Contact states, and what deleting, restoring and forgetting a contact keeps or erases.
  </Card>
  <Card title="Importing contacts" href="/mailer/guide/importing" icon="file-up">
    The v1 and v2 imports compared, and how to follow an import until it is done.
  </Card>
  <Card title="Sending mail" href="/mailer/guide/sending" icon="send">
    Choose between event, batch and web page send, and follow the delivery.
  </Card>
</Cards>

Then browse the endpoints, with examples in cURL, JavaScript, Python, PHP, Java, C#, Go and Ruby:

<TagCards />
