SDKs

The Microsoft Web IQ SDKs provide typed clients for Auto, web, news, video, image, and Places search, Commerce, plus Browse. Choose a language at the top of this page to switch all installation commands and examples together.

These examples use the public 1.2.1 SDK releases for Auto search with typed evidence and result-scoped citations. Upgrade earlier SDK versions before running them.

Property Python TypeScript Rust Java .NET
Package webiq @microsoft/webiq webiq com.microsoft.webiq:webiq Microsoft.WebIQ
Version used 1.2.1 1.2.1 1.2.1 1.2.1 1.2.1
Runtime Python 3.11+ Node.js 22.13+ (22.x) or 24+ Rust 1.88+ Java 11+ .NET 8+
License MIT MIT MIT MIT MIT

You need a Web IQ API key or a Microsoft Entra identity with access to Web IQ. See Authentication.

Installation

python -m pip install webiq==1.2.1
npm install @microsoft/webiq@1.2.1

Add the SDK and the Tokio runtime to your project:

cargo add webiq@1.2.1
cargo add tokio --features macros,rt-multi-thread

Add the Maven Central dependency to your project's pom.xml. Configure the project to compile for Java 11 or later.

<dependency>
    <groupId>com.microsoft.webiq</groupId>
    <artifactId>webiq</artifactId>
    <version>1.2.1</version>
</dependency>

For Gradle:

implementation "com.microsoft.webiq:webiq:1.2.1"

These examples use the public Microsoft.WebIQ 1.2.1 package and require .NET 8 or later. Run this command in a .NET console project:

dotnet add package Microsoft.WebIQ --version 1.2.1

Quickstart

Set the WEBIQ_API_KEY environment variable to your API key before running the example. Don't put API keys in source code.

The example calls Auto in advanced mode with a 60-second per-attempt timeout, prints each evidence result with its supporting citations, then calls Web, News, Video, Image, and Places Search and retrieves a page with Browse. Auto returns evidence, not a generated final answer. See the Auto reference for evidence types and request options.

Web, News, and Browse request passages, the recommended format for grounding. Browse also requires a nonblank selection query of up to 1000 characters. For full-document formats, see Content formats.

import os
from webiq import WebIQClient
from webiq.types import BrowseContentFormat, ContentFormat, AutoMode

with WebIQClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
    evidence = client.auto.search(
        "What are the latest developments in retrieval-augmented generation?",
        mode=AutoMode.advanced,
        max_response_length=30000,
        max_citations=5,
        timeout=60.0,
    )
    for result in evidence.results or []:
        print(result.evidence)
        for citation in result.citations or []:
            print(citation.title, citation.url)

    web = client.web.search(
        "Microsoft Web IQ",
        max_results=5,
        content_format=ContentFormat.passage,
    )
    for result in web.webResults or []:
        print(result.title, result.url)

    news = client.news.search(
        "technology",
        max_results=5,
        content_format=ContentFormat.passage,
    )
    for item in news.newsResults or []:
        print(item.title, item.source)

    videos = client.videos.search("machine learning tutorial", max_results=5)
    for video in videos.videoResults or []:
        print(video.title, video.length)

    images = client.images.search("golden gate bridge", max_results=5)
    for image in images.imageResults or []:
        print(image.title, image.url)

    places = client.places.search(
        "coffee in Seattle",
        max_results=5,
        language="en",
        region="US",
        location="lat:47.6062;long:-122.3321",
    )
    for place in places.placeResults or []:
        print(place.name, place.businessUrl)

    page = client.browse.fetch(
        "https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
        query="How fast is Web IQ",
        content_format=BrowseContentFormat.passage,
        max_length=3000,
        live_crawl="fallback",
    )
    print(page.content)
import { WebIQClient, BrowseContentFormat, ContentFormat, LiveCrawlMode, AutoMode } from '@microsoft/webiq';

async function main() {
  const apiKey = process.env.WEBIQ_API_KEY;
  if (!apiKey) throw new Error('Set WEBIQ_API_KEY before running this example.');

  const client = new WebIQClient({ apiKey });
  try {
    const evidence = await client.auto.search(
      'What are the latest developments in retrieval-augmented generation?',
      { mode: AutoMode.ADVANCED, maxResponseLength: 30000, maxCitations: 5, timeout: 60_000 },
    );
    for (const result of evidence.results ?? []) {
      console.log(result.evidence);
      for (const citation of result.citations ?? []) console.log(citation.title, citation.url);
    }

    const web = await client.web.search('Microsoft Web IQ', {
      maxResults: 5,
      contentFormat: ContentFormat.PASSAGE,
    });
    for (const result of web.webResults ?? []) console.log(result.title, result.url);

    const news = await client.news.search('technology', {
      maxResults: 5,
      contentFormat: ContentFormat.PASSAGE,
    });
    for (const item of news.newsResults ?? []) console.log(item.title, item.source);

    const videos = await client.videos.search('machine learning tutorial', { maxResults: 5 });
    for (const video of videos.videoResults ?? []) console.log(video.title, video.length);

    const images = await client.images.search('golden gate bridge', { maxResults: 5 });
    for (const image of images.imageResults ?? []) console.log(image.title, image.url);

    const places = await client.places.search('coffee in Seattle', {
      maxResults: 5,
      language: 'en',
      region: 'US',
      location: 'lat:47.6062;long:-122.3321',
    });
    for (const place of places.placeResults ?? []) console.log(place.name, place.businessUrl);

    const page = await client.browse.fetch('https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283', {
      query: 'How fast is Web IQ',
      contentFormat: BrowseContentFormat.PASSAGE,
      maxLength: 3000,
      liveCrawl: LiveCrawlMode.FALLBACK,
    });
    console.log(page.content);
  } finally {
    await client.close();
  }
}

