POOR API DOCUMENTATION BUNNY CDN

Assclown

Regular Member
Joined
Apr 20, 2018
Messages
452
Reaction score
342
Any one consuming Bunny Stream API?

Do we have an organised API documentation? The one on the site is VERY confusing .
 
I have used them quite a bit. Do you have a specific query?
I have a bunch of video urls from another file storage that I need to upload to Bunny Stream.

Remote Uploading using the 'Fetch Video' section. I wanted to upload the videos to a particular collection (for organization) as opposed to dumping them in my library.
 
Try creating a Storage zone may be? If you are logged into bunny already, try going to:

Code:
https://dash.bunny.net/storage

Create one from here, and for upload try something like this (This is my own script for a website I have.. its kinda crappy but it works fine...)

Code:
const fs = require("fs").promises;
const path = require("path");
const ftp = require("ftp");
const scriptPath = process.argv[1];
const projectRoot = scriptPath.split("/").slice(0, -2).join("/");
require("dotenv").config({
  path: `${projectRoot}/.env.local`,
});
(async () => {
  const client = new ftp();
  await new Promise((resolve, reject) => {
    client.on("ready", resolve);
    client.on("error", reject);
    client.connect({
      host: process.env.BUNNY_CDN_HOST,
      user: process.env.BUNNY_CDN_USERNAME,
      password: process.env.BUNNY_CDN_API_KEY,
    });
  });
  try {
    await removeDirectory(client, "/bb-cdn/");
  } catch {
    console.log("No directory to remove");
  }
  try {
    await createDirectory(client, "/bb-cdn/_next");
    const localNextStaticPath = `${projectRoot}/.next/static/`;
    const localPublicPath = `${projectRoot}/public/`;
    const remoteNextStaticPath = "/bb-cdn/_next/static/";
    const remotePublicPath = "/bb-cdn";
    await uploadFilesToFTP(localNextStaticPath, remoteNextStaticPath, client);
    await uploadFilesToFTP(localPublicPath, remotePublicPath, client);
  } catch (error) {
    console.error("Error:", error);
  } finally {
    client.end();
  }
})();
async function removeDirectory(client, directory) {
  return new Promise((resolve, reject) => {
    client.list(directory, (err, files) => {
      if (err) {
        reject(err);
        return;
      }
      let deletePromises = [];
      files.forEach((file) => {
        const filePath = `${directory}/${file.name}`;
        if (file.type === "d") {
          deletePromises.push(
            new Promise((resolve, reject) => {
              client.rmdir(filePath, (err) => {
                if (err) {
                  reject(err);
                } else {
                  console.log(`Deleted folder: ${filePath}`);
                  resolve();
                }
              });
            })
          );
        } else {
          deletePromises.push(
            new Promise((resolve, reject) => {
              client.delete(filePath, (err) => {
                if (err) {
                  reject(err);
                } else {
                  console.log(`Deleted file: ${filePath}`);
                  resolve();
                }
              });
            })
          );
        }
      });
      Promise.all(deletePromises)
        .then(() => {
          console.log(`All files deleted from directory: ${directory}`);
          resolve();
        })
        .catch((err) => {
          reject(err);
        });
    });
  });
}
async function createDirectory(client, directory) {
  return new Promise((resolve, reject) => {
    client.mkdir(directory, false, (err) => {
      if (err) {
        reject(new Error(err));
      } else {
        console.log("Created _next dir");
        resolve();
      }
    });
  });
}
async function uploadFilesToFTP(localFolder, remoteFolder, client) {
  await readFilesRecursively(localFolder, remoteFolder, "");
  async function readFilesRecursively(localFolder, remoteFolder, subFolder) {
    const folderPath = path.join(localFolder, subFolder);
    const files = await fs.readdir(folderPath, { withFileTypes: true });
    for (const file of files) {
      const filePath = path.join(folderPath, file.name);
      if (file.isDirectory()) {
        const newSubFolder = path.join(subFolder, file.name);
        await readFilesRecursively(localFolder, remoteFolder, newSubFolder);
      } else {
        const remoteFilePath = path.join(remoteFolder, subFolder, file.name);
        await uploadFile(filePath, remoteFilePath, client);
      }
    }
  }
  async function uploadFile(localFilePath, remoteFilePath, client) {
    console.log(`Uploading ${localFilePath} to ${remoteFilePath}`);
    return new Promise((resolve, reject) => {
      client.put(localFilePath, remoteFilePath, (err) => {
        if (err) {
          console.error("Error uploading file:", err);
          reject(err);
        } else {
          console.log(
            `Successfully uploaded ${localFilePath} to ${remoteFilePath}`
          );
          resolve();
        }
      });
    });
  }
}

