How to Integrate SERPHouse SERP API with Google Sheets using Apps Script

17 min read

Calender 01
Step-by-step tutorial on integrating SERP API with Google Sheets using Apps Script for data retrieval and analysis.

If you work in SEO or digital marketing, checking rankings every day can get old fast. Copying results into a spreadsheet isn’t just boring — it eats up time you could spend on real strategy. A simpler way is to connect the SERPHouse SERP API with Google Sheets. Once it’s set up, your rankings update automatically in the sheet. The data’s fresh, accurate, and always there when you need it — without the copy-paste routine.

Why connect SERPHouse with Google Sheets?

Search results aren’t fixed—they change constantly. Competitors pop up, rankings shift, and user behavior pushes results around faster than you can track. That’s why many marketers now use a SERP API with Google Sheets to automate tracking, making it easier to stay updated without the hassle of manual checks.

Connecting SERPHouse to Google Sheets cuts through the hassle. It creates a live link between the search engine and your reports. Here’s why it makes a difference:

  • Real-time data – Every run of the script pulls the most up-to-date results. Your reports actually match what’s happening right now.
  • Handles big workloads – Whether it’s a handful of keywords or thousands, the setup scales without extra effort.
  • One central hub – Instead of juggling tools, everything lands in Sheets where you can filter, share, or link to dashboards.

How does this help with SEO reporting

For teams reporting on rankings, this approach is a major upgrade:

  • Hours saved each week since there’s no manual work.
  • Reports stay consistent because the pull process is the same every time.
  • Data lives in Sheets, which makes charts, pivots, and dashboards easy to build.
  • Collaboration is simple—everyone with access sees the same live data.
  • It’s affordable compared to heavy software, since you’re using tools already in your workflow.

What is Google Apps Script?

Google Apps Script is a coding environment built right inside Google’s tools. It’s based on JavaScript, but stripped down to be more approachable. Think of it as glue: it connects Sheets with outside apps and APIs. With just a few lines of script, you can fetch data, run automations, or even build lightweight tools that live entirely in your Google account.

The beauty is that it runs in the cloud. No software installs, no servers—just your browser and your Google login.

Why it’s great for API integrations

When it comes to SEO tracking, automation is everything. Apps Script makes API connections straightforward. Instead of downloading CSV files and manually importing them, your script calls the API, grabs the data, and drops it right into Sheets. You can even schedule it to refresh daily or hourly.

Here’s why it works so well:

  • Built-in functions like UrlFetchApp handle API requests.
  • Direct link to Sheets, so data is written and formatted automatically.
  • Time-based triggers mean reports update themselves in the background.

What you’ll need to set it up

The setup doesn’t require fancy tools or a developer background. Here’s the checklist:

  1. Google Sheets – This is where your keyword data lives. Think of it as your SEO dashboard where you can expand results into charts or share them with your team. Since it’s cloud-based, you always see the latest version.
  2. Google Apps Script – The coding environment inside Sheets. It’s where you’ll write the script that connects to the SERPHouse API and automates the updates. Even if you’ve never coded before, the basics are easy to pick up.
  3. SERPHouse API Key – Your access pass. You’ll generate it inside your SERPHouse account. Once added to the script, it authenticates your connection and ensures you’re pulling accurate SERP data.

With those three things, you’re ready to build a reporting system that updates itself, scales with your keyword list, and saves hours every single week.

Integrate SERPHouse SERP API with Google Sheets (Apps Script)

Step 1: Function Trigger

In Google Apps Script, the first step in any automation is setting up a function trigger. This trigger is what starts your script — it decides when the code runs, whether you launch it by hand or let it run on a set schedule.

Here’s the example:

function myFunction() {
  fetchBulkSERPHouseResults();
}

At first glance, this looks very simple. But it plays a crucial role. Let’s break it down:

  • function myFunction() { … } → This defines a function called myFunction. Think of it as a button or a starting switch. Every time this function runs, it kicks off your script.
  • Inside it, we’re calling fetchBulkSERPHouseResults();. This is another function (which we’ll define later) that contains the actual logic—fetching keywords, sending them to the SERPHouse API, and writing results back into your Google Sheet.

Step 2: Prepare Spreadsheet and Variables

Before pulling live results from SERPHouse, you’ll need to set up your Google Sheet and define the variables your script will use. This tells the script where to store the data, how to connect with the API, and how to process multiple keywords at once.

Here’s a simple example setup:

const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const baseUrl = 'https://api.serphouse.com/serp/live?';
const locId = 1026201;
const batchSize = 50;

