# 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](#authentication)
2. [Authentication](#authentication)
   1. [Application Passwords](#bearer-token)
   2. [Bearer Access Token](#bearer-token)
3. [List Videos](#list-videos)
4. [Get Video](#get-video)
5. [Update Video](#id-6.-delete-video)
6. [Delete Video](#id-6.-delete-video)
7. [Upload Video](#upload-video)

***

#### 1. API Endpoints <a href="#endpoints" id="endpoints"></a>

* Blog Posts: <http://domain.com/wp-json/wp/v2/posts>
* Videos: <https://domain.com/wp-json/wp/v2/video>
* Upload: <https://domain.com/wp-json/streamtube/v1/upload>

***

#### 2. Authentication <a href="#authentication" id="authentication"></a>

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

***

#### 2.a) Application Passwords:  <a href="#app-password" id="app-password"></a>

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.

![](https://ticksy_attachments.s3.amazonaws.com/5738482390.png)

**Manage App Passwords via REST API**

* Retrieve a Application Password <https://developer.wordpress.org/rest-api/reference/application-passwords/#retrieve-a-application-password-2>
* Create a Application Password <https://developer.wordpress.org/rest-api/reference/application-passwords/#create-a-application-password>
* Delete a Application Password <https://developer.wordpress.org/rest-api/reference/application-passwords/#delete-a-application-password>

***

#### 2.b) Bearer Access Token <a href="#bearer-token" id="bearer-token"></a>

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.

<figure><img src="https://ticksy_attachments.s3.amazonaws.com/6708509835.png" alt=""><figcaption><p>Generate an Access Token from Dashboard</p></figcaption></figure>

```
// 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 <a href="#list-videos" id="list-videos"></a>

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

General Arguments: <https://developer.wordpress.org/rest-api/reference/posts/#arguments>&#x20;

***

#### 4. Get Video <a href="#get-video" id="get-video"></a>

**GET** [https://domain.com/wp-json/wp/v2/video/{videoId}](https://domain.com/wp-json/wp/v2/video)

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

***

#### 5. Update Video <a href="#update-video" id="update-video"></a>

**POST** [https://domain.com/wp-json/wp/v2/video/{videoId}](https://domain.com/wp-json/wp/v2/video)

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}](https://domain.com/wp-json/wp/v2/video)

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

***

#### 7. Upload Video <a href="#upload-video" id="upload-video"></a>

**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**

```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**

```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
<?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**

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