For the BUNNY_CDN_HOST, BUNNY_CDN_USERNAME and
BUNNY_CDN_API_KEY look in the FTP & API secion.
Code:
https://dash.bunny.net/storage/[projectid]/access
 
Oh! That's easy!

Alright, I am assuming you know how to make a normal upload using the fetch endpoint. Nonetheless, I will post it in some detail for the benefit of someone else reading this who may be unaware

To post to a specific collection, you basically need to post a specific fetch URL and pass the collectionID as a URL parameter.

You need
-

1. Video Library ID - Click on "Stream" > Then in the second Sidebar click on "API Keys" > You will find it at the top of the page
2. Your Collection ID - Click the 3 dots next to the collection name card and click "Copy Collection ID"
3. Your API Key - You can find it on the above API Keys Page

P.S - Stream API has a different API key and your sitewide bunny key won't work.

Now make a POST request to the below URL

Code:
https://video.bunnycdn.com/library/{libraryId}/videos/fetch?collectionId={collectionID}

Set your API key as AccessKey in the header

Your payload should look something like

JSON:
{
    "url": "https://www.w3schools.com/html/mov_bbb.mp4",
    "title": "Test Video"
}

That's it. Your video will be fetched and upload to your desired collection.
 
Try creating a Storage zone may be? If you are logged into bunny already, try going to:

Code:
https://dash.bunny.net/storage

Create one from here, and for upload try something like this (This is my own script for a website I have.. its kinda crappy but it works fine...)

