REST APIs & Upload

StreamTube adheres to the WordPress REST API standards, facilitating seamless integration and extension with third-party applications. Developers can leverage the REST API to build custom applications.

For comprehensive instructions, please refer to the official WordPress REST API Handbook: https://developer.wordpress.org/rest-api/



1. API Endpoints


2. Authentication

https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/


2.a) Application Passwords:

To learn more about Basic Authentication, visits https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#basic-authentication-with-application-passwords

Create An App Password

  • Go to your frontend Dashboard.

  • Navigate to the Account section.

  • Select App Password.

  • In the "App name" field, enter a descriptive name for the application you'll be using this password with.

  • Click the "Add New Application Password" button.

  • Save the generated password in a secure location. It will not be displayed again.

Manage App Passwords via REST API


2.b) Bearer Access Token

You can also authenticate using a Bearer Token.

Install and activate the "JWT Authentication for WP REST API" plugin: https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/ Refer to the plugin page for more details.

Generate an Access Token:

  • Access your frontend Dashboard.

  • Go to Account and select Access Token.

  • Enter your password and click "Create a token" button.

  • Remember to save the generated token in a safe place, as it will not be shown again.

Generate an Access Token from Dashboard
// Generate an access token using command line
$ curl -X POST "https://domain.com.com/wp-json/jwt-auth/v1/token" \
     -H "Content-Type: application/json" \
     -d '{"username": "my_user", "password": "my_wp_password"}'

3. List Videos

GET https://domain.com/wp-json/wp/v2/video

General Arguments: https://developer.wordpress.org/rest-api/reference/posts/#arguments


4. Get Video

GET https://domain.com/wp-json/wp/v2/video/{videoId}

General Arguments: https://developer.wordpress.org/rest-api/reference/posts/#arguments-3


5. Update Video

POST https://domain.com/wp-json/wp/v2/video/{videoId}

General Arguments https://developer.wordpress.org/rest-api/reference/posts/#arguments-4


6. Delete Video

DELETE https://domain.com/wp-json/wp/v2/video/{videoId}

General Arguments https://developer.wordpress.org/rest-api/reference/posts/#delete-a-post


7. Upload Video

POST https://domain.com/wp-json/streamtube/v1/upload

Bash

// Upload with App Password Authentication (Basic Auth)
$ curl 'https://domain.com/wp-json/streamtube/v1/upload' \
     --user 'my_user:my_app_password' \
     --form "file=@path/file.mp4;type=video/mp4"
// Upload with Bearer Token Authentication
$ curl 'https://domain.com/wp-json/streamtube/v1/upload' \
      --header 'Authorization: Bearer YOUR_JWT_TOKEN' \
      --form "file=@path/file.mp4;type=video/mp4"

Python

import requests
url = 'https://domain.com/wp-json/streamtube/v1/upload'
headers = {'Authorization': 'Bearer YOUR_JWT_TOKEN'}
files = {'file': ('file.mp4', open('path/file.mp4', 'rb'), 'video/mp4')}
try:
    response = requests.post(url, headers=headers, files=files)
    response.raise_for_status()  # Raise an exception for bad status codes
    print(response.text)  # Or response.json() if the response is JSON
except requests.exceptions.RequestException as e:
    print(f"Error: {e}")

Javascript

const url = 'https://domain.com/wp-json/streamtube/v1/upload';
const token = 'YOUR_JWT_TOKEN';
const filePath = 'path/file.mp4'; // Adapt to your environment
async function uploadFile() {
  try {
    const formData = new FormData();
    const response = await fetch(filePath);
    const blob = await response.blob();
    formData.append('file', blob, 'file.mp4');
    const uploadResponse = await fetch(url, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: formData,
    });
    if (!uploadResponse.ok) {
      throw new Error(`HTTP error! status: ${uploadResponse.status}`);
    }
    const data = await uploadResponse.text(); // or uploadResponse.json()
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}
uploadFile();

PHP

<?php
$url = 'https://domain.com/wp-json/streamtube/v1/upload';
$token = 'YOUR_JWT_TOKEN';
$filePath = 'path/file.mp4';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Bearer ' . $token,
));
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'file' => curl_file_create($filePath, 'video/mp4', 'file.mp4'),
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
} else {
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code >= 200 && $http_code < 300) {
        echo $response; // or json_decode($response, true);
    } else {
        echo "HTTP error: " . $http_code . "\n";
    }
}
curl_close($ch);
?>

Go

package main
import (
        "bytes"
        "fmt"
        "io"
        "mime/multipart"
        "net/http"
        "os"
)
func main() {
        url := "https://domain.com/wp-json/streamtube/v1/upload"
        token := "YOUR_JWT_TOKEN"
        filePath := "path/file.mp4"
        file, err := os.Open(filePath)
        if err != nil {
                fmt.Println("Error opening file:", err)
                return
        }
        defer file.Close()
        body := &bytes.Buffer{}
        writer := multipart.NewWriter(body)
        part, err := writer.CreateFormFile("file", "file.mp4")
        if err != nil {
                fmt.Println("Error creating form file:", err)
                return
        }
        _, err = io.Copy(part, file)
        err = writer.Close()
        if err != nil {
                fmt.Println("Error closing writer:", err)
                return
        }
        req, err := http.NewRequest("POST", url, body)
        if err != nil {
                fmt.Println("Error creating request:", err)
                return
        }
        req.Header.Set("Authorization", "Bearer "+token)
        req.Header.Set("Content-Type", writer.FormDataContentType())
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
                fmt.Println("Error sending request:", err)
                return
        }
        defer resp.Body.Close()
        bodyResp, err := io.ReadAll(resp.Body)
        if err != nil {
                fmt.Println("Error reading response:", err)
                return
        }
        fmt.Println(string(bodyResp))
}

Last updated