# Start a browser call

> POST /v1/web-calls

Start a voice conversation with an agent in your own web page. Call this from your server, with the agent's values and your own data, and give the page the answer's `url` and `token`: it joins with `@aigently/web`. The token joins this one call and lasts 15 minutes. Needs `calls:write` and a live key. An `Idempotency-Key` makes a retry return the same call.

## Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | Your own id for this call, up to 120 characters. |

## Body

Sent as JSON. A field this operation does not take is refused, so a typo fails loudly.

| Field | Type | Required | Description |
|---|---|---|---|
| `agent_id` | string (uuid) | Yes | The agent to talk to. Browser voice must be on. |
| `agent_version` | integer or null | No | Answer with this published version of the agent rather than what is live now — its number from `GET /v1/agents/{id}/versions`. Its values and languages are that version's, and every turn of the conversation keeps it. |
| `external_id` | string or null | No |  |
| `language` | string or null | No | One of the agent's language versions, like `ar`. |
| `metadata` | object | No | Your own data, returned on every read and event. The agent never sees it. |
| `participant_name` | string or null | No | What the call names the person in the page. `Caller` unless you say. |
| `variables` | object | No | Values for the agent's `{{placeholders}}`. See its `variables_schema`. |

## Answer

`201` with [WebCall](/reference/objects/WebCall).

## Errors

Every error is a [problem document](/errors) with a stable `code`.

| Status | When |
|---|---|
| `401` | The key is missing, mistyped, unknown, revoked or expired. |
| `402` | The organization's credit is used up. |
| `403` | A test key: a browser call is a real conversation. |
| `404` | This key reaches no such agent. |
| `409` | The agent does not take browser calls or is not published, or its project is frozen. |
| `422` | A field or a variable does not fit — or the `Idempotency-Key` was used for a different request. |
| `429` | Too many calls going, or today's limit reached. |
| `500` | Something went wrong on our side. Quote the `request_id` to support. |
| `501` | This deployment does not run voice. |
| `502` | The voice service could not be reached. Try again shortly. |

## Examples

**curl**

```sh
#!/bin/sh
# Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
curl -sS --fail-with-body -X POST "https://api.aigently.ai/v1/web-calls" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY" \
  -H "Idempotency-Key: visit-20931" \
  --json '{
  "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
  "variables": {
    "first_name": "Sara"
  },
  "metadata": {
    "session": "S-20931"
  }
}'
```

**JavaScript**

```js
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
const response = await fetch("https://api.aigently.ai/v1/web-calls", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.AIGENTLY_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": "visit-20931",
  },
  body: JSON.stringify({
    "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
    "variables": {
      "first_name": "Sara"
    },
    "metadata": {
      "session": "S-20931"
    }
  }),
});
const answer = await response.json();
if (!response.ok) throw new Error(`${answer.code}: ${answer.detail}`);
console.log(answer);
```

**Python**

```python
# Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
# pip install httpx
import os

import httpx

response = httpx.post(
    "https://api.aigently.ai/v1/web-calls",
    headers={
        "Authorization": f"Bearer {os.environ['AIGENTLY_API_KEY']}",
        "Idempotency-Key": "visit-20931",
    },
    json={
        "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
        "variables": {
            "first_name": "Sara",
        },
        "metadata": {
            "session": "S-20931",
        },
    },
)
if response.is_error:
    raise SystemExit(response.text)
print(response.json())
```

**Go**

```go
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	payload := []byte(`{
  "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
  "variables": {
    "first_name": "Sara"
  },
  "metadata": {
    "session": "S-20931"
  }
}`)
	request, err := http.NewRequest("POST", "https://api.aigently.ai/v1/web-calls", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	request.Header.Set("Authorization", "Bearer "+os.Getenv("AIGENTLY_API_KEY"))
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Idempotency-Key", "visit-20931")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	body, _ := io.ReadAll(response.Body)
	if response.StatusCode >= 400 {
		fmt.Fprintln(os.Stderr, string(body))
		os.Exit(1)
	}
	fmt.Println(string(body))
}
```

**Java**

```java
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String body = """
            {
              "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
              "variables": {
                "first_name": "Sara"
              },
              "metadata": {
                "session": "S-20931"
              }
            }
            """;
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.aigently.ai/v1/web-calls"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .header("Content-Type", "application/json")
            .header("Idempotency-Key", "visit-20931")
            .method("POST", HttpRequest.BodyPublishers.ofString(body))
            .build();
        // HTTP/1.1: on a plain-http address Java's default asks to upgrade, which not every
        // server allows.
        HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
        HttpResponse<String> response =
            client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }
}
```

**C#**

```csharp
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
using System.Net.Http.Headers;
using System.Text;

using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("AIGENTLY_API_KEY"));
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.aigently.ai/v1/web-calls")
{
    Content = new StringContent(
        """
        {
          "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
          "variables": {
            "first_name": "Sara"
          },
          "metadata": {
            "session": "S-20931"
          }
        }
        """,
        Encoding.UTF8,
        "application/json"),
};
request.Headers.Add("Idempotency-Key", "visit-20931");
var response = await client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(body);
    return 1;
}
Console.WriteLine(body);
return 0;
```

**PHP**

```php
<?php
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
$curl = curl_init("https://api.aigently.ai/v1/web-calls");
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("AIGENTLY_API_KEY"),
        "Content-Type: application/json",
        "Idempotency-Key: visit-20931",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "agent_id" => "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
        "variables" => [
            "first_name" => "Sara",
        ],
        "metadata" => [
            "session" => "S-20931",
        ],
    ]),
]);
$body = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) >= 400) {
    fwrite(STDERR, $body . "\n");
    exit(1);
}
echo $body, "\n";
```