main().catch(console.error);
use webiq::{
    AutoSearchOptions, BrowseContentFormat, BrowseOptions, ContentFormat, ImageSearchOptions,
    LiveCrawlMode, NewsSearchOptions, PlacesSearchOptions, VideoSearchOptions,
    AutoMode, WebIqClient, WebSearchOptions,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = WebIqClient::new(std::env::var("WEBIQ_API_KEY")?)?;

    let evidence = client.auto().search(
        "What are the latest developments in retrieval-augmented generation?",
        AutoSearchOptions::new()
            .mode(AutoMode::Advanced)
            .max_response_length(30000)
            .max_citations(5)
            .timeout(std::time::Duration::from_secs(60)),
    ).await?;
    for result in evidence.results.unwrap_or_default() {
        println!("{:?}", result.evidence);
        for citation in result.citations.unwrap_or_default() {
            println!("{:?} {:?}", citation.title, citation.url);
        }
    }

    let web = client.web().search(
        "Microsoft Web IQ",
        WebSearchOptions::new()
            .max_results(5)
            .content_format(ContentFormat::Passage),
    ).await?;
    for result in web.web_results.unwrap_or_default() {
        println!("{:?} {:?}", result.title, result.url);
    }

    let news = client.news().search(
        "technology",
        NewsSearchOptions::new()
            .max_results(5)
            .content_format(ContentFormat::Passage),
    ).await?;
    for item in news.news_results.unwrap_or_default() {
        println!("{:?} {:?}", item.title, item.source);
    }

    let videos = client.videos().search(
        "machine learning tutorial",
        VideoSearchOptions::new().max_results(5),
    ).await?;
    for video in videos.video_results.unwrap_or_default() {
        println!("{:?} {:?}", video.title, video.length);
    }

    let images = client.images().search(
        "golden gate bridge",
        ImageSearchOptions::new().max_results(5),
    ).await?;
    for image in images.image_results.unwrap_or_default() {
        println!("{:?} {:?}", image.title, image.url);
    }

    let places = client.places().search(
        "coffee in Seattle",
        PlacesSearchOptions::new()
            .max_results(5)
            .language("en")
            .region("US")
            .location("lat:47.6062;long:-122.3321"),
    ).await?;
    for place in places.place_results.unwrap_or_default() {
        println!("{:?} {:?}", place.name, place.business_url);
    }

    let page = client.browse().fetch(
        "https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
        BrowseOptions::new()
            .query("How fast is Web IQ")
            .content_format(BrowseContentFormat::Passage)
            .max_length(3000)
            .live_crawl(LiveCrawlMode::Fallback),
    ).await?;
    println!("{}", page.content.unwrap_or_default());

    Ok(())
}

Save this example as src/main/java/WebIqSample.java in your Maven project and run mvn compile exec:java -Dexec.mainClass=WebIqSample.

import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.models.*;
import com.microsoft.webiq.resources.*;

public class WebIqSample {
    public static void main(String[] args) {
        try (WebIQClient client = WebIQClient.withApiKey(System.getenv("WEBIQ_API_KEY"))) {
            SearchAutoEvidenceResponse evidence = client.auto.search(
                    "What are the latest developments in retrieval-augmented generation?",
                    AutoSearchOptions.builder().mode(AutoMode.ADVANCED)
                            .maxResponseLength(30000).maxCitations(5)
                            .timeout(java.time.Duration.ofSeconds(60)).build());
            if (evidence.getResults() != null) {
                for (AutoEvidenceResult result : evidence.getResults()) {
                    System.out.println(result.getEvidence());
                    if (result.getCitations() != null) {
                        for (AutoEvidenceCitation citation : result.getCitations()) {
                            System.out.println(citation.getTitle() + " " + citation.getUrl());
                        }
                    }
                }
            }

            WebResponse web = client.web.search("Microsoft Web IQ",
                    WebSearchOptions.builder().maxResults(5)
                            .contentFormat(ContentFormat.PASSAGE).build());
            if (web.getWebResults() != null) {
                for (WebResult result : web.getWebResults()) {
                    System.out.println(result.getTitle() + " " + result.getUrl());
                }
            }

            NewsResponse news = client.news.search("technology",
                    NewsSearchOptions.builder().maxResults(5)
                            .contentFormat(ContentFormat.PASSAGE).build());
            if (news.getNewsResults() != null) {
                for (NewsItem item : news.getNewsResults()) {
                    System.out.println(item.getTitle() + " " + item.getSource());
                }
            }

            VideosResponse videos = client.videos.search("machine learning tutorial",
                    VideosSearchOptions.builder().maxResults(5).build());
            if (videos.getVideoResults() != null) {
                for (VideoItem video : videos.getVideoResults()) {
                    System.out.println(video.getTitle() + " " + video.getLength());
                }
            }

            ImagesResponse images = client.images.search("golden gate bridge",
                    ImagesSearchOptions.builder().maxResults(5).build());
            if (images.getImageResults() != null) {
                for (ImageItem image : images.getImageResults()) {
                    System.out.println(image.getTitle() + " " + image.getUrl());
                }
            }

            PlacesResponse places = client.places.search("coffee in Seattle",
                    PlacesSearchOptions.builder().maxResults(5)
                            .language("en").region("US")
                            .location("lat:47.6062;long:-122.3321").build());
            if (places.getPlaceResults() != null) {
                for (PlaceItem place : places.getPlaceResults()) {
                    System.out.println(place.getName() + " " + place.getBusinessUrl());
                }
            }

            BrowseResponse page = client.browse.fetch("https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
                    BrowseFetchOptions.builder()
                            .query("How fast is Web IQ")
                            .contentFormat(BrowseContentFormat.PASSAGE)
                            .maxLength(3000).liveCrawl(LiveCrawlMode.FALLBACK).build());
            System.out.println(page.getContent());
        }
    }
}
using Microsoft.WebIQ;
using Microsoft.WebIQ.Models;
using System.Text.Json;

