# Create room token

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

Generate a Room Token allowing a client to join a Room.

#### Permissions

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

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

Reference: https://signalwire.com/docs/apis/rest/video/room-tokens/create-room-token

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: signalwire-rest
  version: 1.0.0
paths:
  /api/video/room_tokens:
    post:
      operationId: create-room-token
      summary: Create room token
      description: >-
        Generate a Room Token allowing a client to join a Room.


        #### Permissions


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


        [Learn more about API scopes](/docs/platform/your-signalwire-api-space).
      tags:
        - subpackage_roomTokens
      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/Video.RoomTokenResponse'
        '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/Video.VideoStatusCode422'
        '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/Video.CreateRoomTokenRequest'
servers:
  - url: https://%7BYour_Space_Name%7D.signalwire.com
components:
  schemas:
    Video.RoomTokenPermission:
      type: string
      enum:
        - room.member.audio_mute
        - room.member.audio_unmute
        - room.member.video_mute
        - room.member.video_unmute
        - room.member.deaf
        - room.member.undeaf
        - room.member.set_input_volume
        - room.member.set_output_volume
        - room.member.set_input_sensitivity
        - room.member.set_position
        - room.member.set_meta
        - room.member.raisehand
        - room.member.lowerhand
        - room.member.remove
        - room.member.promote
        - room.member.demote
        - room.hide_video_muted
        - room.list_available_layouts
        - room.lock
        - room.playback
        - room.playback_seek
        - room.prioritize_handraise
        - room.recording
        - room.set_layout
        - room.set_position
        - room.set_meta
        - room.show_video_muted
        - room.stream
        - room.unlock
        - room.self.audio_mute
        - room.self.audio_unmute
        - room.self.video_mute
        - room.self.video_unmute
        - room.self.deaf
        - room.self.undeaf
        - room.self.set_input_volume
        - room.self.set_output_volume
        - room.self.set_input_sensitivity
        - room.self.set_position
        - room.self.set_meta
        - room.self.raisehand
        - room.self.lowerhand
        - room.self.screenshare
        - room.self.additional_source
      description: Valid permission scopes for room tokens.
      title: Video.RoomTokenPermission
    Video.JoinAsType:
      type: string
      enum:
        - audience
        - member
      description: Join as type for room tokens.
      title: Video.JoinAsType
    Video.MediaAllowedType:
      type: string
      enum:
        - all
        - video-only
        - audio-only
      description: Media allowed type for room tokens.
      title: Video.MediaAllowedType
    VideoCreateRoomTokenRequestRoomMeta:
      type: object
      properties: {}
      description: Set the room meta. Maximum of 2000 characters when serialized to JSON.
      title: VideoCreateRoomTokenRequestRoomMeta
    VideoCreateRoomTokenRequestMeta:
      type: object
      properties: {}
      description: Set the member meta. Maximum of 2000 characters when serialized to JSON.
      title: VideoCreateRoomTokenRequestMeta
    Video.CreateRoomTokenRequest:
      type: object
      properties:
        room_name:
          type: string
          description: >-
            Room's unique named identifier. Allowed characters: A-Za-z0-9_-. Up
            to 100 characters. The room does not have to exist when the token is
            created, but must exist prior to joining, or ensure auto_create_room
            is set to true.
        user_name:
          type: string
          description: >-
            A display name to use for the user. Up to 100 characters. (If not
            supplied, a random alphanumeric string will be returned for each
            authorization with this token.)
        permissions:
          type: array
          items:
            $ref: '#/components/schemas/Video.RoomTokenPermission'
          description: >-
            A list of permissions, which define what user can do once they join
            the room. If `join_as` is `audience`, permissions are set to an
            empty array regardless of the value provided.
        join_from:
          type: string
          format: date-time
          description: >-
            The user can't join the room before this time. Expects RFC 3339
            datetime: `2022-01-01T23:59:60Z`. Date only: `2022-01-01` will be
            converted to `2022-01-01T00:00:00Z`
        join_until:
          type: string
          format: date-time
          description: >-
            The user can't join the room after this time. Expects RFC 3339
            datetime: `2022-01-01T23:59:60Z`. Date only: `2022-01-01` will be
            converted to `2022-01-01T00:00:00Z`
        remove_at:
          type: string
          format: date-time
          description: >-
            Remove user from the room at this time. Expects RFC 3339 datetime:
            `2022-01-01T23:59:60Z`. Date only: `2022-01-01` will be converted to
            `2022-01-01T00:00:00Z`
        remove_after_seconds_elapsed:
          type: integer
          description: Remove user after they are in the room for N seconds.
        join_audio_muted:
          type: boolean
          default: false
          description: Whether the user joins the room with their audio muted.
        join_video_muted:
          type: boolean
          default: false
          description: Whether the user joins the room with their video muted.
        auto_create_room:
          type: boolean
          default: true
          description: >-
            By default, if the user tries to use this token to join a room that
            doesn't exist, it will be created with default configuration. Set
            this to false to require the room to exist beforehand.
        enable_room_previews:
          type: boolean
          default: false
          description: >-
            Whether to generate a video with a preview of the content of the
            room. This parameter has effect only if this token auto-creates the
            room, thus it will be ignored if the room already exists.
        room_display_name:
          type: string
          description: >-
            Display name used if a room is auto-created when the token joins.
            Maximum of 200 characters. Defaults to the value of room_name.
        end_room_session_on_leave:
          type: boolean
          default: false
          description: >-
            Whether to end the room session when the member using this token
            leaves the room.
        join_as:
          $ref: '#/components/schemas/Video.JoinAsType'
          description: >-
            Whether the user should join as a member or as a non-interactive
            audience participant. Audience participants cannot send audio or
            video.
        media_allowed:
          $ref: '#/components/schemas/Video.MediaAllowedType'
          description: Indicates what media the user is allowed to receive.
        room_meta:
          $ref: '#/components/schemas/VideoCreateRoomTokenRequestRoomMeta'
          description: >-
            Set the room meta. Maximum of 2000 characters when serialized to
            JSON.
        meta:
          $ref: '#/components/schemas/VideoCreateRoomTokenRequestMeta'
          description: >-
            Set the member meta. Maximum of 2000 characters when serialized to
            JSON.
        sync_audio_video:
          type: boolean
          default: false
          description: Enable/disable jitter buffer audio-video sync.
      required:
        - room_name
      description: Request body for creating a room token.
      title: Video.CreateRoomTokenRequest
    Video.RoomTokenResponse:
      type: object
      properties:
        token:
          type: string
          description: A Room Token to be used by clients to connect to the Room.
      required:
        - token
      description: Room token response object.
      title: Video.RoomTokenResponse
    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
    Video.VideoStatusCode422:
      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: Video.VideoStatusCode422
    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/video/room_tokens"

payload = { "room_name": "my_room" }
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/video/room_tokens';
const credentials = btoa("<project_id>:<api_token>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"room_name":"my_room"}'
};

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/video/room_tokens"

	payload := strings.NewReader("{\n  \"room_name\": \"my_room\"\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/video/room_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  \"room_name\": \"my_room\"\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/video/room_tokens")
  .header("Authorization", "Basic " + Base64.getEncoder().encodeToString("<project_id>:<api_token>".getBytes()))
  .header("Content-Type", "application/json")
  .body("{\n  \"room_name\": \"my_room\"\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://{your_space_name}.signalwire.com/api/video/room_tokens', [
  'body' => '{
  "room_name": "my_room"
}',
  '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/video/room_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  \"room_name\": \"my_room\"\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 = ["room_name": "my_room"] as [String : Any]

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

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