Let’s break this down so it’s crystal clear:

  • const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    This line tells Apps Script to connect directly to the active Google Sheet you’re working in. Whatever sheet tab you’re currently on will be the one where your SERP data lands.
  • const apiKey = ‘YOUR_API_KEY’;
    This is your authentication key from SERPHouse. Without it, the API won’t let you fetch any data. Always keep this private and never share it publicly—think of it like a password.
  • const baseUrl = ‘https://api.serphouse.com/serp/live?’;
    This is the endpoint for fetching live SERP results. By defining it once here, you make your script cleaner and easier to update later if needed.
  • const locId = 1026201;
    SERPHouse lets you target searches by location. The locId is a numeric code that represents the location you want results from. For example, 1026201 could point to a specific country or region. This gives you hyper-local SEO insights.
  • const batchSize = 50;
    Instead of hitting the API with hundreds of keywords at once (which can slow things down or exceed limits), batchSize defines how many queries you’ll process in one request. Keeping it at 50 is a good balance between speed and efficiency.

Step 3: Get Keyword List from Google Sheet

Once your variables are ready, the next logical step is to feed your script the keywords you want to track. Think of Google Sheets as the central hub where you’ll manage all your keyword inputs and later review the output results.

Here’s a simple code snippet that fetches the keyword list from your sheet:

const lastRow = sheet.getLastRow();
const keywords = sheet.getRange(2, 2, lastRow - 1).getValues(); // B2:B
const columnC = sheet.getRange(2, 4, lastRow - 1).getValues(); // C2:C

Breaking It Down

  • const lastRow = sheet.getLastRow();
    This line tells the script: “Look at the sheet and figure out how many rows have data.” That way, the script always knows the length of your keyword list without you having to update it manually.
  • const keywords = sheet.getRange(2, 2, lastRow – 1).getValues();
    This fetches all the keywords from Column B, starting at Row 2 (since Row 1 is usually your header, like “Keywords”). For example:
    • Row 2 → “best SEO tools”
    • Row 3 → “Google ranking tracker”
    • Row 4 → “free keyword checker”

The script will then use these as the inputs to fetch live SERP results.

  • const columnC = sheet.getRange(2, 4, lastRow – 1).getValues();
    This pulls data from Column D (because Sheets indexing starts at 1: column 2 = B, column 4 = D). You can use this column however you like — maybe to store extra metadata, track competitor URLs, or keep notes about specific keywords.

Step 4: Build API Requests

Once your keywords are in the spreadsheet, the next step is turning them into live API requests. In simple terms, you’re just formatting each query correctly before sending it to the SERPHouse API.

Here’s the sample code you’ll use:

const fetchRequests = [];
const rowMap = [];

for (let i = 0; i < keywords.length; i++) {
  const keyword = keywords[i][0];
  const isCFilled = columnC[i][0];

  if (!keyword || isCFilled) continue;

  const query = encodeURIComponent(keyword);
  const url = `${baseUrl}domain=google.com&q=${query}&api_token=${apiKey}&num_result=10&loc_id=${locId}`;

  fetchRequests.push({
    url: url,
    method: 'get',
    muteHttpExceptions: true
  });

  rowMap.push(i + 2); // Spreadsheet row number
}

At this stage, we take the keyword list and turn it into API requests for SERPHouse. The script checks each keyword, skips the empty ones, and builds a valid request URL. All of these requests are collected in an array so they can run together in bulk.

Here’s what happens in this step:

  • Loops through each keyword in your sheet
  • Skips empty rows or already-filled results
  • Encodes the keyword into a search-friendly format
  • Builds the API request URL with your API key, location ID, and keyword
  • Stores each request in fetchRequests
  • Tracks the correct spreadsheet row in rowMap to return the results later

In short → this step transforms plain keywords into clean, ready-to-send search queries for SERPHouse.

Step 5: Exit If No New Keywords

Once you’ve built the API requests, it’s important to check whether there are actually any new keywords to process. If every keyword in your Google Sheet already has results, or if no fresh entries exist, running the rest of the script would just waste resources.

That’s where this simple check comes in:

if (fetchRequests.length === 0) {
  Logger.log('No new keywords to process.');
  return;
}

Here’s why this step matters:

  • Saves resources → prevents unnecessary API calls.
  • Keeps reports clean → avoids overwriting old results.
  • Improves efficiency → script stops running immediately if nothing new is found.
  • Easy debugging → logs a clear message so you know why the script didn’t continue.

In short, this acts like a gatekeeper: if no new keywords are waiting, the script gracefully exits instead of running pointlessly.

Step 6: Send Requests in Batches