string apiKey = Environment.GetEnvironmentVariable("WEBIQ_API_KEY")
    ?? throw new InvalidOperationException("Set WEBIQ_API_KEY before running this example.");
using var client = new WebIQClient(apiKey);

var evidence = await client.Auto.SearchAsync(
    "What are the latest developments in retrieval-augmented generation?",
    request =>
    {
        request.Mode = AutoMode.Advanced;
        request.MaxResponseLength = 30000;
        request.MaxCitations = 5;
    }, timeout: TimeSpan.FromSeconds(60));
foreach (var result in evidence.Results ?? [])
{
    Console.WriteLine(JsonSerializer.Serialize(result.Evidence));
    foreach (var citation in result.Citations ?? [])
        Console.WriteLine($"{citation.Title} {citation.Url}");
}

var web = await client.Web.SearchAsync("Microsoft Web IQ", request =>
{
    request.MaxResults = 5;
    request.ContentFormat = ContentFormat.Passage;
});
foreach (var result in web.WebResults ?? [])
    Console.WriteLine($"{result.Title} {result.Url}");

var news = await client.News.SearchAsync("technology", request =>
{
    request.MaxResults = 5;
    request.ContentFormat = ContentFormat.Passage;
});
foreach (var item in news.NewsResults ?? [])
    Console.WriteLine($"{item.Title} {item.Source}");

var videos = await client.Videos.SearchAsync("machine learning tutorial",
    request => request.MaxResults = 5);
foreach (var video in videos.VideoResults ?? [])
    Console.WriteLine($"{video.Title} {video.Length}");

var images = await client.Images.SearchAsync("golden gate bridge",
    request => request.MaxResults = 5);
foreach (var image in images.ImageResults ?? [])
    Console.WriteLine($"{image.Title} {image.Url}");

var places = await client.Places.SearchAsync("coffee in Seattle", request =>
{
    request.MaxResults = 5;
    request.Language = "en";
    request.Region = "US";
    request.Location = "lat:47.6062;long:-122.3321";
});
foreach (var place in places.PlaceResults ?? [])
    Console.WriteLine($"{place.Name} {place.BusinessUrl}");

var page = await client.Browse.FetchAsync("https://techcommunity.microsoft.com/blog/azuredevcommunityblog/why-ai-agents-need-external-grounding/4565283",
    request =>
    {
        request.ContentFormat = BrowseContentFormat.Passage;
        request.Query = "How fast is Web IQ";
        request.MaxLength = 3000;
        request.LiveCrawl = LiveCrawlMode.Fallback;
    });
Console.WriteLine(page.Content);

Microsoft Entra ID authentication

Instead of an API key, pass an Azure Identity credential. For local development, sign in with a supported developer tool, such as the Azure CLI. For Azure-hosted applications, use managed identity or workload identity. Your identity must have access to Web IQ.

The default OAuth scope is https://api.microsoft.ai/.default.

Install the optional authentication dependency:

python -m pip install "webiq[entra]==1.2.1"
from azure.identity import DefaultAzureCredential
from webiq import WebIQClient

with DefaultAzureCredential() as credential:
    with WebIQClient(credential=credential) as client:
        response = client.web.search("Microsoft Web IQ")
        print(response.webResults)
npm install "@azure/identity@>=4.13.1"
import { DefaultAzureCredential } from '@azure/identity';
import { WebIQClient } from '@microsoft/webiq';

const client = new WebIQClient({ credential: new DefaultAzureCredential() });
try {
  const response = await client.web.search('Microsoft Web IQ');
  console.log(response.webResults);
} finally {
  await client.close();
}

Azure Identity support is included in the SDK. The SDK re-exports azure_identity, so no extra dependency is needed. This example uses a developer credential after az login or azd auth login:

use webiq::{azure_identity::DeveloperToolsCredential, WebIqClient};

let credential = DeveloperToolsCredential::new(None)?;
let client = WebIqClient::builder()
    .credential(credential)
    .build()?;
let response = client.web().search("Microsoft Web IQ", Default::default()).await?;
println!("{:?}", response.web_results);

For hosted applications, choose ManagedIdentityCredential or WorkloadIdentityCredential from webiq::azure_identity.

Add com.azure:azure-identity to your Maven or Gradle dependencies, using a version compatible with your project's Azure SDK dependencies.

import com.azure.identity.DefaultAzureCredentialBuilder;
import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.WebIQClientOptions;

WebIQClientOptions options = WebIQClientOptions.builder()
        .credential(new DefaultAzureCredentialBuilder().build())
        .build();
try (WebIQClient client = new WebIQClient(options)) {
    System.out.println(client.web.search("Microsoft Web IQ").getWebResults());
}
dotnet add package Azure.Identity
using Azure.Identity;
using Microsoft.WebIQ;

using var client = new WebIQClient(new WebIQClientOptions
{
    Credential = new DefaultAzureCredential()
});
var response = await client.Web.SearchAsync("Microsoft Web IQ");
Console.WriteLine(response.WebResults?.Count);

Resources and request options

Use the REST reference for parameter descriptions, supported values, response fields, and service limits.

