# Create PubSub token

POST https://%7BYour_Space_Name%7D.signalwire.com/api/pubsub/tokens
Content-Type: application/json

Generate a PubSub Token to be used to authenticate clients to the PubSub Service.

#### Permissions

The API token used to authenticate must have the following scope(s) enabled to make a successful request: _PubSub_.

[Learn more about API scopes](/docs/platform/your-signalwire-api-space).

Reference: https://signalwire.com/docs/apis/rest/pubsub/create-token

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: signalwire-rest
  version: 1.0.0
paths:
  /api/pubsub/tokens:
    post:
      operationId: create-token
      summary: Create PubSub token
      description: >-
        Generate a PubSub Token to be used to authenticate clients to the PubSub
        Service.


        #### Permissions


        The API token used to authenticate must have the following scope(s)
        enabled to make a successful request: _PubSub_.


        [Learn more about API scopes](/docs/platform/your-signalwire-api-space).
      tags:
        - subpackage_pubSubTokens
      parameters:
        - name: Authorization
          in: header
          description: >-
            SignalWire Basic Authentication using Project ID and API Token.


            The client sends HTTP requests with the Authorization header
            containing

            the word Basic followed by a space and a base64-encoded string of
            project_id:token.

            The project ID will be used as the username and the API token as the
            password.


            Example:

            ```

            Authorization: Basic base64(project_id:token)

            ```
          required: true
          schema:
            type: string
      responses:
        '200':
          description: The request has succeeded.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PubSub.PubSubToken'
        '400':
          description: The request is invalid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Types.StatusCodes.StatusCode400'
        '401':
          description: Access is unauthorized.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Types.StatusCodes.StatusCode401'
        '422':
          description: The request contains invalid parameters. See errors for details.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PubSub.PubSubToken422Error'
        '500':
          description: An internal server error occurred.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Types.StatusCodes.StatusCode500'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PubSub.NewPubSubToken'
servers:
  - url: https://%7BYour_Space_Name%7D.signalwire.com
components:
  schemas:
    PubSub.PubSubChannels:
      type: object
      properties: {}
      description: >-
        User-defined channel names. Each channel is an object with `read` and/or
        `write` properties.

        Max of 500 channels. Either `read`, `write`, or both are required inside
        each channel and default to `false`.

        Each channel name can be up to 250 characters. Must be valid JSON.
      title: PubSub.PubSubChannels
    PubSub.PubSubState:
      type: object
      properties: {}
      description: >-
        An arbitrary JSON object available to store stateful application
        information in. Must be valid JSON and have a maximum size of 2,000
        characters.
      title: PubSub.PubSubState
    PubSub.NewPubSubToken:
      type: object
      properties:
        ttl:
          type: integer
          description: >-
            The maximum time, in minutes, for which the access token will be
            valid. Between 1 and 43,200 (30 days).
        channels:
          $ref: '#/components/schemas/PubSub.PubSubChannels'
          description: >-
            Each channel with `write` and `read` objects with boolean as values.
            Max of 500 channels inside main `channels`.

            Either `read`, `write`, or both are required inside each channel and
            default to false.

            Each channel name can be up to 250 characters. Must be valid JSON.
        member_id:
          type: string
          description: >-
            The unique identifier of the member. Up to 250 characters. If not
            specified, a random UUID will be generated.
        state:
          $ref: '#/components/schemas/PubSub.PubSubState'
          description: >-
            An arbitrary JSON object available to store stateful application
            information in. Must be valid JSON and have a maximum size of 2,000
            characters.
      required:
        - ttl
        - channels
      title: PubSub.NewPubSubToken
    PubSub.PubSubToken:
      type: object
      properties:
        token:
          type: string
          description: >-
            A PubSub Token to be used to authenticate clients to the PubSub
            Service.
      required:
        - token
      title: PubSub.PubSubToken
    TypesStatusCodesStatusCode400Error:
      type: string
      enum:
        - Bad Request
      title: TypesStatusCodesStatusCode400Error
    Types.StatusCodes.StatusCode400:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/TypesStatusCodesStatusCode400Error'
      required:
        - error
      description: The request is invalid.
      title: Types.StatusCodes.StatusCode400
    TypesStatusCodesStatusCode401Error:
      type: string
      enum:
        - Unauthorized
      title: TypesStatusCodesStatusCode401Error
    Types.StatusCodes.StatusCode401:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/TypesStatusCodesStatusCode401Error'
      required:
        - error
      description: Access is unauthorized.
      title: Types.StatusCodes.StatusCode401
    Types.StatusCodes.RestApiErrorItem:
      type: object
      properties:
        type:
          type: string
          description: The category of error.
        code:
          type: string
          description: A specific error code.
        message:
          type: string
          description: A description of what caused the error.
        attribute:
          type:
            - string
            - 'null'
          description: The request parameter that caused the error, if applicable.
        url:
          type: string
          description: A link to documentation about this error.
      required:
        - type
        - code
        - message
        - url
      description: Details about a specific error.
      title: Types.StatusCodes.RestApiErrorItem
    PubSub.PubSubToken422Error:
      type: object
      properties:
        errors:
          type: array
          items:
            $ref: '#/components/schemas/Types.StatusCodes.RestApiErrorItem'
          description: List of validation errors.
      required:
        - errors
      description: The request contains invalid parameters. See errors for details.
      title: PubSub.PubSubToken422Error
    TypesStatusCodesStatusCode500Error:
      type: string
      enum:
        - Internal Server Error
      title: TypesStatusCodesStatusCode500Error
    Types.StatusCodes.StatusCode500:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/TypesStatusCodesStatusCode500Error'
      required:
        - error
      description: An internal server error occurred.
      title: Types.StatusCodes.StatusCode500
  securitySchemes:
    SignalWireBasicAuth:
      type: http
      scheme: basic
      description: >-
        SignalWire Basic Authentication using Project ID and API Token.


        The client sends HTTP requests with the Authorization header containing

        the word Basic followed by a space and a base64-encoded string of
        project_id:token.

        The project ID will be used as the username and the API token as the
        password.


        Example:

        ```

        Authorization: Basic base64(project_id:token)

        ```

