> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.bakbak.si/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.bakbak.si/_mcp/server.

# Stream speech

POST https://hub.getraya.app/v1/text-to-speech/stream
Content-Type: application/json

Generates audio from text using Server-Sent Events (SSE) format. Audio chunks are
streamed in real-time as base64-encoded audio. This endpoint is optimized
for low-latency applications where audio playback should start as soon as possible.

By default each chunk is PCM F32LE (32-bit float). Send `output_format` to receive `pcm_s16le`, `pcm_mulaw` or `pcm_alaw` instead, at 8000, 16000, 22050 or 24000 Hz. The stream is always raw audio, so `output_format.container` must be `raw`. With `output_format`, the response also carries `X-Audio-Format`, `X-Audio-Sample-Rate` and `X-Audio-Channels`. See [Output Formats](/text-to-speech/output-formats).

The response is a stream of SSE events:
- `event: chunk` - Contains base64-encoded audio data
- `event: done` - Signals completion of audio generation

Each chunk event contains:
- `type`: "chunk"
- `status_code`: 206 (Partial Content)
- `done`: false
- `data`: Base64-encoded audio chunk, in the `output_format` encoding (PCM F32LE by default)
- `step_time`: Time taken to generate this chunk in seconds


Reference: https://docs.bakbak.si/api-reference/text-to-speech/stream-speech

## Authentication

- `X-API-Key` header (required) — API key for authentication. Example: raya_ABCD1234567890abcdef

## Request

### Body (application/json)

This endpoint expects a TTSRequest.

- `text` (string, required) — The text to convert to speech. **Script notes:** - Hindi (`language`: `hi`) must be in Devanagari script. Romanized Hindi is not supported. - For English (`en-in`, `en-us`), Indic named entities (names, places, etc.) are pronounced more accurately in Devanagari — e.g. `राहुल` instead of `Rahul`. If text is LLM-generated, prompt it to output Indic names in Devanagari even when the rest of the content is in English.
- `voice_id` (string, required) — The ID of the voice to use for synthesis. Use `/v1/voices` to get available voice IDs. The `voice_id` must match the `model` you specify — `standard` voices only work with `"model": "standard"`, and `m1` voices only work with `"model": "m1"`.
- `language` (enum, required) — Language code for the text. Currently supported: hi (Hindi), mr (Marathi), te (Telugu), kn (Kannada), bn (Bengali), as (Assamese), gu (Gujarati), ne (Nepali), ml (Malayalam), ta (Tamil), en (English, used by m1 voices), en-in (Indian English), en-us (US English). Hindi must be written in Devanagari script (Romanized Hindi is not supported). For English, Indic named entities are best written in Devanagari for accurate pronunciation. More languages are coming soon.
  - Allowed values: `hi`, `mr`, `te`, `kn`, `bn`, `as`, `gu`, `ne`, `ml`, `ta`, `en`, `en-in`, `en-us`
- `model` (enum, optional, default: standard) — The synthesis model to use. Each model has its own set of voices — use `/v1/voices` to find voice IDs for the model you choose. **Important:** `standard` and `m1` voices are not interchangeable. Passing a `standard` voice ID with `"model": "m1"` (or vice versa) will fail.
  - Allowed values: `standard`, `m1`
- `speed` (float, optional, default: 1) — Speech speed multiplier (0.5 to 1.5). Changes standard voices only; m1 voices ignore it.
- `output_format` (OutputFormat, optional) — Encoding and sample rate of the audio chunks. Only the `raw` container is accepted on the WebSocket.

## Response

### 200

Streaming audio generation started

- Streaming response of `string`.

## Errors

### 400 Bad Request Error

Bad request, for example empty `text`

- `detail` (string, optional) — Error message describing what went wrong

### 404 Not Found Error

Voice ID not found

- `detail` (string, optional) — Error message describing what went wrong

### 422 Unprocessable Entity Error

Validation error. Each invalid field has its own entry in `detail`, and `loc` is the path to it.