Resource Method Reference
Auto client.auto.search(query, ...) Auto
Web client.web.search(query, ...) Web Search
News client.news.search(query, ...) News Search
Videos client.videos.search(query, ...) Video Search
Images client.images.search(query, ...) Image Search
Places client.places.search(query, ...) Places
Browse client.browse.fetch(url, ...) Browse
Commerce Search client.commerce.search(query, ...) Commerce
Commerce Offers client.commerce.fetch_offers(...) Commerce
Commerce Product Details client.commerce.fetch_details(...) Commerce

Request options use snake_case; response properties use camelCase. Use SDK enums for supported values. For example:

from webiq.types import ContentFormat, ImageAspectRatio, ImageSize, SafeSearch

web = client.web.search(
    "search terms",
    max_results=10,
    language="en",
    region="US",
    location="lat:40.7;long:-74.0",
    content_format=ContentFormat.passage,
    max_length=3000,
)
news = client.news.search(
    "search terms",
    max_results=10,
    content_format=ContentFormat.passage,
    max_length=3000,
)
videos = client.videos.search(
    "search terms", max_results=5, enable_playlist=True, freshness="month",
)
images = client.images.search(
    "search terms",
    max_results=5,
    aspect_ratio=ImageAspectRatio.wide,
    image_size=ImageSize.large,
    safe_search=SafeSearch.strict,
    watermark_free=True,
)

The remaining snippets assume an open client unless they construct one explicitly.

Resource Method Reference
Auto client.auto.search(query, options) Auto
Web client.web.search(query, options) Web Search
News client.news.search(query, options) News Search
Videos client.videos.search(query, options) Video Search
Images client.images.search(query, options) Image Search
Places client.places.search(query, options) Places
Browse client.browse.fetch(url, options) Browse
Commerce Search client.commerce.search(query, options) Commerce
Commerce Offers client.commerce.fetchOffers(options) Commerce
Commerce Product Details client.commerce.fetchDetails(options) Commerce

Request options and response properties use camelCase, such as maxResults, contentFormat, liveCrawl, and aspectRatio. Pass options as the second argument. Use SDK enums for supported values, as shown in the quickstart.

The remaining snippets assume an open client and run inside an async function, unless they construct a client explicitly. Top-level await requires an ES module.

Resource Method Reference
Auto client.auto().search(query, options) Auto
Web client.web().search(query, options) Web Search
News client.news().search(query, options) News Search
Videos client.videos().search(query, options) Video Search
Images client.images().search(query, options) Image Search
Places client.places().search(query, options) Places
Browse client.browse().fetch(url, options) Browse
Commerce Search client.commerce().search(query, options) Commerce
Commerce Offers client.commerce().fetch_offers(options) Commerce
Commerce Product Details client.commerce().fetch_details(options) Commerce

Build options with AutoSearchOptions, WebSearchOptions, NewsSearchOptions, VideoSearchOptions, ImageSearchOptions, PlacesSearchOptions, BrowseOptions, CommerceSearchOptions, CommerceOffersOptions, or CommerceDetailsOptions. Response fields use snake_case and optional values use Option.

The remaining snippets run inside an async function returning Result, with an open client unless they construct one explicitly. Use the Tokio runtime setup from the quickstart.

Resource Method Reference
Auto client.auto.search(query, AutoSearchOptions) Auto
Web client.web.search(query, WebSearchOptions) Web Search
News client.news.search(query, NewsSearchOptions) News Search
Videos client.videos.search(query, VideosSearchOptions) Video Search
Images client.images.search(query, ImagesSearchOptions) Image Search
Places client.places.search(query, PlacesSearchOptions) Places
Browse client.browse.fetch(url, BrowseFetchOptions) Browse
Commerce Search client.commerce.search(query, CommerceSearchOptions) Commerce
Commerce Offers client.commerce.fetchOffers(CommerceOffersOptions) Commerce
Commerce Product Details client.commerce.fetchDetails(CommerceDetailsOptions) Commerce

Build request options with camelCase builder methods such as maxResults, contentFormat, and maxLength. Read response properties through getters such as getWebResults() and getTraceId(). Optional response fields can be null.

The remaining snippets run inside a method, with an open client unless they construct one explicitly. Place imports at the top of your Java file.

Resource Async method Reference
Auto client.Auto.SearchAsync(query, configure) Auto
Web client.Web.SearchAsync(query, configure) Web Search
News client.News.SearchAsync(query, configure) News Search
Videos client.Videos.SearchAsync(query, configure) Video Search
Images client.Images.SearchAsync(query, configure) Image Search
Places client.Places.SearchAsync(query, configure) Places
Browse client.Browse.FetchAsync(url, configure) Browse
Commerce Search client.Commerce.SearchAsync(query, configure) Commerce
Commerce Offers client.Commerce.FetchOffersAsync(...) Commerce
Commerce Product Details client.Commerce.FetchDetailsAsync(...) Commerce

Request and response properties use PascalCase. Set request options in the configuration callback, or pass a request model directly. Synchronous Search and Fetch methods are also available.

The remaining snippets assume an open client unless they construct one explicitly.

Auto availability

Auto is available in all five SDKs at version 1.2.1. Python and Java expose Auto through both their synchronous and asynchronous clients; .NET provides Search and SearchAsync; TypeScript and Rust use asynchronous calls.

Write a complete natural-language question and preserve the constraints that matter to your application. Read each result's evidence together with that result's citations; citations support only their enclosing result. For parameters, evidence types, and service limits, see the Auto API reference.

Commerce

Note

The Commerce APIs are in private preview and are included with AppIDs that have full document access. Access is enabled separately for Search, Offers, and Product Details. See Build a shopping experience with the Commerce APIs.

Search for products, then fetch offers and product details for a product you found. When you show an offer, link to its clickUrl exactly as returned; see Link to offers.