By now, your script has a queue of API requests ready to go. But here’s the thing: sending hundreds of requests at once can overload the system or even hit API rate limits. That’s why it’s smart to break them into smaller, more manageable groups — also known as batch processing.

Here’s the code that does exactly that:

for (let b = 0; b < fetchRequests.length; b += batchSize) {
  const batchRequests = fetchRequests.slice(b, b + batchSize);
  const batchRows = rowMap.slice(b, b + batchSize);
  const responses = UrlFetchApp.fetchAll(batchRequests);
}

How It Works

  • Loop through requests in chunks → Instead of sending all at once, the loop processes them in groups defined by batchSize (in our case, 50).
  • slice creates smaller batches → It takes just the right portion of requests and their matching row numbers.
  • UrlFetchApp.fetchAll() → This is Google Apps Script’s powerful method to send multiple HTTP requests simultaneously. In one go, it fetches all results for the batch.

Why Batch Processing Matters

  • Efficiency → Sending 50 requests at a time is faster and more stable than handling each one individually.
  • Avoids throttling → APIs often limit how many requests you can make per second; batching helps you stay safe.
  • Scalability → Whether you’re tracking 100 or 5,000 keywords, batching keeps your workflow smooth.
  • Accuracy → By mapping each batch to specific spreadsheet rows, results always land in the right place.

Step 7: Parse API Responses

Up until now, your script has done all the prep work — collecting keywords, building API requests, and sending them off in batches. But an API response on its own is just raw JSON data. To make it useful, we need to parse that response, extract the important details, and then neatly place them into the spreadsheet.

Here’s the code that handles it:

for (let i = 0; i < responses.length; i++) {
  const response = responses[i];
  const row = batchRows[i];

  try {
    const json = JSON.parse(response.getContentText());

    if (
      json.status === 'success' &&
      json.results &&
      json.results.results &&
      json.results.results.organic
    ) {
      const organicResults = json.results.results.organic;
      const links = organicResults.slice(0, 10).map(r => r.link || '');

      sheet.getRange(row, 3, 1, 10).setValues([links]); // Fill C to L
    } else {
      sheet.getRange(row, 3).setValue('No results or error');
    }
  } catch (e) {
    sheet.getRange(row, 3).setValue('API Error: ' + e.message);
  }
}

Breaking It Down

  • Loop through each response
    Each response from SERPHouse corresponds to one keyword in your sheet.
  • JSON.parse(response.getContentText())
    Converts the raw response text into a usable JavaScript object. Without parsing, the script can’t understand the data.
  • Check for success
    The condition ensures the response contains valid results. If the API didn’t return proper data (maybe due to a rate limit or a missing keyword), the script gracefully skips it.
  • Extract organic results
    json.results.results.organic holds the actual search results. From here, the script grabs the top 10 organic links.
  • Write results into the sheet
    sheet.getRange(row, 3, 1, 10).setValues([links]);
    Places up to 10 links (columns C through L) into the correct row for that keyword.
  • Error handling
    If something goes wrong (invalid response, parsing issue, API error), the script writes a clear message into the sheet so you know what happened.

Step 8: Add Delay Between Batches

When working with APIs, speed isn’t always your best friend. While batching requests (Step 6) is efficient, firing them back-to-back without any pause can sometimes cause issues, such as API throttling (when the server limits the number of requests you can send at once). To avoid that, we add a short delay between each batch.

Here’s the line of code that handles it:

Utilities.sleep(1000); // 1 second delay to avoid throttling

What This Does

  • Utilities.sleep(1000) → Tells the script to “pause” for 1,000 milliseconds (which equals 1 second).
  • After completing one batch of requests, the script waits for a moment before moving on to the next batch.
  • This reduces the risk of being blocked, throttled, or flagged for suspicious traffic by the API.

Final Complete Code Example

Now that we’ve walked through each step — from setting up triggers, preparing your spreadsheet, fetching keywords, building API requests, batching, parsing responses, and even adding delays — it’s time to put everything together.Here’s the full working script you can copy into your Google Apps Script editor:

function myFunction() {
  fetchBulkSERPHouseResults();
}

