# Phone numbers

> List your organization's phone numbers, and choose the agent each one belongs to.

Your phone numbers are added in the console, on the **Telephony** page, where each is connected to
your carrier. Through the API you can list them and choose which agent each one belongs to.

## List them

**curl**

```sh
#!/bin/sh
# List phone numbers
curl -sS --fail-with-body -X GET "https://api.aigently.ai/v1/phone-numbers" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY"
```

**JavaScript**

```js
// List phone numbers
const response = await fetch("https://api.aigently.ai/v1/phone-numbers", {
  method: "GET",
  headers: {
    Authorization: `Bearer ${process.env.AIGENTLY_API_KEY}`,
  },
});
const answer = await response.json();
if (!response.ok) throw new Error(`${answer.code}: ${answer.detail}`);
console.log(answer);
```

**Python**

```python
# List phone numbers
# pip install httpx
import os

import httpx

response = httpx.get(
    "https://api.aigently.ai/v1/phone-numbers",
    headers={
        "Authorization": f"Bearer {os.environ['AIGENTLY_API_KEY']}",
    },
)
if response.is_error:
    raise SystemExit(response.text)
print(response.json())
```

**Go**

```go
// List phone numbers
package main

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

func main() {
	request, err := http.NewRequest("GET", "https://api.aigently.ai/v1/phone-numbers", nil)
	if err != nil {
		panic(err)
	}
	request.Header.Set("Authorization", "Bearer "+os.Getenv("AIGENTLY_API_KEY"))
	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
// List phone numbers
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 {
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.aigently.ai/v1/phone-numbers"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .method("GET", HttpRequest.BodyPublishers.noBody())
            .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
// List phone numbers
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.Get, "https://api.aigently.ai/v1/phone-numbers")
{
};
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
// List phone numbers
$curl = curl_init("https://api.aigently.ai/v1/phone-numbers");
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("AIGENTLY_API_KEY"),
    ],
]);
$body = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) >= 400) {
    fwrite(STDERR, $body . "\n");
    exit(1);
}
echo $body, "\n";
```

This needs `phone_numbers:read`. Each number says which way it carries calls, whether it is in
service, and the agent it belongs to. `can_receive_calls` and `can_place_calls` say whether it works
right now: a number still waiting to be verified, or switched off, cannot. Use a number that can
place calls as `phone_number_id` when you [place a call](/guides/outbound-calls).

## Point a number at an agent

**curl**

```sh
#!/bin/sh
# Point a number at an agent. With a live key: a phone number is real.
curl -sS --fail-with-body -X PATCH "https://api.aigently.ai/v1/phone-numbers/7a9c1e3f-5b7d-4f9a-8c2e-4d6f8a0c2e4a" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY" \
  --json '{
  "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f"
}'
```

**JavaScript**

```js
// Point a number at an agent. With a live key: a phone number is real.
const response = await fetch("https://api.aigently.ai/v1/phone-numbers/7a9c1e3f-5b7d-4f9a-8c2e-4d6f8a0c2e4a", {
  method: "PATCH",
  headers: {
    Authorization: `Bearer ${process.env.AIGENTLY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f"
  }),
});
const answer = await response.json();
if (!response.ok) throw new Error(`${answer.code}: ${answer.detail}`);
console.log(answer);
```

**Python**

```python
# Point a number at an agent. With a live key: a phone number is real.
# pip install httpx
import os

import httpx

response = httpx.patch(
    "https://api.aigently.ai/v1/phone-numbers/7a9c1e3f-5b7d-4f9a-8c2e-4d6f8a0c2e4a",
    headers={
        "Authorization": f"Bearer {os.environ['AIGENTLY_API_KEY']}",
    },
    json={
        "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
    },
)
if response.is_error:
    raise SystemExit(response.text)
print(response.json())
```

**Go**

```go
// Point a number at an agent. With a live key: a phone number is real.
package main

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

func main() {
	payload := []byte(`{
  "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f"
}`)
	request, err := http.NewRequest("PATCH", "https://api.aigently.ai/v1/phone-numbers/7a9c1e3f-5b7d-4f9a-8c2e-4d6f8a0c2e4a", 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")
	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
// Point a number at an agent. With a live key: a phone number is real.
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"
            }
            """;
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.aigently.ai/v1/phone-numbers/7a9c1e3f-5b7d-4f9a-8c2e-4d6f8a0c2e4a"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .header("Content-Type", "application/json")
            .method("PATCH", 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
// Point a number at an agent. With a live key: a phone number is real.
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.Patch, "https://api.aigently.ai/v1/phone-numbers/7a9c1e3f-5b7d-4f9a-8c2e-4d6f8a0c2e4a")
{
    Content = new StringContent(
        """
        {
          "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f"
        }
        """,
        Encoding.UTF8,
        "application/json"),
};
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
// Point a number at an agent. With a live key: a phone number is real.
$curl = curl_init("https://api.aigently.ai/v1/phone-numbers/7a9c1e3f-5b7d-4f9a-8c2e-4d6f8a0c2e4a");
curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => "PATCH",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("AIGENTLY_API_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "agent_id" => "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
    ]),
]);
$body = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) >= 400) {
    fwrite(STDERR, $body . "\n");
    exit(1);
}
echo $body, "\n";
```

This needs `phone_numbers:write`, a permission no starting point in the console includes, and a
**live key**: a phone number is real, so a test key is refused with `403 live_key_required`.

- A number that only receives calls rings its agent, so the agent must be an inbound agent that
  answers phone calls.
- A number that only places calls is the caller ID of an outbound agent.
- A number that does both can belong to either. An inbound agent answers it; an outbound agent calls
  from it, and calls back to it go where that agent's **When somebody calls back** setting says.
- The agent must be in the number's project.

A mismatch is refused with `409 number_agent_mismatch`, and `detail` says what to change. Send
`"agent_id": null` to leave the number with no agent. The change takes effect on the next call; a
call already in progress is not affected.

If the number's previous agent made calls from it, that agent keeps calling from it: only the
owner changes. Each change is recorded in your organization's audit log under the key.

## What a key sees

A key limited to some projects lists their numbers alone. A key limited to some agents lists the
numbers those agents own or call from, and moves a number only between those agents.