response = client.commerce.search(
    "wireless headphones",
    max_results=5,  # 1-50, default 10
    language="en",
    region="US",
)
for product in response.products or []:
    if product.id:
        offer_id = product.offers[0].id if product.offers else None
        offers = client.commerce.fetch_offers(
            product_id=product.id, sku_id=product.skuId, offer_id=offer_id)
        details = client.commerce.fetch_details(
            product_id=product.id, sku_id=product.skuId)
        for offer in offers.offers or []:
            print(offer.name, offer.price, offer.clickUrl)
        for detail in details.products or []:
            print(detail.name, detail.description, detail.rating)

fetch_offers requires at least one of product_id, sku_id, or offer_id. fetch_details requires a non-whitespace product_id or sku_id and returns zero or one product, not a batch. Both accept language, region, and timeout; offers also accept location. The same methods are available with await on WebIQAsyncClient.

const response = await client.commerce.search('wireless headphones', {
  maxResults: 5, // 1-50, default 10
  language: 'en',
  region: 'US',
});
for (const product of response.products ?? []) {
  if (product.id?.trim()) {
    const offers = await client.commerce.fetchOffers({
      productId: product.id,
      skuId: product.skuId,
      offerId: product.offers?.[0]?.id,
    });
    const details = await client.commerce.fetchDetails({
      productId: product.id,
      skuId: product.skuId,
    });
    console.log(offers.offers, details.products);
  }
}

fetchOffers requires at least one of productId, skuId, or offerId. fetchDetails requires a non-whitespace productId or skuId and returns zero or one product, not a batch. Both accept language, region, timeout, and signal; offers also accept location. Search identifiers and collections are optional.

use webiq::{CommerceDetailsOptions, CommerceOffersOptions, CommerceSearchOptions};

let response = client.commerce().search("wireless headphones",
    CommerceSearchOptions::new().max_results(5).language("en").region("US")).await?;
for product in response.products.unwrap_or_default() {
    if let Some(id) = product.id.filter(|id| !id.trim().is_empty()) {
        let mut offers_options = CommerceOffersOptions::new().product_id(id.clone());
        let mut details_options = CommerceDetailsOptions::new().product_id(id);
        if let Some(sku_id) = product.sku_id {
            offers_options = offers_options.sku_id(sku_id.clone());
            details_options = details_options.sku_id(sku_id);
        }
        if let Some(offer_id) = product.offers.unwrap_or_default().into_iter().next().and_then(|o| o.id) {
            offers_options = offers_options.offer_id(offer_id);
        }
        let offers = client.commerce().fetch_offers(offers_options).await?;
        let details = client.commerce().fetch_details(details_options).await?;
        println!("{:?} {:?}", offers.offers, details.products);
    }
}

fetch_offers requires at least one of product_id, sku_id, or offer_id. fetch_details requires a non-whitespace product_id or sku_id and returns zero or one product, not a batch. Both options builders accept language, region, and timeout; offers also accept location. Search identifiers and collections are optional.

CommerceResponse response = client.commerce.search("wireless headphones",
        CommerceSearchOptions.builder().maxResults(5).language("en").region("US").build());
if (response.getProducts() != null) {
    for (var product : response.getProducts()) {
        if (product.getId() != null && !product.getId().isBlank()) {
            String offerId = product.getOffers() != null && !product.getOffers().isEmpty()
                    ? product.getOffers().get(0).getId() : null;
            CommerceOffersResponse offers = client.commerce.fetchOffers(
                    CommerceOffersOptions.builder().productId(product.getId())
                            .skuId(product.getSkuId()).offerId(offerId).build());
            CommerceProductDetailsResponse details = client.commerce.fetchDetails(
                    CommerceDetailsOptions.builder().productId(product.getId())
                            .skuId(product.getSkuId()).build());
            System.out.println(offers.getOffers());
            System.out.println(details.getProducts());
        }
    }
}

fetchOffers requires at least one of productId, skuId, or offerId. fetchDetails requires a non-whitespace productId or skuId and returns zero or one product, not a batch. Both options builders accept language, region, and timeout; offers also accept location. Search identifiers and collections are optional.

CommerceResponse response = await client.Commerce.SearchAsync("wireless headphones",
    request => request.MaxResults = 5);
foreach (var product in response.Products ?? [])
{
    if (!string.IsNullOrWhiteSpace(product.Id))
    {
        var offers = await client.Commerce.FetchOffersAsync(productId: product.Id,
            skuId: product.SkuId, offerId: product.Offers?.FirstOrDefault()?.Id);
        var details = await client.Commerce.FetchDetailsAsync(productId: product.Id,
            skuId: product.SkuId);
        Console.WriteLine($"{offers.Offers?.Count} offers, {details.Products?.Count} products");
    }
}

FetchOffers and FetchOffersAsync require at least one of productId, skuId, or offerId. FetchDetails and FetchDetailsAsync require a non-whitespace productId or skuId and return zero or one product, not a batch. Both accept a configure callback for Language and Region, plus timeout and cancellation parameters; offers also support Location. Search identifiers and collections are optional.

Scopes

Web Search and News accept the name of a scope you created to filter results using that scope's inclusion and exclusion rules. Replace your-scope-name with your scope name. For setup and behavior, see Filter results with Scopes.

response = client.web.search(
    "Microsoft cloud services",
    scope_name="your-scope-name",
)
const response = await client.web.search('Microsoft cloud services', {
  scopeName: 'your-scope-name',
});
use webiq::WebSearchOptions;

let response = client.web().search("Microsoft cloud services",
    WebSearchOptions::new().scope_name("your-scope-name")).await?;
WebResponse response = client.web.search("Microsoft cloud services",
        WebSearchOptions.builder().scopeName("your-scope-name").build());