function fetchBulkSERPHouseResults() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
  const baseUrl = 'https://api.serphouse.com/serp/live?';
  const locId = 1026201;
  const batchSize = 50;

  const lastRow = sheet.getLastRow();
  const keywords = sheet.getRange(2, 2, lastRow - 1).getValues(); // B2:B
  const columnC = sheet.getRange(2, 4, lastRow - 1).getValues(); // C2:C

  const fetchRequests = [];
  const rowMap = [];

  // Step 4: Build API requests
  for (let i = 0; i < keywords.length; i++) {
    const keyword = keywords[i][0];
    const isCFilled = columnC[i][0];

    if (!keyword || isCFilled) continue;

    const query = encodeURIComponent(keyword);
    const url = `${baseUrl}domain=google.com&q=${query}&api_token=${apiKey}&num_result=10&loc_id=${locId}`;

    fetchRequests.push({
      url: url,
      method: 'get',
      muteHttpExceptions: true
    });

    rowMap.push(i + 2); // Row number in sheet
  }

  // Step 5: Exit if no new keywords
  if (fetchRequests.length === 0) {
    Logger.log('No new keywords to process.');
    return;
  }

  // Step 6: Send requests in batches
  for (let b = 0; b < fetchRequests.length; b += batchSize) {
    const batchRequests = fetchRequests.slice(b, b + batchSize);
    const batchRows = rowMap.slice(b, b + batchSize);
    const responses = UrlFetchApp.fetchAll(batchRequests);

    // Step 7: Parse API responses
    for (let i = 0; i < responses.length; i++) {
      const response = responses[i];
      const row = batchRows[i];

      try {
        const json = JSON.parse(response.getContentText());

        if (
          json.status === 'success' &&
          json.results &&
          json.results.results &&
          json.results.results.organic
        ) {
          const organicResults = json.results.results.organic;
          const links = organicResults.slice(0, 10).map(r => r.link || '');
          sheet.getRange(row, 3, 1, 10).setValues([links]); // Fill columns C → L
        } else {
          sheet.getRange(row, 3).setValue('No results or error');
        }
      } catch (e) {
        sheet.getRange(row, 3).setValue('API Error: ' + e.message);
      }
    }

    // Step 8: Add delay between batches
    Utilities.sleep(1000); // 1 sec delay to avoid throttling
  }
}

How This Script Works

  • Runs automatically: The myFunction() serves as your entry point.
  • Reads your keywords: Picks them up from column B of your Google Sheet.
  • Checks duplicates: Skips rows that already have results.
  • Sends requests: Uses the SERPHouse API to fetch live SERP results.
  • Stores results: Writes the top 10 organic links into columns C → L.
  • Handles errors: Marks failed rows with a clear error message.
  • Stays safe: Waits one second between each batch to avoid throttling.

Advanced Use Cases

Once you’ve got the SERP API with Google Sheets running, don’t stop at rankings. That’s just the baseline. The real fun begins when you twist the setup to handle bigger SEO challenges. Think less “basic tracker” and more “custom command center” that runs inside your spreadsheet.

1. Multi-location rank tracking
Most brands don’t care about just one market. They want to see how things look across cities or even countries. By tweaking the locId parameter, you can run the same keyword list for multiple places. Then you can stack the results next to each other, spot where you’re winning locally, and even build region-specific dashboards straight inside Sheets.

2. Competitor checks
It’s not enough to know your own spot. You need to know who’s sitting around you. With a little extra script logic, you can track your competitors at the same time. That way you’ll know if someone pushes you down, if the SERP is shifting a lot, or if a rival starts creeping into your space.

3. SERP feature monitoring
Blue links aren’t the whole story anymore. Snippets, maps, videos, and “People Also Ask” boxes take up a huge part of the screen. By pulling more data from the API, you can keep track of those too. You’ll know which features show up for your terms, whether your site appears, and where you might need to optimize differently.

Conclusion

Here’s the point: pulling data with the SERP API with Google Sheets isn’t just about saving time. It’s about shaping reporting around how you work. You decide which metrics matter, how they’re displayed, and how far you want to take the automation.

And honestly? Manual keyword checks just don’t scale anymore. Search moves too fast. Automation like this keeps your reporting sharp, current, and always ready without burning hours.

FAQs

1. Can I fetch more than 50 keywords at once?

Yes, but not in a single request. The script is designed to handle large keyword lists by breaking them into batches of 50. So, if you have 200 keywords, the script will run four batches automatically. This way, you stay within API limits and avoid overloading your requests while still covering all your keywords.

2. How do I know if my API key is valid?

The easiest way is to run the script with a sample keyword. If your key is valid, the results will appear directly in your Google Sheet. If it’s invalid or expired, you’ll see an error message like “API Error”. You can also double-check your key’s status in the SERPHouse dashboard, where usage stats and active keys are listed.

3. Can I share the sheet with my team?

Absolutely. Since it’s a Google Sheet, your team can view or collaborate in real-time once you share it. However, remember that the script is tied to your Google account and API key. If teammates want to run the script themselves, they’ll need their own API key to avoid sharing yours for security reasons.