Code:
const fs = require("fs").promises;
const path = require("path");
const ftp = require("ftp");
const scriptPath = process.argv[1];
const projectRoot = scriptPath.split("/").slice(0, -2).join("/");
require("dotenv").config({
  path: `${projectRoot}/.env.local`,
});
(async () => {
  const client = new ftp();
  await new Promise((resolve, reject) => {
    client.on("ready", resolve);
    client.on("error", reject);
    client.connect({
      host: process.env.BUNNY_CDN_HOST,
      user: process.env.BUNNY_CDN_USERNAME,
      password: process.env.BUNNY_CDN_API_KEY,
    });
  });
  try {
    await removeDirectory(client, "/bb-cdn/");
  } catch {
    console.log("No directory to remove");
  }
  try {
    await createDirectory(client, "/bb-cdn/_next");
    const localNextStaticPath = `${projectRoot}/.next/static/`;
    const localPublicPath = `${projectRoot}/public/`;
    const remoteNextStaticPath = "/bb-cdn/_next/static/";
    const remotePublicPath = "/bb-cdn";
    await uploadFilesToFTP(localNextStaticPath, remoteNextStaticPath, client);
    await uploadFilesToFTP(localPublicPath, remotePublicPath, client);
  } catch (error) {
    console.error("Error:", error);
  } finally {
    client.end();
  }
})();
async function removeDirectory(client, directory) {
  return new Promise((resolve, reject) => {
    client.list(directory, (err, files) => {
      if (err) {
        reject(err);
        return;
      }
      let deletePromises = [];
      files.forEach((file) => {
        const filePath = `${directory}/${file.name}`;
        if (file.type === "d") {
          deletePromises.push(
            new Promise((resolve, reject) => {
              client.rmdir(filePath, (err) => {
                if (err) {
                  reject(err);
                } else {
                  console.log(`Deleted folder: ${filePath}`);
                  resolve();
                }
              });
            })
          );
        } else {
          deletePromises.push(
            new Promise((resolve, reject) => {
              client.delete(filePath, (err) => {
                if (err) {
                  reject(err);
                } else {
                  console.log(`Deleted file: ${filePath}`);
                  resolve();
                }
              });
            })
          );
        }
      });
      Promise.all(deletePromises)
        .then(() => {
          console.log(`All files deleted from directory: ${directory}`);
          resolve();
        })
        .catch((err) => {
          reject(err);
        });
    });
  });
}
async function createDirectory(client, directory) {
  return new Promise((resolve, reject) => {
    client.mkdir(directory, false, (err) => {
      if (err) {
        reject(new Error(err));
      } else {
        console.log("Created _next dir");
        resolve();
      }
    });
  });
}
async function uploadFilesToFTP(localFolder, remoteFolder, client) {
  await readFilesRecursively(localFolder, remoteFolder, "");
  async function readFilesRecursively(localFolder, remoteFolder, subFolder) {
    const folderPath = path.join(localFolder, subFolder);
    const files = await fs.readdir(folderPath, { withFileTypes: true });
    for (const file of files) {
      const filePath = path.join(folderPath, file.name);
      if (file.isDirectory()) {
        const newSubFolder = path.join(subFolder, file.name);
        await readFilesRecursively(localFolder, remoteFolder, newSubFolder);
      } else {
        const remoteFilePath = path.join(remoteFolder, subFolder, file.name);
        await uploadFile(filePath, remoteFilePath, client);
      }
    }
  }
  async function uploadFile(localFilePath, remoteFilePath, client) {
    console.log(`Uploading ${localFilePath} to ${remoteFilePath}`);
    return new Promise((resolve, reject) => {
      client.put(localFilePath, remoteFilePath, (err) => {
        if (err) {
          console.error("Error uploading file:", err);
          reject(err);
        } else {
          console.log(
            `Successfully uploaded ${localFilePath} to ${remoteFilePath}`
          );
          resolve();
        }
      });
    });
  }
}

For the BUNNY_CDN_HOST, BUNNY_CDN_USERNAME and
BUNNY_CDN_API_KEY look in the FTP & API secion.
Code:
https://dash.bunny.net/storage/[projectid]/access

Oh! That's easy!

Alright, I am assuming you know how to make a normal upload using the fetch endpoint. Nonetheless, I will post it in some detail for the benefit of someone else reading this who may be unaware

To post to a specific collection, you basically need to post a specific fetch URL and pass the collectionID as a URL parameter.

You need
-

1. Video Library ID - Click on "Stream" > Then in the second Sidebar click on "API Keys" > You will find it at the top of the page
2. Your Collection ID - Click the 3 dots next to the collection name card and click "Copy Collection ID"
3. Your API Key - You can find it on the above API Keys Page

P.S - Stream API has a different API key and your sitewide bunny key won't work.

Now make a POST request to the below URL

Code:
https://video.bunnycdn.com/library/{libraryId}/videos/fetch?collectionId={collectionID}

Set your API key as AccessKey in the header

Your payload should look something like

JSON:
{
    "url": "https://www.w3schools.com/html/mov_bbb.mp4",
    "title": "Test Video"
}

That's it. Your video will be fetched and upload to your desired collection.
Thanks very much everyone.

Let me get to work now. Thanks again.
 
Oh! That's easy!

Alright, I am assuming you know how to make a normal upload using the fetch endpoint. Nonetheless, I will post it in some detail for the benefit of someone else reading this who may be unaware

