# Start linking a program to an account

> For a program that cannot show a login form, such as a chat bot. Returns a secret device_code to poll with and a short user_code to show the person, who opens verification_url in a browser, checks the code and approves. What the key may do is fixed by the client kind, not asked for. Rate limited per IP.

Source: https://tools.vukem.dev/docs/api/devicelinks.start/

## Authentication

No key is needed: the codes in the exchange are the credential. This route is limited per address. See [Authentication](/docs/api/overview#authentication).

## Request body

Content type `application/json`.

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `client` | `string` | yes | The kind of program asking. It decides what the key may do: the server fixes the abilities, the program cannot choose them. one of `telegram`; min length 1 |
| `device_name` | `string` | no | A label for the key in the account's key list, such as the Telegram name of the person. Optional. max length 64 |

## Responses

### 201 Created

Content type `application/json`. Schema: [`LinkStarted`](/docs/api/schemas#linkstarted).

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `device_code` | `string` | - | Secret to poll with. Never show it to the person |
| `expires_in` | `integer` | - | Seconds until the link can no longer be approved |
| `interval` | `integer` | - | Seconds to wait between polls |
| `user_code` | `string` | - | The short code to show the person, formatted XXXX-XXXX |
| `verification_url` | `string` | - | Where the person approves. It already contains the user code |

### 422 Unprocessable Content

Content type `application/problem+json`. Validation failed; errors maps each field to its messages and issues lists each problem with its code, key and params. Schema: [`Problem`](/docs/api/schemas#problem).

The error follows RFC 9457. See [Errors](/docs/api/overview#errors).

### Any other status

Content type `application/problem+json`. Error (RFC 9457 problem details). Schema: [`Problem`](/docs/api/schemas#problem).

The error follows RFC 9457. See [Errors](/docs/api/overview#errors).

```bash
curl -X POST "http://localhost:3000/api/v1/device-links" \
  -H "Content-Type: application/json" \
  -d '{
  "client": "telegram",
  "device_name": "Telegram: ana"
}'
```

```python
import requests

response = requests.post(
    "http://localhost:3000/api/v1/device-links",
    json={
        "client": "telegram",
        "device_name": "Telegram: ana",
    },
    timeout=30,
)
response.raise_for_status()
print(response.json())
```

```javascript
const response = await fetch("http://localhost:3000/api/v1/device-links", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "client": "telegram",
    "device_name": "Telegram: ana"
  }),
});
if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
console.log(await response.json());
```

```go
package main

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

func main() {
	body := strings.NewReader(`{
  "client": "telegram",
  "device_name": "Telegram: ana"
}`)
	req, err := http.NewRequest("POST", "http://localhost:3000/api/v1/device-links", body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	out, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Status, string(out))
}
```

```php
<?php

$ch = curl_init("http://localhost:3000/api/v1/device-links");
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => '{
  "client": "telegram",
  "device_name": "Telegram: ana"
}',
]);

$response = curl_exec($ch);
if ($response === false) {
    throw new RuntimeException(curl_error($ch));
}
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $response, PHP_EOL;
```

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Example {
    public static void main(String[] args) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:3000/api/v1/device-links"))
            .header("Content-Type", "application/json")
            .method("POST", HttpRequest.BodyPublishers.ofString("""
                {
                  "client": "telegram",
                  "device_name": "Telegram: ana"
                }
                """))
            .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

```csharp
using System;
using System.Net.Http;
using System.Text;

using var client = new HttpClient();
using var request = new HttpRequestMessage(
    HttpMethod.Post, "http://localhost:3000/api/v1/device-links");
request.Content = new StringContent("""
{
  "client": "telegram",
  "device_name": "Telegram: ana"
}
""", Encoding.UTF8, "application/json");

using var response = await client.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

```ruby
require "net/http"
require "uri"

uri = URI("http://localhost:3000/api/v1/device-links")
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request.body = '{
  "client": "telegram",
  "device_name": "Telegram: ana"
}'

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
  http.request(request)
end
puts "#{response.code} #{response.body}"
```

**Response examples**

```json
{
  "device_code": "kV3x0Zp8mQ1sT9nL2aR7wYc4HbU6eGdJ5oFiNtX-AqE",
  "expires_in": 600,
  "interval": 3,
  "user_code": "BCDF-2346",
  "verification_url": "http://localhost:3000/account/link?code=BCDF-2346"
}
```

```json
{
  "detail": "1 field(s) are invalid.",
  "errors": {
    "abilities": [
      "Unknown abilities: image:resize. Allowed: pixels:svg, ..."
    ]
  },
  "instance": "/api/v1/tokens",
  "request_id": "01JQZ8R4T6WQ2N9K3V5Y7B0C1D",
  "status": 422,
  "title": "Validation failed",
  "type": "about:blank"
}
```

The examples are built from the schemas, so every value is a placeholder of its type. The tables above hold the fields that carry the real values.
