Scroll to Top
💻
Free Code
Users get ready-to-use code at no cost.
📋
Easy Copy
Copy and use the code instantly.
Quick Learning
Understand concepts fast and clearly.
📝
Step-by-Step
Follow simple instructions to implement.
📅 August 16, 2024 💻 Tutorial ⭐ Beginner Friendly

Bulk URL Shortener In Google sheet using Bitly API & Apps Script

Author Avatar

Ashish Dwivedi

Editorial Team • Tech Writer

About This Tutorial

Create a bulk URL shortener in Google Sheets using the Bitly API and Google Apps Script. Add long URLs in a column, then use a script to send each to Bitly’s API, retrieve the shortened version, and display it in another column—perfect for managing multiple links efficiently.
  1. Step 1: Click on the Copy button to copy the code snippet.
  2. Step 2: Paste the copied code into your project’s script editor.

Apps Scripts Blog

Read Blog

 

📂 javascript
⚡ script1.js
⚡ script1.js
function shortenUrls() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // ✅ Change sheet name if needed
  var dataRange = sheet.getDataRange();
  var data = dataRange.getValues();
  var urlColumn = 1; // ✅ Column A (1) contains the original URLs
  var shortUrlColumn = 2; // ✅ Column B (2) will store shortened URLs

  // ⚠️ Replace this with your actual Bitly API key (Bearer token)
  var bitlyApiKey = "Bearer YOUR_BITLY_API_KEY";

  for (var i = 0; i < data.length; i++) {
    var url = data[i][urlColumn - 1];

    // ✅ Skip header row & empty cells
    if (i === 0 || !url || typeof url !== 'string' || !url.startsWith("http")) {
      continue;
    }

    try {
      var apiUrl = "https://api-ssl.bitly.com/v4/shorten";
      var headers = {
        "Authorization": bitlyApiKey,
        "Content-Type": "application/json"
      };

      var payload = {
        "long_url": url
      };

      var options = {
        "method": "post",
        "headers": headers,
        "muteHttpExceptions": true,
        "payload": JSON.stringify(payload)
      };

      var response = UrlFetchApp.fetch(apiUrl, options);
      var json = JSON.parse(response.getContentText());

      if (json.link) {
        // ✅ Write shortened URL in Column B
        sheet.getRange(i + 1, shortUrlColumn).setValue(json.link);
      } else {
        // ❌ If API returned an error, show it in the cell
        sheet.getRange(i + 1, shortUrlColumn).setValue("Error: " + (json.message || "Unknown"));
      }

    } catch (error) {
      sheet.getRange(i + 1, shortUrlColumn).setValue("Error: " + error.toString());
    }
  }
}