- `detail` (list of ValidationErrorEntry, optional)

### 500 Internal Server Error

Internal server error

- `detail` (string, optional) — Error message describing what went wrong

## Types

### OutputFormat

Encoding and sample rate of the audio chunks. Only the `raw` container is accepted on the WebSocket.

- `container` (enum, optional, default: raw) — `raw` for headerless audio, `wav` for a WAV file, `mp3` for MP3. `wav` and `mp3` are only available on `/v1/text-to-speech`; the streaming endpoint accepts only `raw`.
  - Allowed values: `raw`
- `encoding` (enum, optional) — Sample encoding. Required for `raw` and `wav`; omit it for `mp3`. Audio is always mono. - `pcm_f32le`: 32-bit float, little-endian - `pcm_s16le`: 16-bit signed integer, little-endian - `pcm_mulaw`: G.711 μ-law (PCMU), 1 byte per sample - `pcm_alaw`: G.711 A-law (PCMA), 1 byte per sample
  - Allowed values: `pcm_f32le`, `pcm_s16le`, `pcm_mulaw`, `pcm_alaw`
- `sample_rate` (enum, optional, default: 24000) — Sample rate in Hz.
  - Allowed values: `8000`, `16000`, `22050`, `24000`

### ValidationErrorEntry

- `type` (string, optional) — Machine-readable kind of problem, such as `missing` or `value_error`.
- `loc` (list of ValidationErrorEntryLocItems, optional) — Path to the invalid field, for example `["body", "output_format", "encoding"]`.
- `msg` (string, optional) — Human-readable description of the problem.
- `input` (any, optional) — The rejected value, when it can be echoed back.
- `ctx` (ValidationErrorEntryCtx, optional) — Additional context. Present on `value_error` entries.

### ValidationErrorEntryLocItems

- string
- integer

### ValidationErrorEntryCtx

Additional context. Present on `value_error` entries.

## Examples

### 16-bit PCM with output_format

**Request**

```json
{
  "text": "Hello, this is a test message.",
  "voice_id": "voice_001",
  "language": "hi",
  "model": "standard",
  "speed": 1,
  "output_format": {
    "container": "raw",
    "encoding": "pcm_s16le",
    "sample_rate": 24000
  }
}
```

**SDK Code**

```python 16-bit PCM with output_format
import requests

url = "https://hub.getraya.app/v1/text-to-speech/stream"

payload = {
    "text": "Hello, this is a test message.",
    "voice_id": "voice_001",
    "language": "hi",
    "model": "standard",
    "speed": 1,
    "output_format": {
        "container": "raw",
        "encoding": "pcm_s16le",
        "sample_rate": 24000
    }
}
headers = {
    "X-API-Key": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 16-bit PCM with output_format
const url = 'https://hub.getraya.app/v1/text-to-speech/stream';
const options = {
  method: 'POST',
  headers: {'X-API-Key': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"text":"Hello, this is a test message.","voice_id":"voice_001","language":"hi","model":"standard","speed":1,"output_format":{"container":"raw","encoding":"pcm_s16le","sample_rate":24000}}'
};

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

```go 16-bit PCM with output_format
package main

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

