Search & AI  /  18 septiembre 2026

How to Connect to the Bing Webmaster Tools API Using Google Colab

Summarise with AI

Bing Webmaster Tools lets you analyse how Bing crawls, indexes and displays a website in its search results. As well as using the visual interface, you can also access part of that information programmatically through its API.

In this tutorial you will learn how to connect Google Colab to the Bing Webmaster Tools API to extract performance data such as clicks and impressions. The goal is that anyone can copy and paste the scripts, adapt them with their own data and get a working first connection.

With this tutorial you will be able to:

  • Generate an API Key in Bing Webmaster Tools.
  • Connect to the API from Google Colab.
  • Verify whether the connection works.
  • Download clicks and impressions data.
  • Convert the response into a table.
  • Save or export the results for analysis.

1. What is the Bing Webmaster Tools API

The Bing Webmaster Tools API allows programmatic access to data from sites verified in Bing Webmaster Tools.

According to Microsoft’s official documentation, the API lets you query information about registered sites, including data such as Rank & Traffic Stats, Link Details, Keyword Details and Crawl Stats. It also allows you to submit URLs, sitemaps and other site details.

There are two main options to access the API:

  • OAuth 2.0.
  • API Key.

Microsoft indicates that webmasters can use either method, although OAuth 2.0 is listed as recommended in the documentation. This tutorial will use API Key because it is the simplest way to get started from Colab.

2. What you need before starting

Before opening Colab, you need to have:

  • A Bing Webmaster Tools account.
  • A website added and verified in Bing Webmaster Tools.
  • An API Key from Bing Webmaster Tools.
  • A Google Colab notebook.
  • The exact URL of the verified property.

The property URL matters. If in Bing Webmaster Tools you have the property verified as https://www.example.com/, that exact URL must be used in the script. If you use a different variant (without www, with http, etc.) the API may return an error or not find any data.

3. How to generate the API Key in Bing Webmaster Tools

To generate the API Key:

  1. Log in to Bing Webmaster Tools.
  2. Select your account.
  3. Go to the settings section.
  4. Find the API Access section.
  5. Accept the terms if this is your first time accessing it.
  6. Click Generate API Key.
  7. Copy the generated API Key.

Microsoft explains that the API Key is generated for the user, not for a specific site. This means the same API Key can be used for all sites that user has verified in Bing Webmaster Tools.

Important: do not share your API Key publicly. If you think the key has been exposed or compromised, delete it and generate a new one from Bing Webmaster Tools.

4. Create a notebook in Google Colab

Open Google Colab and create a new notebook. Recommended name: Bing_Webmaster_Tools_API_Colab.

5. Cell 1 — Install and import libraries

The first cell installs and imports the necessary libraries: requests to make API calls, pandas to convert data into tables, re to clean dates and getpass to paste the API Key without displaying it on screen.

!pip install -q pandas requests

import requests
import pandas as pd
import re
from getpass import getpass

print("Libraries ready")

6. Cell 2 — Configure the API Key and site URL

In this cell you enter your Bing Webmaster Tools API Key and the exact URL of the verified property. To avoid leaving the API Key written directly in the notebook, we use getpass().

BWT_API_KEY = getpass("Paste your Bing Webmaster Tools API Key: ").strip()

# Change this URL to the exact URL of your verified property in Bing Webmaster Tools
BWT_SITE_URL = "https://www.yourdomain.com/"

BWT_BASE_URL = "https://ssl.bing.com/webmaster/api.svc/json"

print("Configuration loaded")
print(f"Site configured: {BWT_SITE_URL}")

7. Cell 3 — Create a function to call the API

To avoid repeating code, we create a general function called bwt_get(). This function builds the endpoint URL, adds the API Key, sends the request, hides the API Key in prints, checks whether the response was correct and returns the data in JSON format.

def bwt_get(method, params=None):
    '''
    Calls a JSON method from the Bing Webmaster Tools API.
    method: name of the API method.
    params: additional parameters for the call.
    '''
    if params is None:
        params = {}

    params = params.copy()
    params["apikey"] = BWT_API_KEY

    url = f"{BWT_BASE_URL}/{method}"
    response = requests.get(url, params=params, timeout=120)

    # Hide the API key in the print to avoid exposing it on screen
    safe_url = response.url.replace(BWT_API_KEY, "HIDDEN_API_KEY")
    print(f"Request: {safe_url}")
    print(f"Status: {response.status_code}")

    if response.status_code != 200:
        print("Bing response:")
        print(response.text[:2000])
        raise Exception(f"Bing Webmaster API error: {response.status_code}")

    data = response.json()

    if isinstance(data, dict) and "d" in data:
        return data["d"]

    return data