To post to a specific collection, you basically need to post a specific fetch URL and pass the collectionID as a URL parameter.

You need
-

1. Video Library ID - Click on "Stream" > Then in the second Sidebar click on "API Keys" > You will find it at the top of the page
2. Your Collection ID - Click the 3 dots next to the collection name card and click "Copy Collection ID"
3. Your API Key - You can find it on the above API Keys Page

P.S - Stream API has a different API key and your sitewide bunny key won't work.

Now make a POST request to the below URL

Code:
https://video.bunnycdn.com/library/{libraryId}/videos/fetch?collectionId={collectionID}

Set your API key as AccessKey in the header

Your payload should look something like

JSON:
{
    "url": "https://www.w3schools.com/html/mov_bbb.mp4",
    "title": "Test Video"
}

That's it. Your video will be fetched and upload to your desired collection.
This worked really well.

But is there a way, i could add something like "description" or 'tags' to it.
 
This worked really well.

Happy to help. :)

But is there a way, i could add something like "description" or 'tags' to it.

That should be easy too. The Fetch endpoint mentioned in my earlier response only fetches the video and let's you assign the title. It doesn't support metaTags (description is a part of Meta Data in Bunny API).

So you'll have to break your request in two parts to be able to add the description.

When you post to the above fetch endpoint, you get a response like

JSON:
{
    "id": "727c94b1-08s4-481f-86a2-46b26978b34c" <~~ Your VideoID,
    "success": true,
    "message": "OK",
    "statusCode": 200
}

Just send an Update Video request - your URL should look something like below - again make a POST request

Code:
https://video.bunnycdn.com/library/{libraryId}/videos/{videoId}

LibraryID - Your Main Library ID

VideoID - What you received from the above request

Your body should look something like this

JSON:
{
    "title": "Video New Title",
    "metaTags": [
        {
            "property": "description",
            "value": "This is a test description"
        }
    ]
}

P.S - When you send the title in your update request, the title will be overwritten with the new title. So you can skip it altogether.

P.P.S - I couldn't find "tags" as a property either in the UI or the API, so not sure. Maybe they exist, but I am not aware of them.

//

Now Bunny can take a second to process requests and videos. So sending consecutive Update request may fail (this is an assumption).

If I were you, I'd have a CSV ready with the title, description and source URL. I'd add another column with "VideoID" and just keep updating the CSV with every upload. Once done, I'd update all the videos with descriptions at one go.
 
Happy to help. :)



That should be easy too. The Fetch endpoint mentioned in my earlier response only fetches the video and let's you assign the title. It doesn't support metaTags (description is a part of Meta Data in Bunny API).

So you'll have to break your request in two parts to be able to add the description.

When you post to the above fetch endpoint, you get a response like

JSON:
{
    "id": "727c94b1-08s4-481f-86a2-46b26978b34c" <~~ Your VideoID,
    "success": true,
    "message": "OK",
    "statusCode": 200
}

Just send an Update Video request - your URL should look something like below - again make a POST request

Code:
https://video.bunnycdn.com/library/{libraryId}/videos/{videoId}

LibraryID - Your Main Library ID

VideoID - What you received from the above request

Your body should look something like this

JSON:
{
    "title": "Video New Title",
    "metaTags": [
        {
            "property": "description",
            "value": "This is a test description"
        }
    ]
}

P.S - When you send the title in your update request, the title will be overwritten with the new title. So you can skip it altogether.

P.P.S - I couldn't find "tags" as a property either in the UI or the API, so not sure. Maybe they exist, but I am not aware of them.

//

Now Bunny can take a second to process requests and videos. So sending consecutive Update request may fail (this is an assumption).

If I were you, I'd have a CSV ready with the title, description and source URL. I'd add another column with "VideoID" and just keep updating the CSV with every upload. Once done, I'd update all the videos with descriptions at one go.
Thank you very much for taking the time to explain nicely.
 
Back
Top