WebResponse response = await client.Web.SearchAsync("Microsoft cloud services",
    request => request.ScopeName = "your-scope-name");

Async support

Issue independent requests concurrently when your application needs multiple result types.

Use WebIQAsyncClient with asyncio:

import asyncio
import os
from webiq import WebIQAsyncClient

async def main():
    async with WebIQAsyncClient(api_key=os.environ["WEBIQ_API_KEY"]) as client:
        web, news = await asyncio.gather(
            client.web.search("Microsoft Web IQ"),
            client.news.search("technology"),
        )
        print(web.webResults, news.newsResults)

asyncio.run(main())
const [web, news] = await Promise.all([
  client.web.search('Microsoft Web IQ'),
  client.news.search('technology'),
]);
console.log(web.webResults, news.newsResults);
let web_resource = client.web();
let news_resource = client.news();
let (web, news) = tokio::try_join!(
    web_resource.search("Microsoft Web IQ", Default::default()),
    news_resource.search("technology", Default::default()),
)?;
println!("{:?} {:?}", web.web_results, news.news_results);

Use WebIQAsyncClient; its resource methods return CompletableFuture:

import com.microsoft.webiq.WebIQAsyncClient;
import com.microsoft.webiq.models.NewsResponse;
import com.microsoft.webiq.models.WebResponse;
import java.util.concurrent.CompletableFuture;

try (WebIQAsyncClient client = WebIQAsyncClient.withApiKey(System.getenv("WEBIQ_API_KEY"))) {
    CompletableFuture<WebResponse> web = client.web.search("Microsoft Web IQ");
    CompletableFuture<NewsResponse> news = client.news.search("technology");
    CompletableFuture.allOf(web, news).join();
    System.out.println(web.join().getWebResults());
    System.out.println(news.join().getNewsResults());
}
var webTask = client.Web.SearchAsync("Microsoft Web IQ");
var newsTask = client.News.SearchAsync("technology");
await Task.WhenAll(webTask, newsTask);
Console.WriteLine((await webTask).WebResults?.Count);
Console.WriteLine((await newsTask).NewsResults?.Count);

Configuration

Timeouts and retries

Set a client-level timeout, then override it per request when necessary. Timeouts apply per attempt, not to the total time spent retrying.

By default, the SDKs retry transient network failures and HTTP 408, 500, 502, 520, 523, and 524 up to twice, with exponential backoff and jitter. A valid retryAfter value in the response body takes precedence over generated backoff. HTTP 429 and 430 are never retried automatically: inspect the error's retry guidance and apply your own backoff. Client-side timeouts aren't retried.

import os
from webiq import WebIQClient, RetryPolicy

with WebIQClient(
    api_key=os.environ["WEBIQ_API_KEY"],
    timeout=10.0,
    retry=RetryPolicy(max_retries=2, base_delay_s=0.25, max_delay_s=4.0),
) as client:
    response = client.web.search("Microsoft Web IQ", timeout=30.0)

Timeouts are in seconds. The client default is 10 seconds.

import { WebIQClient, RetryPolicy } from '@microsoft/webiq';

const client = new WebIQClient({
  apiKey: process.env.WEBIQ_API_KEY,
  timeout: 10_000,
  retry: new RetryPolicy({
    maxRetries: 2,
    baseDelaySeconds: 0.25,
    maxDelaySeconds: 4.0,
  }),
});
try {
  const response = await client.web.search('Microsoft Web IQ', { timeout: 30_000 });
  console.log(response.webResults);
} finally {
  await client.close();
}

Timeouts are in milliseconds. The client default is 10,000 milliseconds.

use std::time::Duration;
use webiq::{RetryPolicy, WebIqClient, WebSearchOptions};

let client = WebIqClient::builder()
    .api_key(std::env::var("WEBIQ_API_KEY")?)
    .timeout(Duration::from_secs(10))
    .retry(RetryPolicy::new().max_retries(2))
    .build()?;
let response = client.web().search(
    "Microsoft Web IQ",
    WebSearchOptions::new().timeout(Duration::from_secs(30)),
).await?;

The client default is 10 seconds.

import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.WebIQClientOptions;
import com.microsoft.webiq.resources.WebSearchOptions;
import com.microsoft.webiq.retry.RetryPolicy;
import java.time.Duration;

WebIQClientOptions options = WebIQClientOptions.builder()
        .apiKey(System.getenv("WEBIQ_API_KEY"))
        .timeout(Duration.ofSeconds(10))
        .retry(RetryPolicy.builder().maxRetries(2).build())
        .build();
try (WebIQClient client = new WebIQClient(options)) {
    client.web.search("Microsoft Web IQ",
            WebSearchOptions.builder().timeout(Duration.ofSeconds(30)).build());
}

The client default is 10 seconds.

using Microsoft.WebIQ;

using var client = new WebIQClient(new WebIQClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("WEBIQ_API_KEY"),
    Timeout = TimeSpan.FromSeconds(30),
    Retry = new RetryPolicy { MaxRetries = 2 }
});
var response = await client.Web.SearchAsync("Microsoft Web IQ",
    timeout: TimeSpan.FromSeconds(10));

The client default is 30 seconds.

Custom HTTP clients

Use a custom HTTP client for proxy, TLS, or connection-pooling configuration. Don't disable certificate verification.

Pass http_client and close the caller-owned HTTP client yourself. Use httpx.AsyncClient with WebIQAsyncClient for async requests.

import os
import httpx
from webiq import WebIQClient

with httpx.Client(
    base_url="https://api.microsoft.ai/v3",
    proxy="http://proxy:8080",
) as http_client:
    with WebIQClient(
        api_key=os.environ["WEBIQ_API_KEY"],
        http_client=http_client,
    ) as client:
        response = client.web.search("Microsoft Web IQ")