print("bwt_get function ready")

8. Cell 4 — Create a function to clean dates

Some Bing responses may return dates in a format like /Date(1316156400000-0700)/. We create a function that converts them to a normal format.

def parse_bing_date(value):
    '''
    Converts Bing dates like /Date(1316156400000-0700)/ to a normal date.
    '''
    if pd.isna(value):
        return None

    value = str(value)
    match = re.search(r"/Date((d+)", value)

    if match:
        timestamp_ms = int(match.group(1))
        return pd.to_datetime(timestamp_ms, unit="ms", utc=True).date()

    try:
        return pd.to_datetime(value).date()
    except Exception:
        return None


print("parse_bing_date function ready")

9. Cell 5 — Convert the response into a DataFrame

The API returns data in JSON. To analyse it conveniently, we convert the response into a pandas table.

def clean_bwt_dataframe(data):
    '''
    Converts a Bing Webmaster Tools API response into a clean DataFrame.
    '''
    df = pd.DataFrame(data)

    if df.empty:
        return df

    if "__type" in df.columns:
        df = df.drop(columns=["__type"])

    if "Date" in df.columns:
        df["Date"] = df["Date"].apply(parse_bing_date)
        df = df.sort_values("Date")

    return df


print("clean_bwt_dataframe function ready")

10. Cell 6 — Test the connection with GetRankAndTrafficStats

The first method we will test is GetRankAndTrafficStats. This method returns traffic statistics for the site, such as clicks and impressions. The official documentation states that data is updated daily and includes traffic from different Bing verticals, such as Web, Chat, News, Images, Videos and Knowledge Panel since 24 March 2023.

try:
    test_data = bwt_get(
        method="GetRankAndTrafficStats",
        params={"siteUrl": BWT_SITE_URL}
    )

    df_test = clean_bwt_dataframe(test_data)

    print("Connection successful")
    display(df_test.head())
    print(f"Rows: {len(df_test)}")
    print(f"Columns: {df_test.columns.tolist()}")

except Exception as e:
    print("Error connecting to Bing Webmaster Tools API")
    print(e)
    print("nCheck:")
    print("1. That the API Key is correct.")
    print("2. That the site is verified in Bing Webmaster Tools.")
    print("3. That BWT_SITE_URL matches exactly the verified property.")

If everything works correctly, you should see a table with columns Date, Clicks and Impressions.

11. Understanding the GetRankAndTrafficStats results

The result typically includes:

  • Date: date.
  • Clicks: clicks recorded by Bing.
  • Impressions: impressions recorded by Bing.

This data lets you build a time series to track performance trends in Bing. If impressions go up, the site is appearing more in Bing. If there are many impressions but few clicks, there may be opportunities to improve titles, snippets or relevance. This kind of analysis is part of a solid technical SEO strategy.

12. Cell 7 — Save data to CSV

output_file = "bwt_rank_traffic_stats.csv"
df_test.to_csv(output_file, index=False, encoding="utf-8-sig")
print(f"File created: {output_file}")

Then, in Colab, you can download it from the files panel.

13. Cell 8 — Download Query Stats from Bing

Another useful method is GetQueryStats, which can return data related to search queries in Bing, if available for the property.

try:
    query_stats_data = bwt_get(
        method="GetQueryStats",
        params={"siteUrl": BWT_SITE_URL}
    )

    df_query_stats = clean_bwt_dataframe(query_stats_data)

    print("Query Stats downloaded")
    display(df_query_stats.head())
    print(f"Rows: {len(df_query_stats)}")
    print(f"Columns: {df_query_stats.columns.tolist()}")

except Exception as e:
    print("Could not download Query Stats")
    print(e)

14. What to do if GetQueryStats returns no data

It may happen that GetQueryStats returns an empty table, an error or columns different from what was expected. This can depend on the verified property, the volume of available data, the account settings or changes to the API.

If this happens, it does not necessarily mean the API is not connected correctly. If GetRankAndTrafficStats works, the base connection is correct.

15. Cell 9 — Save Query Stats to CSV

if "df_query_stats" in globals() and not df_query_stats.empty:
    output_file = "bwt_query_stats.csv"
    df_query_stats.to_csv(output_file, index=False, encoding="utf-8-sig")
    print(f"File created: {output_file}")
else:
    print("No Query Stats data to export.")

16. Cell 10 — Create a clicks and impressions chart

Once the Rank & Traffic data is downloaded, you can create a quick chart.

import matplotlib.pyplot as plt

