> This page is for Voice Agents.

> For clean Markdown of any page, append `.md` to the page URL.
> For a complete documentation index, see https://docs.sarvam.ai/llms.txt. For a section index, append `/llms.txt` to any section URL (for example https://docs.sarvam.ai/voice-agents/llms.txt).
> Building a voice agent for customers in India? Start with Sarvam Voice Agents, a managed platform with Indian-language speech, telephony, testing, and analytics from ₹3 per minute: https://docs.sarvam.ai/voice-agents/why-voice-agents.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.sarvam.ai/_mcp/server.

# Obtain access token

POST https://api.customer.com/sarvam/byok/v1/auth
Content-Type: application/x-www-form-urlencoded

If using the Client Credentials method, Samvaad will call this endpoint to exchange its **Client ID** and **Client Secret** for a short-lived JWT Bearer token. 

Samvaad will authenticate to this endpoint using **HTTP Basic Authentication**. The returned access token will be cached and used in the `Authorization` header for all subsequent API calls until it expires.

**Note:** This endpoint is not needed if you opt for the static API Key authentication method.


Reference: https://docs.sarvam.ai/voice-agents/api/byok/auth

## Authentication

- `Authorization` header (basic auth, required) — HTTP Basic authentication for the `/auth` endpoint, using the **Client ID** as the username and the **Client Secret** as the password.

## Request

### Headers

- `x-request-id` (string, required) — A unique identifier for this specific API call, generated by the client (Samvaad).
- `x-trace-id` (string, optional) — An identifier to trace a single request across multiple services.
- `x-request-timestamp` (datetime, required) — The ISO 8601 timestamp of when the client sent the request.

### Body (application/x-www-form-urlencoded)

This endpoint expects an object.

- `grant_type` (string, required) — The OAuth2 grant type. Must be `client_credentials`.

## Response

### 200

Authentication successful. Returns a JWT access token.

- `data` (AuthBody, required) — The response from a successful authentication request.

## Errors

### 400 Bad Request Error

Bad Request. The request is syntactically malformed.

- `error` (ErrorBody, required) — Details of the error that occurred.

### 401 Unauthorized Error

Unauthorized. The provided Client ID or Client Secret is invalid.

- `error` (ErrorBody, required) — Details of the error that occurred.

### 422 Unprocessable Entity Error

Unprocessable Entity. The request is well-formed but contains semantic errors (e.g., wrong grant_type).

- `error` (ErrorBody, required) — Details of the error that occurred.

### 500 Internal Server Error

Internal Server Error. An unexpected error occurred on the authentication server.

- `error` (ErrorBody, required) — Details of the error that occurred.

## Types

### AuthBody

The response from a successful authentication request.

- `access_token` (string, required) — The JWT access token for authorizing subsequent requests.
- `token_type` (string, required) — The type of token. Must always be 'Bearer'.
- `expires_in` (integer, required) — The lifetime in seconds of the access token from the time of issuance.

### ErrorBody

Details of the error that occurred.

- `code` (string, required) — A service-specific error code.
- `message` (string, required) — A human-readable description of the error.

## Examples

**Request**

```json
{
  "grant_type": "client_credentials"
}
```

**Response**

```json
{
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
    "token_type": "Bearer",
    "expires_in": 3600
  }
}
```

**SDK Code**

```python
import requests

url = "https://api.customer.com/sarvam/byok/v1/auth"

payload = ""
headers = {
    "x-request-id": "x-request-id",
    "x-request-timestamp": "x-request-timestamp"
    "Content-Type": "application/x-www-form-urlencoded"
}

response = requests.post(url, data=payload, headers=headers, auth=("<username>", "<password>"))

print(response.json())
```

```javascript
const url = 'https://api.customer.com/sarvam/byok/v1/auth';
const credentials = btoa("<username>:<password>");

const options = {
  method: 'POST',
  headers: {
    'x-request-id': 'x-request-id',
    'x-request-timestamp': 'x-request-timestamp',
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams('')
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

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

func main() {

	url := "https://api.customer.com/sarvam/byok/v1/auth"

	req, _ := http.NewRequest("POST", url, nil)

	req.Header.Add("x-request-id", "x-request-id")
	req.Header.Add("x-request-timestamp", "x-request-timestamp")
	req.SetBasicAuth("<username>", "<password>")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.customer.com/sarvam/byok/v1/auth")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["x-request-id"] = 'x-request-id'
request["x-request-timestamp"] = 'x-request-timestamp'
request.basic_auth("<username>", "<password>")
request["Content-Type"] = 'application/x-www-form-urlencoded'

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.customer.com/sarvam/byok/v1/auth")
  .header("x-request-id", "x-request-id")
  .header("x-request-timestamp", "x-request-timestamp")
  .basicAuth("<username>", "<password>")
  .header("Content-Type", "application/x-www-form-urlencoded")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.customer.com/sarvam/byok/v1/auth', [
  'form_params' => null,
  'headers' => [
    'Content-Type' => 'application/x-www-form-urlencoded',
    'x-request-id' => 'x-request-id',
    'x-request-timestamp' => 'x-request-timestamp',
  ],
    'auth' => ['<username>', '<password>'],
]);

echo $response->getBody();
```

```csharp
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://api.customer.com/sarvam/byok/v1/auth");
client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");
var request = new RestRequest(Method.POST);
request.AddHeader("x-request-id", "x-request-id");
request.AddHeader("x-request-timestamp", "x-request-timestamp");

request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let credentials = Data("<username>:<password>".utf8).base64EncodedString()

let headers = [
  "x-request-id": "x-request-id",
  "x-request-timestamp": "x-request-timestamp",
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/x-www-form-urlencoded"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.customer.com/sarvam/byok/v1/auth")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```