Install undici for proxy support:

npm install undici

Pass a custom fetchFn. Preserve init so the SDK's headers, body, and internal AbortSignal are forwarded.

import { ProxyAgent } from 'undici';
import { WebIQClient } from '@microsoft/webiq';

const proxyAgent = new ProxyAgent('http://proxy:8080');
const client = new WebIQClient({
  apiKey: process.env.WEBIQ_API_KEY,
  fetchFn: (url, init) => {
    const options = { ...init, dispatcher: proxyAgent };
    return fetch(url, options);
  },
});
try {
  const response = await client.web.search('Microsoft Web IQ');
  console.log(response.webResults);
} finally {
  await client.close();
  await proxyAgent.close();
}

Pass a configured reqwest::Client to WebIqClient::builder().http_client(...). If your application constructs this client directly, add reqwest as a direct dependency with a version compatible with the SDK.

Pass a configured java.net.http.HttpClient through WebIQClientOptions.builder().httpClient(...). The SDK doesn't close caller-owned clients; manage their lifetime in your application.

Pass an HttpClient through WebIQClientOptions.HttpClient. The SDK doesn't dispose a caller-owned HTTP client; manage its lifetime in your application.

Cancellation

For async requests, use asyncio task cancellation or asyncio.timeout to impose a wall-clock budget that includes retry waits. A per-request SDK timeout limits each HTTP attempt.

Every resource method accepts an AbortSignal through options.signal. Aborting cancels the in-flight request and retry waits; the signal's reason is rethrown unchanged.

const response = await client.web.search('Microsoft Web IQ', {
  signal: AbortSignal.timeout(5_000),
});

To combine an inbound request's signal with a wall-clock limit, use AbortSignal.any([request.signal, AbortSignal.timeout(5_000)]).

Cancel or drop the request future to interrupt the operation, including retry waits. For an application deadline, use the Tokio time utilities and enable Tokio's time feature.

Use a per-call timeout to bound each HTTP attempt. SDK 1.2.1 doesn't expose a request cancellation token. Cancelling the returned CompletableFuture doesn't guarantee cancellation of the underlying HTTP request or retry waits.

Pass a CancellationToken to cancel the operation, including retry waits:

using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var response = await client.Web.SearchAsync("Microsoft Web IQ",
    cancellationToken: cancellation.Token);

Telemetry

Attach a telemetry callback to log each request attempt, status, and elapsed time. Telemetry also includes request and trace IDs, retry guidance, and error information. Avoid logging credentials or sensitive query content.

import os
from webiq import WebIQClient, TelemetryEvent

def on_request(event: TelemetryEvent):
    print(f"{event.method} {event.path}: {event.status_code} ({event.elapsed_ms}ms)")

with WebIQClient(
    api_key=os.environ["WEBIQ_API_KEY"],
    telemetry_hook=on_request,
) as client:
    response = client.web.search("Microsoft Web IQ")

Telemetry fields use snake_case, including attempt, status_code, request_id, trace_id, retry_after, elapsed_ms, error, and error_body.

import { WebIQClient } from '@microsoft/webiq';

const client = new WebIQClient({
  apiKey: process.env.WEBIQ_API_KEY,
  telemetryHook: event => {
    console.log(`${event.method} ${event.path}: ${event.statusCode} (${event.elapsedMs}ms)`);
  },
});
try {
  await client.web.search('Microsoft Web IQ');
} finally {
  await client.close();
}

Telemetry fields use camelCase, including attempt, statusCode, requestId, traceId, retryAfter, elapsedMs, error, and errorBody.

use std::sync::Arc;
use webiq::{TelemetryEvent, WebIqClient};

let client = WebIqClient::builder()
    .api_key(std::env::var("WEBIQ_API_KEY")?)
    .telemetry_hook(Arc::new(|event: &TelemetryEvent| {
        println!("{} {}: {:?} ({:?}ms)",
            event.method, event.path, event.status_code, event.elapsed_ms);
    }))
    .build()?;
client.web().search("Microsoft Web IQ", Default::default()).await?;
import com.microsoft.webiq.WebIQClient;
import com.microsoft.webiq.WebIQClientOptions;

WebIQClientOptions options = WebIQClientOptions.builder()
        .apiKey(System.getenv("WEBIQ_API_KEY"))
        .telemetryHook(event -> System.out.printf("%s %s: %s (%sms)%n",
                event.getMethod(), event.getPath(),
                event.getStatusCode(), event.getElapsedMs()))
        .build();
try (WebIQClient client = new WebIQClient(options)) {
    client.web.search("Microsoft Web IQ");
}
using Microsoft.WebIQ;

using var client = new WebIQClient(new WebIQClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("WEBIQ_API_KEY"),
    TelemetryHook = telemetry => Console.WriteLine(
        $"{telemetry.Method} {telemetry.Path}: " +
        $"{telemetry.StatusCode} ({telemetry.ElapsedMilliseconds}ms)")
});
await client.Web.SearchAsync("Microsoft Web IQ");

Error handling

Handle authentication, permission, and rate-limit errors separately from transient failures. HTTP 429 and 430 surface immediately, without SDK retries. Use the returned retry guidance to decide when to try again.

All SDK exceptions inherit from WebIQError. HTTP errors inherit from APIStatusError, including AuthenticationError, PermissionDeniedError, and RateLimitError. Network failures and timeouts raise APIConnectionError. Python request validation can raise pydantic.ValidationError before sending a request.

from webiq import (
    APIConnectionError, APIStatusError, AuthenticationError,
    PermissionDeniedError, RateLimitError, WebIQError,
)