```

## SDK Code Examples

```python
import requests
import base64

url = "https://{your_space_name}.signalwire.com/api/pubsub/tokens"

payload = {
    "ttl": 15,
    "channels": {
        "channela": {
            "read": True,
            "write": False
        },
        "channelb": { "read": True }
    }
}
credentials = base64.b64encode(f"<project_id>:<api_token>".encode()).decode()

headers = {
    "Authorization": f"Basic {credentials}",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://{your_space_name}.signalwire.com/api/pubsub/tokens';
const credentials = btoa("<project_id>:<api_token>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"ttl":15,"channels":{"channela":{"read":true,"write":false},"channelb":{"read":true}}}'
};

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"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://{your_space_name}.signalwire.com/api/pubsub/tokens"

	payload := strings.NewReader("{\n  \"ttl\": 15,\n  \"channels\": {\n    \"channela\": {\n      \"read\": true,\n      \"write\": false\n    },\n    \"channelb\": {\n      \"read\": true\n    }\n  }\n}")

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

	req.SetBasicAuth("<project_id>", "<api_token>")
	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
require 'uri'
require 'base64'
require 'net/http'

url = URI("https://{your_space_name}.signalwire.com/api/pubsub/tokens")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = "Basic #{Base64.strict_encode64("<project_id>:<api_token>")}"
request["Content-Type"] = 'application/json'
request.body = "{\n  \"ttl\": 15,\n  \"channels\": {\n    \"channela\": {\n      \"read\": true,\n      \"write\": false\n    },\n    \"channelb\": {\n      \"read\": true\n    }\n  }\n}"

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

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

HttpResponse<String> response = Unirest.post("https://{your_space_name}.signalwire.com/api/pubsub/tokens")
  .header("Authorization", "Basic " + Base64.getEncoder().encodeToString("<project_id>:<api_token>".getBytes()))
  .header("Content-Type", "application/json")
  .body("{\n  \"ttl\": 15,\n  \"channels\": {\n    \"channela\": {\n      \"read\": true,\n      \"write\": false\n    },\n    \"channelb\": {\n      \"read\": true\n    }\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://{your_space_name}.signalwire.com/api/pubsub/tokens', [
  'body' => '{
  "ttl": 15,
  "channels": {
    "channela": {
      "read": true,
      "write": false
    },
    "channelb": {
      "read": true
    }
  }
}',
  'headers' => [
    'Authorization' => 'Basic ' . base64_encode('<project_id>:<api_token>'),
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;
using System;
using System.Text;

var client = new RestClient("https://{your_space_name}.signalwire.com/api/pubsub/tokens");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("<project_id>:<api_token>")));
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"ttl\": 15,\n  \"channels\": {\n    \"channela\": {\n      \"read\": true,\n      \"write\": false\n    },\n    \"channelb\": {\n      \"read\": true\n    }\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let credentials = Data("<project_id>:<api_token>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]
let parameters = [
  "ttl": 15,
  "channels": [
    "channela": [
      "read": true,
      "write": false
    ],
    "channelb": ["read": true]
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://{your_space_name}.signalwire.com/api/pubsub/tokens")! 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()
```