if "df_test" in globals() and not df_test.empty:
    df_plot = df_test.copy()
    df_plot["Date"] = pd.to_datetime(df_plot["Date"])

    plt.figure(figsize=(12, 5))
    plt.plot(df_plot["Date"], df_plot["Clicks"], label="Clicks")
    plt.plot(df_plot["Date"], df_plot["Impressions"], label="Impressions")

    plt.title("Bing Webmaster Tools: Clicks and Impressions")
    plt.xlabel("Date")
    plt.ylabel("Volume")
    plt.legend()
    plt.grid(True)
    plt.show()

else:
    print("No data to chart.")

17. How to connect this data to Google Sheets

If you want to send the data automatically to Google Sheets, you can use gspread.

!pip install -q gspread gspread_dataframe
from google.colab import auth
auth.authenticate_user()

import gspread
from google.auth import default
from gspread_dataframe import set_with_dataframe

creds, _ = default()
gc = gspread.authorize(creds)

SPREADSHEET_ID = "PASTE_YOUR_GOOGLE_SHEET_ID_HERE"
sh = gc.open_by_key(SPREADSHEET_ID)

print("Google Sheet connected")
print(sh.url)
def write_df_to_sheet(spreadsheet, tab_name, df):
    df = df.copy()

    try:
        worksheet = spreadsheet.worksheet(tab_name)
        worksheet.clear()
    except Exception:
        rows = max(len(df) + 20, 100)
        cols = max(len(df.columns) + 5, 10) if not df.empty else 10
        worksheet = spreadsheet.add_worksheet(title=tab_name, rows=rows, cols=cols)

    if df.empty:
        worksheet.update("A1", [["No data"]])
    else:
        set_with_dataframe(worksheet, df)

    print(f"Tab updated: {tab_name} | Rows: {len(df)}")
write_df_to_sheet(sh, "RAW_BWT_RankTraffic", df_test)

if "df_query_stats" in globals() and not df_query_stats.empty:
    write_df_to_sheet(sh, "RAW_BWT_QueryStats", df_query_stats)

18. Common errors and how to fix them

Error: InvalidApiKey. Means the API Key is incorrect, was deleted or was copied incorrectly. Generate a new API Key, copy the complete key and re-run the configuration cell.

Error: the site returns no data. Can happen if the URL used in the script does not match the verified property. Check that in Bing Webmaster Tools the property appears exactly as you have it in BWT_SITE_URL.

Error: status other than 200. Can be caused by an incorrect API Key, unverified site, misspelled endpoint, temporary API issue or incorrect parameters. The script prints the request URL hiding the API Key to help you review what is being sent.

The table comes back empty. If the connection works but there is no data, it may be because the site has low volume in Bing, the queried method has no available data, the API returns data in a different structure or the period or data type does not apply to that property.

19. Security best practices

  • Do not paste your API Key in public documents.
  • Do not upload notebooks with the API Key written directly in them.
  • Use getpass() to paste the key in a hidden way.
  • If the API Key is exposed, delete it and generate a new one.

Microsoft warns that if an API Key is lost or compromised, it must be deleted and a new one generated from Bing Webmaster Tools.

20. What you can do next

Once the API is connected, you can use this data to:

  • Create automatic traffic reports in Bing.
  • Compare Google Search Console vs Bing Webmaster Tools.
  • Analyse clicks and impressions trends.
  • Save historical data in Google Sheets.
  • Create dashboards in Looker Studio.
  • Combine this data with Grounding Queries from AI Performance.
  • Detect whether Bing/Copilot is giving visibility to specific content.

Integrating these insights with your AI SEO strategy gives you a fuller picture of your organic visibility across both traditional and generative search.

Conclusion

Connecting the Bing Webmaster Tools API with Google Colab lets you extract Bing data automatically and bring it into tables or dashboards.

The simplest way to start is using an API Key and the GetRankAndTrafficStats method, which quickly validates whether the connection works.

From there, you can expand the analysis with other methods, save data to Google Sheets or cross-reference it with Google Search Console data. This flow is especially useful for creating SEO and GEO analyses without relying solely on the Bing Webmaster Tools visual interface.

Julio Febres

Author

Julio Febres

Estrategia Digital — IA SEO & Diseño Web

Especialista en IA SEO y Diseño Web con más de 6 años de experiencia desde 2020. Trabajo directamente con marcas para que aparezcan en Google, AI Overviews y motores generativos como ChatGPT y Perplexity. Creador del canal @juliofebresSEO sobre SEO y estrategia digital.

Prefer to have it done for you?

Position your brand where your customers are searching

Talk to the team

Shall we talk about your project?

We reply in under 24 hours

Contact us