# Introduction

The LianaCommerce REST API lets your applications manage a shop's products, variations,
categories, prices, discounts and stock, read and update orders, and manage customer accounts and
companies. Requests and responses are JSON.

## API URL

Each shop serves its own API. The API URL is the shop's address followed by `/api/v1`:

| Shop address                 | API URL                                               |
| ---------------------------- | ----------------------------------------------------- |
| `https://shop.example.com`   | <CopyCode value="https://shop.example.com/api/v1" />  |
| `https://example.com/store/` | <CopyCode value="https://example.com/store/api/v1" /> |

Send requests to `{API URL}/{endpoint}`, for example `https://shop.example.com/api/v1/products`. If
the shop runs under a path, such as `/store/`, include it: a request without it is redirected, and
many HTTP clients turn a redirected `POST` or `PUT` into a `GET`.

## Requests and responses

The API uses `GET` to read, `POST` to create, `PUT` to update and `DELETE` to delete.

- `POST` and `PUT` take a JSON body with `Content-Type: application/json`. An empty body returns
  `400`.
- `PUT` is a partial update: it changes only the fields you send.
- The API ignores fields and query parameters it doesn't know, so check the spelling of names.
- A method that an endpoint doesn't support returns `403` with the message `method not allowed`.
- `GET` filters go in the query string. A filter with `[]` in its name takes a list, for example
  `?codes[]=A100&codes[]=A200`.

Every response, also for a single item, has the same shape: the request URL in `href`, the
results in `items` and the response time in `meta`. Each item has its position in the response in
`result_index`. Lists also have links to the `first`, `prev` and `next` page.

```json title="Response"
{
  "href": "https://shop.example.com/api/v1/countries?limit=2",
  "next": { "href": "https://shop.example.com/api/v1/countries?offset=2&limit=2" },
  "first": { "href": "https://shop.example.com/api/v1/countries?offset=0&limit=2" },
  "prev": { "href": null },
  "items": [
    {
      "id": 2,
      "names": [
        { "language": "EN", "name": "Sweden" },
        { "language": "FI", "name": "Ruotsi" }
      ],
      "code": "SE",
      "href": "https://shop.example.com/api/v1/countries/2",
      "result_index": 1
    },
    {
      "id": 1,
      "names": [
        { "language": "EN", "name": "Finland" },
        { "language": "FI", "name": "Suomi" }
      ],
      "code": "FI",
      "href": "https://shop.example.com/api/v1/countries/1",
      "result_index": 2
    }
  ],
  "meta": { "response_at": "2026-11-22T07:35:27+02:00" }
}
```

- `POST` returns `200` with the created item, and `DELETE` returns `200` with the deleted item.
- Lists are paged with `limit` (default 20) and `offset` (default 0). There is no page size cap,
  but large pages are slower. To read a whole list, follow `next` until its `href` is `null`.
  `limit` and `offset` must be whole numbers; any other value returns `400`.
- Texts in several languages are lists of `language` and text pairs, as `names` above. When you
  send them, languages that the shop doesn't use are ignored.
- Times in responses are in the shop's time zone, such as `2026-11-22T07:35:27+02:00`. Times you
  send are read as the shop's local time, and a time zone offset in them is ignored.

An error returns an HTTP error status, with the status repeated in the body:

```json title="Response"
{
  "code": 400,
  "message": "Missing parameter 'name' from request body",
  "meta": { "response_at": "2026-11-22T07:35:27+02:00" }
}
```

| Status | Meaning                                                                                                 |
| ------ | ------------------------------------------------------------------------------------------------------- |
| `400`  | A parameter or a field is missing or invalid. `message` names it.                                       |
| `401`  | The credentials are missing or invalid. See [Authorization](./authorization#errors).                    |
| `403`  | The token's scope doesn't cover the method, or the endpoint doesn't support the method.                 |
| `404`  | The item doesn't exist or has been deleted. Bulk updates return `404` when no element matched anything. |

The message is meant for people and may change, so don't parse it.

## Make your first request

The [`ping`](/commerce/api/ping) endpoint returns `success: true` when your credentials work. Use
it to check the credentials and the shop's API URL.

<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 `commerce-api`, which is optional. The token is valid for 15 minutes. To use a shop API
   key instead, send it in the `X-Auth-Token` header; see [Authorization](./authorization).

   Shops accept Bearer tokens from the January 2027 update. Until then, use an API key.

1. **Send the request**

   <CodeTabs syncKey="language">

   ```bash title="cURL"
   curl 'https://shop.example.com/api/v1/ping' \
     --header 'Authorization: Bearer <token>'
   ```

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

   // Send the request with the token
   const response = await fetch("https://shop.example.com/api/v1/ping", {
     headers: { Authorization: `Bearer ${token}` },
   });
   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": "commerce-api",
       },
   ).json()["access_token"]

   # Send the request with the token
   ret = requests.get(
       "https://shop.example.com/api/v1/ping",
       headers={"Authorization": f"Bearer {token}"},
   ).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' => 'commerce-api',
       ]),
       CURLOPT_RETURNTRANSFER => true,
   ]);
   $token = json_decode(curl_exec($ch), true)['access_token'];

   // Send the request with the token
   $ch = curl_init('https://shop.example.com/api/v1/ping');
   curl_setopt_array($ch, [
       CURLOPT_HTTPHEADER => ["Authorization: Bearer {$token}"],
       CURLOPT_RETURNTRANSFER => true,
   ]);
   $ret = json_decode(curl_exec($ch), true);
   ```

   ```java title="Java"
   // Uses java.net.*, java.net.http.*, java.nio.charset.StandardCharsets 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=commerce-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://shop.example.com/api/v1/ping"))
       .header("Authorization", "Bearer " + token)
       .GET()
       .build();
   JsonNode ret = json.readTree(http.send(request, HttpResponse.BodyHandlers.ofString()).body());
   ```

   ```csharp title="C#"
   using System.Net.Http.Headers;
   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"] = "commerce-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.Get, "https://shop.example.com/api/v1/ping");
   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 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":         {"commerce-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("GET", "https://shop.example.com/api/v1/ping", nil)
   if err != nil {
   	log.Fatal(err)
   }
   req.Header.Set("Authorization", "Bearer "+token.AccessToken)

   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"
   {
     "success": true,
     "code": 200,
     "meta": { "response_at": "2026-11-22T07:35:27+02:00" }
   }
   ```

   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): Bearer tokens, API keys and their errors.
1. [Changes](./changes): what changed for existing integrations.

Then browse the endpoints:

<Cards>
  <Card title="Products" href="/commerce/api/products">
    Products and their descriptions, images, attachments, tags, properties and stock.
  </Card>
  <Card title="Variations" href="/commerce/api/variations">
    Sizes, colors and other variations of a product, with their own stock and images.
  </Card>
  <Card title="Stocks" href="/commerce/api/stocks">
    Update the stock of many products and variations in one request.
  </Card>
  <Card title="Prices" href="/commerce/api/prices">
    Update the prices of many products and variations in one request.
  </Card>
  <Card title="Orders" href="/commerce/api/orders">
    Read orders and their rows, and change their status.
  </Card>
  <Card title="Accounts" href="/commerce/api/accounts">
    Customer accounts and their roles and companies.
  </Card>
</Cards>
