> 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 full documentation content in one file, see https://docs.sarvam.ai/llms-full.txt.
> 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/api-reference/byok/auth

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: agents
  version: 1.0.0
paths:
  /auth:
    post:
      operationId: obtainAJwtAccessToken
      summary: Obtain a JWT Access Token
      description: >
        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.
      tags:
        - keyManagement
      parameters:
        - name: Authorization
          in: header
          description: >-
            HTTP Basic authentication for the `/auth` endpoint, using the
            **Client ID** as the username and the **Client Secret** as the
            password.
          required: true
          schema:
            type: string
        - name: x-request-id
          in: header
          description: >-
            A unique identifier for this specific API call, generated by the
            client (Samvaad).
          required: true
          schema:
            type: string
            format: uuid
        - name: x-trace-id
          in: header
          description: An identifier to trace a single request across multiple services.
          required: false
          schema:
            type: string
            format: uuid
        - name: x-request-timestamp
          in: header
          description: The ISO 8601 timestamp of when the client sent the request.
          required: true
          schema:
            type: string
            format: date-time
      responses:
        '200':
          description: Authentication successful. Returns a JWT access token.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AuthSuccessResponse'
        '400':
          description: Bad Request. The request is syntactically malformed.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Unauthorized. The provided Client ID or Client Secret is invalid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          description: >-
            Unprocessable Entity. The request is well-formed but contains
            semantic errors (e.g., wrong grant_type).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: >-
            Internal Server Error. An unexpected error occurred on the
            authentication server.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      requestBody:
        description: The request body must specify the grant type as 'client_credentials'.
        content:
          application/json:
            schema:
              type: object
              properties:
                grant_type:
                  type: string
                  description: The OAuth2 grant type. Must be `client_credentials`.
              required:
                - grant_type
servers:
  - url: https://api.customer.com/sarvam/byok/v1
    description: Production
components:
  schemas:
    AuthBody:
      type: object
      properties:
        access_token:
          type: string
          description: The JWT access token for authorizing subsequent requests.
        token_type:
          type: string
          description: The type of token. Must always be 'Bearer'.
        expires_in:
          type: integer
          description: >-
            The lifetime in seconds of the access token from the time of
            issuance.
      required:
        - access_token
        - token_type
        - expires_in
      description: The response from a successful authentication request.
      title: AuthBody
    AuthSuccessResponse:
      type: object
      properties:
        data:
          $ref: '#/components/schemas/AuthBody'
      required:
        - data
      title: AuthSuccessResponse
    ErrorBody:
      type: object
      properties:
        code:
          type: string
          description: A service-specific error code.
        message:
          type: string
          description: A human-readable description of the error.
      required:
        - code
        - message
      description: Details of the error that occurred.
      title: ErrorBody
    ErrorResponse:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/ErrorBody'
      required:
        - error
      description: A standard wrapper for all error responses.
      title: ErrorResponse
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic
      description: >-
        HTTP Basic authentication for the `/auth` endpoint, using the **Client
        ID** as the username and the **Client Secret** as the password.

```

## 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()
```