func main() {

	url := "https://hub.getraya.app/v1/text-to-speech/stream"

	payload := strings.NewReader("{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"speed\": 1,\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_s16le\",\n    \"sample_rate\": 24000\n  }\n}")

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

	req.Header.Add("X-API-Key", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

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

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

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

}
```

```ruby 16-bit PCM with output_format
require 'uri'
require 'net/http'

url = URI("https://hub.getraya.app/v1/text-to-speech/stream")

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

request = Net::HTTP::Post.new(url)
request["X-API-Key"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"speed\": 1,\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_s16le\",\n    \"sample_rate\": 24000\n  }\n}"

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

```java 16-bit PCM with output_format
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://hub.getraya.app/v1/text-to-speech/stream")
  .header("X-API-Key", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"speed\": 1,\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_s16le\",\n    \"sample_rate\": 24000\n  }\n}")
  .asString();
```

```php 16-bit PCM with output_format
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://hub.getraya.app/v1/text-to-speech/stream', [
  'body' => '{
  "text": "Hello, this is a test message.",
  "voice_id": "voice_001",
  "language": "hi",
  "model": "standard",
  "speed": 1,
  "output_format": {
    "container": "raw",
    "encoding": "pcm_s16le",
    "sample_rate": 24000
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-API-Key' => '<apiKey>',
  ],
]);

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

```csharp 16-bit PCM with output_format
using RestSharp;

var client = new RestClient("https://hub.getraya.app/v1/text-to-speech/stream");
var request = new RestRequest(Method.POST);
request.AddHeader("X-API-Key", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"speed\": 1,\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_s16le\",\n    \"sample_rate\": 24000\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 16-bit PCM with output_format
import Foundation

let headers = [
  "X-API-Key": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "text": "Hello, this is a test message.",
  "voice_id": "voice_001",
  "language": "hi",
  "model": "standard",
  "speed": 1,
  "output_format": [
    "container": "raw",
    "encoding": "pcm_s16le",
    "sample_rate": 24000
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://hub.getraya.app/v1/text-to-speech/stream")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

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

### μ-law at 8 kHz with output_format

**Request**

```json
{
  "text": "Hello, this is a test message.",
  "voice_id": "voice_001",
  "language": "hi",
  "model": "standard",
  "output_format": {
    "container": "raw",
    "encoding": "pcm_mulaw",
    "sample_rate": 8000
  }
}
```

**SDK Code**

```python μ-law at 8 kHz with output_format
import requests

url = "https://hub.getraya.app/v1/text-to-speech/stream"

payload = {
    "text": "Hello, this is a test message.",
    "voice_id": "voice_001",
    "language": "hi",
    "model": "standard",
    "output_format": {
        "container": "raw",
        "encoding": "pcm_mulaw",
        "sample_rate": 8000
    }
}
headers = {
    "X-API-Key": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript μ-law at 8 kHz with output_format
const url = 'https://hub.getraya.app/v1/text-to-speech/stream';
const options = {
  method: 'POST',
  headers: {'X-API-Key': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"text":"Hello, this is a test message.","voice_id":"voice_001","language":"hi","model":"standard","output_format":{"container":"raw","encoding":"pcm_mulaw","sample_rate":8000}}'
};

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

```go μ-law at 8 kHz with output_format
package main

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

func main() {

	url := "https://hub.getraya.app/v1/text-to-speech/stream"

	payload := strings.NewReader("{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_mulaw\",\n    \"sample_rate\": 8000\n  }\n}")

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

	req.Header.Add("X-API-Key", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

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

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

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

}
```

```ruby μ-law at 8 kHz with output_format
require 'uri'
require 'net/http'

url = URI("https://hub.getraya.app/v1/text-to-speech/stream")

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

request = Net::HTTP::Post.new(url)
request["X-API-Key"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_mulaw\",\n    \"sample_rate\": 8000\n  }\n}"

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

```java μ-law at 8 kHz with output_format
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://hub.getraya.app/v1/text-to-speech/stream")
  .header("X-API-Key", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_mulaw\",\n    \"sample_rate\": 8000\n  }\n}")
  .asString();
```

```php μ-law at 8 kHz with output_format
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://hub.getraya.app/v1/text-to-speech/stream', [
  'body' => '{
  "text": "Hello, this is a test message.",
  "voice_id": "voice_001",
  "language": "hi",
  "model": "standard",
  "output_format": {
    "container": "raw",
    "encoding": "pcm_mulaw",
    "sample_rate": 8000
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-API-Key' => '<apiKey>',
  ],
]);

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

```csharp μ-law at 8 kHz with output_format
using RestSharp;

var client = new RestClient("https://hub.getraya.app/v1/text-to-speech/stream");
var request = new RestRequest(Method.POST);
request.AddHeader("X-API-Key", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_mulaw\",\n    \"sample_rate\": 8000\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift μ-law at 8 kHz with output_format
import Foundation

let headers = [
  "X-API-Key": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "text": "Hello, this is a test message.",
  "voice_id": "voice_001",
  "language": "hi",
  "model": "standard",
  "output_format": [
    "container": "raw",
    "encoding": "pcm_mulaw",
    "sample_rate": 8000
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://hub.getraya.app/v1/text-to-speech/stream")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

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

### A-law at 8 kHz with output_format

**Request**

```json
{
  "text": "Hello, this is a test message.",
  "voice_id": "voice_001",
  "language": "hi",
  "model": "standard",
  "output_format": {
    "container": "raw",
    "encoding": "pcm_alaw",
    "sample_rate": 8000
  }
}
```

**SDK Code**

```python A-law at 8 kHz with output_format
import requests

url = "https://hub.getraya.app/v1/text-to-speech/stream"

payload = {
    "text": "Hello, this is a test message.",
    "voice_id": "voice_001",
    "language": "hi",
    "model": "standard",
    "output_format": {
        "container": "raw",
        "encoding": "pcm_alaw",
        "sample_rate": 8000
    }
}
headers = {
    "X-API-Key": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript A-law at 8 kHz with output_format
const url = 'https://hub.getraya.app/v1/text-to-speech/stream';
const options = {
  method: 'POST',
  headers: {'X-API-Key': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"text":"Hello, this is a test message.","voice_id":"voice_001","language":"hi","model":"standard","output_format":{"container":"raw","encoding":"pcm_alaw","sample_rate":8000}}'
};

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

```go A-law at 8 kHz with output_format
package main

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

func main() {

	url := "https://hub.getraya.app/v1/text-to-speech/stream"

	payload := strings.NewReader("{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_alaw\",\n    \"sample_rate\": 8000\n  }\n}")

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

	req.Header.Add("X-API-Key", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

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

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

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

}
```

```ruby A-law at 8 kHz with output_format
require 'uri'
require 'net/http'

url = URI("https://hub.getraya.app/v1/text-to-speech/stream")

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

request = Net::HTTP::Post.new(url)
request["X-API-Key"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_alaw\",\n    \"sample_rate\": 8000\n  }\n}"

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

```java A-law at 8 kHz with output_format
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://hub.getraya.app/v1/text-to-speech/stream")
  .header("X-API-Key", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_alaw\",\n    \"sample_rate\": 8000\n  }\n}")
  .asString();
```

```php A-law at 8 kHz with output_format
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://hub.getraya.app/v1/text-to-speech/stream', [
  'body' => '{
  "text": "Hello, this is a test message.",
  "voice_id": "voice_001",
  "language": "hi",
  "model": "standard",
  "output_format": {
    "container": "raw",
    "encoding": "pcm_alaw",
    "sample_rate": 8000
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-API-Key' => '<apiKey>',
  ],
]);

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

```csharp A-law at 8 kHz with output_format
using RestSharp;

var client = new RestClient("https://hub.getraya.app/v1/text-to-speech/stream");
var request = new RestRequest(Method.POST);
request.AddHeader("X-API-Key", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"text\": \"Hello, this is a test message.\",\n  \"voice_id\": \"voice_001\",\n  \"language\": \"hi\",\n  \"model\": \"standard\",\n  \"output_format\": {\n    \"container\": \"raw\",\n    \"encoding\": \"pcm_alaw\",\n    \"sample_rate\": 8000\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift A-law at 8 kHz with output_format
import Foundation

let headers = [
  "X-API-Key": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "text": "Hello, this is a test message.",
  "voice_id": "voice_001",
  "language": "hi",
  "model": "standard",
  "output_format": [
    "container": "raw",
    "encoding": "pcm_alaw",
    "sample_rate": 8000
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://hub.getraya.app/v1/text-to-speech/stream")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

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