# Place a call

> POST /v1/calls

Call a phone number with one of your outbound agents. Answers `201` with the conversation, `pending` until the phone is answered. Needs `calls:write` and an `Idempotency-Key`: the same request sent again with the same key returns the same conversation instead of calling twice.

## Parameters

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

## 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 outbound agent that makes the call. |
| `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. |
| `call_window` | [CallWindow](/reference/objects/CallWindow) or null | No | Only start the call within these hours. Outside them it is refused with `outside_call_window`, which says when the window opens — schedule it for then with `POST /v1/scheduled-calls`. |
| `external_id` | string or null | No |  |
| `from_number` | string or null | No | One of the agent's numbers to call from. Or send `phone_number_id`, never both; with neither, the agent's own number. |
| `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. |
| `phone_number_id` | string (uuid) or null | No | One of the agent's numbers to call from, by its id. |
| `to_number` | string | Yes | The number to call, in international format, like `+966501234567`. |
| `variables` | object | No | Values for the agent's `{{placeholders}}` — text, numbers or true/false. See the agent's `variables_schema`. |

## Answer

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

## Errors

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

| Status | When |
|---|---|
| `400` | No `Idempotency-Key`, or one longer than 120 characters. |
| `401` | The key is missing, mistyped, unknown, revoked or expired. |
| `402` | The organization's credit is used up. |
| `403` | The key lacks a permission, a live key was sent from a browser, or the organization is frozen and the request would change something. |
| `404` | This key reaches no such agent. |
| `409` | The agent does not place calls or is not published, or its project is frozen. |
| `413` | The request is larger than 64 KB. |
| `422` | A field, a variable, the number to call or the number to call from does not fit — or the `Idempotency-Key` was already used for a different request. |
| `429` | Too many requests for this key or its organization; see `Retry-After`. |
| `500` | Something went wrong on our side. Quote the `request_id` to support. |
| `501` | This deployment does not place phone calls. |
| `502` | The call could not be placed. Try again shortly. |

## Examples

**curl**

```sh
#!/bin/sh
# Place a call. With a test key this calls a test number and rings nobody.
curl -sS --fail-with-body -X POST "https://api.aigently.ai/v1/calls" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY" \
  -H "Idempotency-Key: lead-20931" \
  --json '{
  "agent_id": "8a1f3c2e-0b6d-4f5e-9a7c-2d4e6f8a0b1c",
  "to_number": "+12025550100",
  "variables": {
    "first_name": "Sara"
  },
  "metadata": {
    "crm_lead_id": "L-20931"
  },
  "external_id": "lead-20931"
}'
```

**JavaScript**

```js
// Place a call. With a test key this calls a test number and rings nobody.
const response = await fetch("https://api.aigently.ai/v1/calls", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.AIGENTLY_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": "lead-20931",
  },
  body: JSON.stringify({
    "agent_id": "8a1f3c2e-0b6d-4f5e-9a7c-2d4e6f8a0b1c",
    "to_number": "+12025550100",
    "variables": {
      "first_name": "Sara"
    },
    "metadata": {
      "crm_lead_id": "L-20931"
    },
    "external_id": "lead-20931"
  }),
});
const answer = await response.json();
if (!response.ok) throw new Error(`${answer.code}: ${answer.detail}`);
console.log(answer);
```

**Python**

```python
# Place a call. With a test key this calls a test number and rings nobody.
# pip install httpx
import os

import httpx

response = httpx.post(
    "https://api.aigently.ai/v1/calls",
    headers={
        "Authorization": f"Bearer {os.environ['AIGENTLY_API_KEY']}",
        "Idempotency-Key": "lead-20931",
    },
    json={
        "agent_id": "8a1f3c2e-0b6d-4f5e-9a7c-2d4e6f8a0b1c",
        "to_number": "+12025550100",
        "variables": {
            "first_name": "Sara",
        },
        "metadata": {
            "crm_lead_id": "L-20931",
        },
        "external_id": "lead-20931",
    },
)
if response.is_error:
    raise SystemExit(response.text)
print(response.json())
```

**Go**

```go
// Place a call. With a test key this calls a test number and rings nobody.
package main

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

func main() {
	payload := []byte(`{
  "agent_id": "8a1f3c2e-0b6d-4f5e-9a7c-2d4e6f8a0b1c",
  "to_number": "+12025550100",
  "variables": {
    "first_name": "Sara"
  },
  "metadata": {
    "crm_lead_id": "L-20931"
  },
  "external_id": "lead-20931"
}`)
	request, err := http.NewRequest("POST", "https://api.aigently.ai/v1/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", "lead-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
// Place a call. With a test key this calls a test number and rings nobody.
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": "8a1f3c2e-0b6d-4f5e-9a7c-2d4e6f8a0b1c",
              "to_number": "+12025550100",
              "variables": {
                "first_name": "Sara"
              },
              "metadata": {
                "crm_lead_id": "L-20931"
              },
              "external_id": "lead-20931"
            }
            """;
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.aigently.ai/v1/calls"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .header("Content-Type", "application/json")
            .header("Idempotency-Key", "lead-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
// Place a call. With a test key this calls a test number and rings nobody.
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/calls")
{
    Content = new StringContent(
        """
        {
          "agent_id": "8a1f3c2e-0b6d-4f5e-9a7c-2d4e6f8a0b1c",
          "to_number": "+12025550100",
          "variables": {
            "first_name": "Sara"
          },
          "metadata": {
            "crm_lead_id": "L-20931"
          },
          "external_id": "lead-20931"
        }
        """,
        Encoding.UTF8,
        "application/json"),
};
request.Headers.Add("Idempotency-Key", "lead-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
// Place a call. With a test key this calls a test number and rings nobody.
$curl = curl_init("https://api.aigently.ai/v1/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: lead-20931",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "agent_id" => "8a1f3c2e-0b6d-4f5e-9a7c-2d4e6f8a0b1c",
        "to_number" => "+12025550100",
        "variables" => [
            "first_name" => "Sara",
        ],
        "metadata" => [
            "crm_lead_id" => "L-20931",
        ],
        "external_id" => "lead-20931",
    ]),
]);
$body = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) >= 400) {
    fwrite(STDERR, $body . "\n");
    exit(1);
}
echo $body, "\n";
```
