> ## Documentation Index
> Fetch the complete documentation index at: https://docs.widgetic.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Requests and errors

> Page through a list, create something safely with an idempotency key, and handle an error or a call that gets no answer, in TypeScript, Python, Go, Java, C#, Ruby and PHP

The first call is in [Get started](https://docs.widgetic.com/docs/sdks/getting-started.md). This page is about the three things every integration needs next: reading a list to its end, creating something once, and knowing what went wrong.

## What a call returns

A call returns the answer the API sends: `success`, then `data`, and for a list `meta`. See [Pagination](https://docs.widgetic.com/api-reference/pagination.md#response-format) for the shape of `meta`. The names of the fields in `data` and `meta` are the ones in the [API reference](https://docs.widgetic.com/api-reference/introduction.md), written the way each language writes a name: `hasNextPage` in TypeScript, `has_next_page` in Python and Ruby, `HasNextPage` in C#, `getHasNextPage()` in Java and PHP, and `GetHasNextPage()` in Go.

## Page through a list

A list that pages takes `page`, counting from 1, and `size`, from 1 to 100 (20 when you leave it out), and says in `meta.hasNextPage` whether there is another page. Pass them. `GET /widgets` answers with the whole list when you pass neither, and for an account with many widgets that answer can be cut short, with nothing in it to say so.

```typescript TypeScript theme={"theme":"css-variables"}
import { WidgetsApi } from '@widgetic/api-sdk-ts';

const widgetsApi = new WidgetsApi(process.env.WIDGETIC_API_KEY!);

let page = 1;
let hasNextPage = true;

while (hasNextPage) {
  const { data, meta } = await widgetsApi.getWidgets({ page, size: 100 }); // 100 is the most a page holds
  for (const widget of data) {
    console.log(widget.name);
  }

  hasNextPage = meta?.hasNextPage ?? false;
  page += 1;
}
```

```python Python theme={"theme":"css-variables"}
import os

import api_sdk_py

configuration = api_sdk_py.Configuration(access_token=os.environ["WIDGETIC_API_KEY"])

with api_sdk_py.ApiClient(configuration) as api_client:
    widgets_api = api_sdk_py.WidgetsApi(api_client)

    page = 1
    while True:
        answer = widgets_api.get_widgets(page=page, size=100)  # 100 is the most a page holds
        for widget in answer.data:
            print(widget.name)

        if not (answer.meta and answer.meta.has_next_page):
            break
        page += 1
```

```go Go theme={"theme":"css-variables"}
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	widgetic "github.com/widgetic/api-sdk-go"
)

func main() {
	client := widgetic.NewAPIClient(widgetic.NewConfiguration())
	ctx := context.WithValue(context.Background(), widgetic.ContextAccessToken, os.Getenv("WIDGETIC_API_KEY"))

	for page := int32(1); ; page++ {
		answer, _, err := client.WidgetsAPI.GetWidgets(ctx).Page(page).Size(100).Execute() // 100 is the most a page holds
		if err != nil {
			log.Fatal(err)
		}
		for _, widget := range answer.Data {
			fmt.Println(widget.GetName())
		}

		if !answer.Meta.GetHasNextPage() {
			break
		}
	}
}
```

```java Java theme={"theme":"css-variables"}
import com.widgetic.api.ApiClient;
import com.widgetic.api.ApiException;
import com.widgetic.api.Configuration;
import com.widgetic.api.api.WidgetsApi;
import com.widgetic.api.model.GetWidgets200Response;
import com.widgetic.api.model.Widget;

public class Paginate {
    public static void main(String[] args) throws ApiException {
        ApiClient client = Configuration.getDefaultApiClient();
        client.setBearerToken(System.getenv("WIDGETIC_API_KEY"));

        WidgetsApi widgetsApi = new WidgetsApi(client);

        int page = 1;
        boolean hasNextPage;
        do {
            GetWidgets200Response answer = widgetsApi.getWidgets(page, 100, null, null, null); // 100 is the most a page holds
            for (Widget widget : answer.getData()) {
                System.out.println(widget.getName());
            }

            hasNextPage = answer.getMeta() != null && Boolean.TRUE.equals(answer.getMeta().getHasNextPage());
            page++;
        } while (hasNextPage);
    }
}
```

```csharp C# theme={"theme":"css-variables"}
using System;
using Widgetic.ApiSdk.Cs.Api;
using Widgetic.ApiSdk.Cs.Client;

var configuration = new Configuration
{
    AccessToken = Environment.GetEnvironmentVariable("WIDGETIC_API_KEY")!,
};
var widgetsApi = new WidgetsApi(configuration);

var page = 1;
bool hasNextPage;
do
{
    var answer = widgetsApi.GetWidgets(page: page, size: 100); // 100 is the most a page holds
    foreach (var widget in answer.Data)
    {
        Console.WriteLine(widget.Name);
    }

    hasNextPage = answer.Meta?.HasNextPage ?? false;
    page++;
} while (hasNextPage);
```

```ruby Ruby theme={"theme":"css-variables"}
require 'api-sdk-rb'

ApiSdkRb.configure do |config|
  config.access_token = ENV['WIDGETIC_API_KEY']
end

widgets_api = ApiSdkRb::WidgetsApi.new

page = 1
loop do
  answer = widgets_api.get_widgets(page: page, size: 100) # 100 is the most a page holds
  answer.data.each { |widget| puts widget.name }

  break unless answer.meta&.has_next_page
  page += 1
end
```

```php PHP theme={"theme":"css-variables"}
<?php

require_once __DIR__ . '/vendor/autoload.php';

use WidgeticApi\Api\WidgetsApi;
use WidgeticApi\Configuration;

$config = Configuration::getDefaultConfiguration()->setAccessToken(getenv('WIDGETIC_API_KEY'));
$widgetsApi = new WidgetsApi(new GuzzleHttp\Client(), $config);

$page = 1;
do {
    $answer = $widgetsApi->getWidgets(page: $page, size: 100); // 100 is the most a page holds
    foreach ($answer->getData() as $widget) {
        echo $widget->getName(), PHP_EOL;
    }

    $hasNextPage = $answer->getMeta()?->getHasNextPage() ?? false;
    $page++;
} while ($hasNextPage);
```

## Create something safely

A call that creates or changes something takes an idempotency key, and the library asks you for it: the sample below shows where it goes in each language. A call sent without one is refused with `400`. The key is what lets you send the same call again, after a timeout or a dropped connection, and have the widget made once and not twice.

Make the key once for each thing you mean to do, before the first attempt, and send that same key on every retry. A UUID is a good key.

```typescript TypeScript theme={"theme":"css-variables"}
import { WidgetsApi } from '@widgetic/api-sdk-ts';
import { randomUUID } from 'node:crypto';

const widgetsApi = new WidgetsApi(process.env.WIDGETIC_API_KEY!);

const result = await widgetsApi.createWidget({
  idempotencyKey: randomUUID(),
  newWidget: {
    name: 'New Chart Widget',
    type: 'chart',
    content: {
      chartType: 'bar',
      dataSource: 'api',
    },
    isPublic: false,
  },
});
console.log(result);
```

```python Python theme={"theme":"css-variables"}
import os
import uuid

import api_sdk_py

configuration = api_sdk_py.Configuration(access_token=os.environ["WIDGETIC_API_KEY"])

with api_sdk_py.ApiClient(configuration) as api_client:
    widgets_api = api_sdk_py.WidgetsApi(api_client)
    result = widgets_api.create_widget(
        idempotency_key=str(uuid.uuid4()),
        new_widget={
            "name": "New Chart Widget",
            "type": "chart",
            "content": {
                "chartType": "bar",
                "dataSource": "api",
            },
            "isPublic": False,
        },
    )
    print(result)
```

```go Go theme={"theme":"css-variables"}
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/google/uuid"
	widgetic "github.com/widgetic/api-sdk-go"
)

func main() {
	ctx := context.WithValue(context.Background(), widgetic.ContextAccessToken, os.Getenv("WIDGETIC_API_KEY"))
	client := widgetic.NewAPIClient(widgetic.NewConfiguration())

	createWidgetRequestJSON := `{
  "name": "New Chart Widget",
  "type": "chart",
  "content": {
    "chartType": "bar",
    "dataSource": "api"
  },
  "isPublic": false
}`
	var createWidgetRequest widgetic.CreateWidgetRequest
	if err := json.Unmarshal([]byte(createWidgetRequestJSON), &createWidgetRequest); err != nil {
		log.Fatal(err)
	}

	result, _, err := client.WidgetsAPI.CreateWidget(ctx).
		IdempotencyKey(uuid.NewString()).
		CreateWidgetRequest(createWidgetRequest).
		Execute()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println(result)
}
```

```java Java theme={"theme":"css-variables"}
import com.widgetic.api.ApiClient;
import com.widgetic.api.ApiException;
import com.widgetic.api.Configuration;
import com.widgetic.api.JSON;
import com.widgetic.api.api.WidgetsApi;
import com.widgetic.api.model.NewWidget;
import java.util.UUID;

public class Example {
    public static void main(String[] args) throws ApiException {
        ApiClient client = Configuration.getDefaultApiClient();
        client.setBearerToken(System.getenv("WIDGETIC_API_KEY"));

        WidgetsApi widgetsApi = new WidgetsApi(client);

        String newWidgetJson = """
                {
                  "name": "New Chart Widget",
                  "type": "chart",
                  "content": {
                    "chartType": "bar",
                    "dataSource": "api"
                  },
                  "isPublic": false
                }
                """;
        NewWidget newWidget = JSON.deserialize(newWidgetJson, NewWidget.class);

        var result = widgetsApi.createWidget(UUID.randomUUID().toString(), newWidget);
        System.out.println(result);
    }
}
```

```csharp C# theme={"theme":"css-variables"}
using System;
using Newtonsoft.Json;
using Widgetic.ApiSdk.Cs.Api;
using Widgetic.ApiSdk.Cs.Client;
using Widgetic.ApiSdk.Cs.Model;

var configuration = new Configuration
{
    AccessToken = Environment.GetEnvironmentVariable("WIDGETIC_API_KEY")!,
};
var widgetsApi = new WidgetsApi(configuration);

var newWidget = JsonConvert.DeserializeObject<NewWidget>("""
    {
      "name": "New Chart Widget",
      "type": "chart",
      "content": {
        "chartType": "bar",
        "dataSource": "api"
      },
      "isPublic": false
    }
    """)!;

var result = widgetsApi.CreateWidget(
    idempotencyKey: Guid.NewGuid().ToString(),
    newWidget: newWidget
);
Console.WriteLine(result);
```

```ruby Ruby theme={"theme":"css-variables"}
require 'securerandom'
require 'api-sdk-rb'

ApiSdkRb.configure do |config|
  config.access_token = ENV['WIDGETIC_API_KEY']
end

widgets_api = ApiSdkRb::WidgetsApi.new

result = widgets_api.create_widget(
  SecureRandom.uuid,
  {
    name: 'New Chart Widget',
    type: 'chart',
    content: {
      chartType: 'bar',
      dataSource: 'api'
    },
    isPublic: false
  }
)
puts result
```

```php PHP theme={"theme":"css-variables"}
<?php

require_once __DIR__ . '/vendor/autoload.php';

use WidgeticApi\Api\WidgetsApi;
use WidgeticApi\Configuration;
use WidgeticApi\Model\NewWidget;
use WidgeticApi\ObjectSerializer;

$config = Configuration::getDefaultConfiguration()->setAccessToken(getenv('WIDGETIC_API_KEY'));
$widgetsApi = new WidgetsApi(new GuzzleHttp\Client(), $config);

$newWidgetJson = '{
  "name": "New Chart Widget",
  "type": "chart",
  "content": {
    "chartType": "bar",
    "dataSource": "api"
  },
  "isPublic": false
}';
$newWidget = ObjectSerializer::deserialize(json_decode($newWidgetJson), NewWidget::class);

$result = $widgetsApi->createWidget(
    idempotency_key: bin2hex(random_bytes(16)),
    new_widget: $newWidget,
);
print_r($result);
```

The API keeps the answer to a call for 24 hours. A retry with the same key gets that answer back, and a retry while the first call is still running gets a `409` that says to wait. See [Idempotency](https://docs.widgetic.com/docs/reference/idempotency.md) for both, and for what a key has to look like.

## Read the headers of an answer

A call returns the body of the answer and, in most languages, nothing else. A few answers say something in a header: `RateLimit-Remaining` and `RateLimit-Reset` (see [Rate limits](https://docs.widgetic.com/docs/reference/rate-limits.md)), and `X-Idempotency-Cached: true` on an answer that was replayed. Each library has a second form of every call that returns them too:

| Language | The call that returns the status and the headers | You read |
| :- | :- | :- |
| TypeScript | `getWidgetsRaw(…)`, the same arguments | `raw.status` and `raw.headers`, and `await value()` for the body |
| Python | `get_widgets_with_http_info(…)` | `status_code`, `headers` and `data` |
| Go | every call, as the second value it returns | the `*http.Response` |
| Java | `getWidgetsWithHttpInfo(…)` | `getStatusCode()`, `getHeaders()` and `getData()` |
| C# | `GetWidgetsWithHttpInfo(…)` | `StatusCode`, `Headers` and `Data` |
| Ruby | `get_widgets_with_http_info(…)` | an array: the data, the status code and the headers |
| PHP | `getWidgetsWithHttpInfo(…)` | an array: the data, the status code and the headers |

`getWidgets` stands for any call: the name of every call takes the same ending (`Raw` in TypeScript, `WithHttpInfo` in Java, C# and PHP, `_with_http_info` in Python and Ruby).

## Handle errors

When the API refuses a call, the library raises an error that holds the status and the body, and the body holds a `code` you can act on, such as `RATE_LIMIT_EXCEEDED`. When nothing answers at all (the network is down, the call timed out) the error is of another kind, and there is no status. This example handles both, and waits for `Retry-After` after a `429`:

```typescript TypeScript theme={"theme":"css-variables"}
import { FetchError, ResponseError, WidgetsApi } from '@widgetic/api-sdk-ts';

const widgetsApi = new WidgetsApi(process.env.WIDGETIC_API_KEY!);

try {
  await widgetsApi.getWidgets({ page: 1, size: 20 });
} catch (error) {
  if (error instanceof ResponseError) {
    // The API answered with an error: read the status and the machine-readable code
    console.error(error.response.status, error.code); // 429 RATE_LIMIT_EXCEEDED

    if (error.response.status === 429) {
      // Wait this many seconds, then send the same request again
      const secondsToWait = Number(error.response.headers.get('retry-after'));
      console.error(`Try again in ${secondsToWait} seconds`);
    }
  } else if (error instanceof FetchError) {
    // The request never got an answer: a network failure or a timeout
    console.error('Network problem:', error.cause);
  } else {
    throw error;
  }
}
```

```python Python theme={"theme":"css-variables"}
import os

import api_sdk_py
from api_sdk_py.exceptions import ApiException
from urllib3.exceptions import HTTPError

configuration = api_sdk_py.Configuration(access_token=os.environ["WIDGETIC_API_KEY"])

with api_sdk_py.ApiClient(configuration) as api_client:
    widgets_api = api_sdk_py.WidgetsApi(api_client)

    try:
        widgets_api.get_widgets(page=1, size=20)
    except ApiException as error:
        # The API answered with an error: the status and the JSON body
        print(error.status, error.body)

        if error.status == 429:
            # Wait this many seconds, then send the same request again
            seconds_to_wait = int(error.headers.get("Retry-After", 1))
            print(f"Try again in {seconds_to_wait} seconds")
    except HTTPError as error:
        # The request never got an answer: a network failure or a timeout
        print("Network problem:", error)
```

```go Go theme={"theme":"css-variables"}
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"strconv"

	widgetic "github.com/widgetic/api-sdk-go"
)

func main() {
	client := widgetic.NewAPIClient(widgetic.NewConfiguration())
	ctx := context.WithValue(context.Background(), widgetic.ContextAccessToken, os.Getenv("WIDGETIC_API_KEY"))

	_, response, err := client.WidgetsAPI.GetWidgets(ctx).Page(1).Size(20).Execute()
	if err != nil {
		var apiError *widgetic.GenericOpenAPIError
		if !errors.As(err, &apiError) {
			// The request never got an answer: a network failure or a timeout
			fmt.Fprintln(os.Stderr, "Network problem:", err)
			return
		}

		// The API answered with an error: the status and the JSON body
		fmt.Fprintln(os.Stderr, response.StatusCode, string(apiError.Body()))

		if response.StatusCode == http.StatusTooManyRequests {
			// Wait this many seconds, then send the same request again
			secondsToWait, _ := strconv.Atoi(response.Header.Get("Retry-After"))
			fmt.Fprintf(os.Stderr, "Try again in %d seconds\n", secondsToWait)
		}
	}
}
```

```java Java theme={"theme":"css-variables"}
import com.widgetic.api.ApiClient;
import com.widgetic.api.ApiException;
import com.widgetic.api.Configuration;
import com.widgetic.api.api.WidgetsApi;
import java.util.List;
import java.util.Map;

public class Errors {
    public static void main(String[] args) {
        ApiClient client = Configuration.getDefaultApiClient();
        client.setBearerToken(System.getenv("WIDGETIC_API_KEY"));

        WidgetsApi widgetsApi = new WidgetsApi(client);

        try {
            widgetsApi.getWidgets(1, 20, null, null, null);
        } catch (ApiException error) {
            if (error.getCode() == 0) {
                // The request never got an answer: a network failure or a timeout
                System.err.println("Network problem: " + error.getCause());
                return;
            }

            // The API answered with an error: the status and the JSON body
            System.err.println(error.getCode() + " " + error.getResponseBody());

            if (error.getCode() == 429) {
                // Wait this many seconds, then send the same request again
                Map<String, List<String>> headers = error.getResponseHeaders();
                int secondsToWait = Integer.parseInt(headers.get("retry-after").get(0));
                System.err.println("Try again in " + secondsToWait + " seconds");
            }
        }
    }
}
```

```csharp C# theme={"theme":"css-variables"}
using System;
using System.Linq;
using Widgetic.ApiSdk.Cs.Api;
using Widgetic.ApiSdk.Cs.Client;

var configuration = new Configuration
{
    AccessToken = Environment.GetEnvironmentVariable("WIDGETIC_API_KEY")!,
};
var widgetsApi = new WidgetsApi(configuration);

try
{
    widgetsApi.GetWidgets(page: 1, size: 20);
}
catch (ApiException error)
{
    if (error.ErrorCode == 0)
    {
        // The request never got an answer: a network failure or a timeout
        Console.Error.WriteLine($"Network problem: {error.ErrorContent}");
        return;
    }

    // The API answered with an error: the status and the JSON body
    Console.Error.WriteLine($"{error.ErrorCode} {error.ErrorContent}");

    if (error.ErrorCode == 429)
    {
        // Wait this many seconds, then send the same request again
        var secondsToWait = int.Parse(error.Headers["Retry-After"].First());
        Console.Error.WriteLine($"Try again in {secondsToWait} seconds");
    }
}
```

```ruby Ruby theme={"theme":"css-variables"}
require 'api-sdk-rb'

ApiSdkRb.configure do |config|
  config.access_token = ENV['WIDGETIC_API_KEY']
end

widgets_api = ApiSdkRb::WidgetsApi.new

begin
  widgets_api.get_widgets(page: 1, size: 20)
rescue ApiSdkRb::ApiError => error
  if error.code == 0
    # The request never got an answer: a network failure or a timeout
    puts "Network problem: #{error.message}"
    exit
  end

  # The API answered with an error: the status and the JSON body
  puts "#{error.code} #{error.response_body}"

  if error.code == 429
    # Wait this many seconds, then send the same request again
    seconds_to_wait = error.response_headers['Retry-After'].to_i
    puts "Try again in #{seconds_to_wait} seconds"
  end
end
```

```php PHP theme={"theme":"css-variables"}
<?php

require_once __DIR__ . '/vendor/autoload.php';

use WidgeticApi\Api\WidgetsApi;
use WidgeticApi\ApiException;
use WidgeticApi\Configuration;

$config = Configuration::getDefaultConfiguration()->setAccessToken(getenv('WIDGETIC_API_KEY'));
$widgetsApi = new WidgetsApi(new GuzzleHttp\Client(), $config);

try {
    $widgetsApi->getWidgets(page: 1, size: 20);
} catch (ApiException $error) {
    if ($error->getCode() === 0) {
        // The request never got an answer: a network failure or a timeout
        echo 'Network problem: ', $error->getMessage(), PHP_EOL;
        exit;
    }

    // The API answered with an error: the status and the JSON body
    echo $error->getCode(), ' ', $error->getResponseBody(), PHP_EOL;

    if ($error->getCode() === 429) {
        // Wait this many seconds, then send the same request again
        $headers = array_change_key_case($error->getResponseHeaders() ?? [], CASE_LOWER);
        $secondsToWait = (int) ($headers['retry-after'][0] ?? 1);
        echo "Try again in {$secondsToWait} seconds", PHP_EOL;
    }
}
```

### What to catch

| Language | The API answered with an error | The call got no answer |
| :- | :- | :- |
| TypeScript | `ResponseError`: `response.status`, `code` | `FetchError`: `cause` |
| Python | `ApiException`: `status`, `body`, `headers` | `urllib3.exceptions.HTTPError` |
| Go | `*widgetic.GenericOpenAPIError`, and the `*http.Response` that comes back beside it | any other error |
| Java | `ApiException`: `getCode()` is the status | `ApiException` whose `getCode()` is `0` |
| C# | `ApiException`: `ErrorCode` is the status | `ApiException` whose `ErrorCode` is `0` |
| Ruby | `ApiSdkRb::ApiError`: `code` is the status | `ApiSdkRb::ApiError` whose `code` is `0` |
| PHP | `ApiException`: `getCode()` is the status | `ApiException` whose `getCode()` is `0` |

The body of an error is the envelope described in [Errors](https://docs.widgetic.com/api-reference/errors.md#error-response-format): `error.code` to act on, `error.message` to show, and a `correlationId` to quote to [the support team](https://docs.widgetic.com/docs/introduction.md#need-help) (see [Using correlation IDs](https://docs.widgetic.com/api-reference/errors.md#using-correlation-ids)).

### What to retry

The libraries leave the retry to you: a `429` or a `503` reaches your code as an error, and the loop is yours to write. The one exception is Python. The HTTP client under it (`urllib3`) sends a `GET`, `PUT` or `DELETE` again, up to three times, when the answer is `429` or `503` with a `Retry-After` header, and waits as long as the header says, so the error reaches your code only after that. A `POST` or a `PATCH` is not sent again. To handle every error yourself, set `retries=0` on the `Configuration`. Which errors are worth another attempt:

| What you got | What to do |
| :- | :- |
| `429` | Wait `Retry-After` seconds, then send the same call again. See [Rate limits](https://docs.widgetic.com/docs/reference/rate-limits.md). |
| `409` with `CONFLICT_IDEMPOTENCY_IN_PROGRESS` | The first attempt is still running. Wait `Retry-After` seconds, then send it again with the **same** key. |
| `500`, `502`, `503` or `504` | Try again a few times, after a pause that grows, with the **same** key. If a `500` keeps coming, quote its `correlationId` to support. |
| No answer | The call may have gone through. Try again with the **same** key, so a call that creates something creates it once. |
| `426` | The library is too old. Update it: see [When a version is too old](https://docs.widgetic.com/docs/sdks/overview.md#when-a-version-is-too-old). |
| Any other `4xx` | Do not retry. The call is wrong: read `error.message`, and fix it. |

[Retry strategies](https://docs.widgetic.com/api-reference/errors.md#retry-strategies) has a backoff loop you can copy.

## Next steps

> [card] [API classes](https://docs.widgetic.com/docs/sdks/api-classes.md)
>
> Find the class and the method for an endpoint

> [card] [Errors](https://docs.widgetic.com/api-reference/errors.md)
>
> Every error code, with what to do about it


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.