try:
    response = client.web.search("Microsoft Web IQ")
except AuthenticationError as error:
    print(f"Authentication failed: {error}")
except PermissionDeniedError as error:
    print(f"Forbidden: {error}")
except RateLimitError as error:
    print(f"Rate limited; retry after: {error.retry_after}")
except APIStatusError as error:
    print(f"HTTP {error.status_code}: {error}")
    if isinstance(error.body, dict):
        print(error.body.get("errorCode"), error.body.get("traceId"))
except APIConnectionError as error:
    print(f"Connection failed: {error}")
except WebIQError as error:
    print(f"SDK error: {error}")

Inspect APIStatusError.body for the full server error response, including errorCategory, errorCode, technicalDetails, retryAfter, and traceId.

All SDK errors inherit from WebIQError. HTTP errors inherit from APIStatusError, including AuthenticationError, PermissionDeniedError, and RateLimitError. Network failures and timeouts raise APIConnectionError.

import {
  APIConnectionError, APIStatusError, AuthenticationError,
  PermissionDeniedError, RateLimitError,
} from '@microsoft/webiq';

try {
  await client.web.search('Microsoft Web IQ');
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
  } else if (error instanceof PermissionDeniedError) {
    console.error('Forbidden:', error.message);
  } else if (error instanceof RateLimitError) {
    console.error('Rate limited; retry after:', error.retryAfter);
  } else if (error instanceof APIStatusError) {
    console.error(`HTTP ${error.statusCode}:`, error.message);
    if (error.body && typeof error.body === 'object') {
      const body = error.body as Record<string, unknown>;
      console.error(body.errorCode, body.traceId);
    }
  } else if (error instanceof APIConnectionError) {
    console.error('Connection failed:', error.message);
  } else {
    throw error;
  }
}

Inspect APIStatusError.body for the full server error response, including errorCategory, errorCode, technicalDetails, retryAfter, and traceId.

Calls return Result<T, WebIqError>. Match on API errors or inspect the error accessors for structured diagnostics:

use webiq::WebIqError;

match client.web().search("Microsoft Web IQ", Default::default()).await {
    Ok(response) => println!("{:?}", response.web_results),
    Err(WebIqError::Authentication(details)) => eprintln!("401: {}", details.message),
    Err(WebIqError::PermissionDenied(details)) => eprintln!("403: {}", details.message),
    Err(WebIqError::RateLimit(details)) => {
        eprintln!("Rate limited; retry after: {:?}", details.retry_after());
    }
    Err(error) => {
        eprintln!("{error}");
        eprintln!("Code: {:?}, trace: {:?}", error.error_code(), error.trace_id());
    }
}

API errors expose status_code(), error_category(), error_code(), user_message(), technical_details(), retry_after(), request_id(), trace_id(), and body(). Missing optional fields return None.

All SDK exceptions inherit from WebIQException. HTTP status exceptions inherit from APIStatusException. Network failures and timeouts raise APIConnectionException.

import com.microsoft.webiq.errors.*;

try {
    client.web.search("Microsoft Web IQ");
} catch (AuthenticationException error) {
    System.err.println("Authentication failed: " + error.getMessage());
} catch (PermissionDeniedException error) {
    System.err.println("Forbidden: " + error.getMessage());
} catch (RateLimitException error) {
    System.err.println("Rate limited; retry after: " + error.getRetryAfter());
} catch (APIStatusException error) {
    System.err.println("HTTP " + error.getStatusCode() + ": " + error.getMessage());
    System.err.println("Code: " + error.getErrorCode() + ", trace: " + error.getTraceId());
} catch (APIConnectionException error) {
    System.err.println("Connection failed: " + error.getMessage());
}

Status exceptions expose getStatusCode(), getErrorCategory(), getErrorCode(), getUserMessage(), getTechnicalDetails(), getRetryAfter(), getRequestId(), getTraceId(), and getBody(). Missing optional fields return null.

HTTP status exceptions inherit from ApiStatusException. Network failures and timeouts raise ApiConnectionException.

using Microsoft.WebIQ;

try
{
    await client.Web.SearchAsync("Microsoft Web IQ");
}
catch (AuthenticationException error)
{
    Console.Error.WriteLine($"Authentication failed: {error.Message}");
}
catch (PermissionDeniedException error)
{
    Console.Error.WriteLine($"Forbidden: {error.Message}");
}
catch (RateLimitException error)
{
    Console.Error.WriteLine($"Rate limited; retry after: {error.RetryAfter}");
}
catch (ApiStatusException error)
{
    Console.Error.WriteLine($"HTTP {error.StatusCode}: {error.Message}");
    Console.Error.WriteLine($"Code: {error.ErrorCode}, trace: {error.TraceId}");
}
catch (ApiConnectionException error)
{
    Console.Error.WriteLine($"Connection failed: {error.Message}");
}

Status exceptions expose ErrorCategory, ErrorCode, UserMessage, TechnicalDetails, RetryAfter, RequestId, TraceId, and Body. Missing optional fields are null.

Browse can return HTTP 202 Accepted when a crawl is pending. This is a normal response, not an exception, and the SDK doesn't poll automatically. Use the response URL and UTC retryAfter timestamp to retry later. Partial HTTP 200 responses can include a truncationReason, such as "encumbrance".

Debugging and next steps

  • Include traceId when contacting support. Rust uses trace_id, Java uses getTraceId(), and .NET uses TraceId.
  • Use telemetry to correlate attempts, response codes, and elapsed time.
  • Inspect the structured error body before treating an error as retryable. See Error handling.
  • Add click and citation instrumentation when displaying or citing search results.