Skip to content

About

Zig client library for SerpApi.com

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

SerpApi Zig Library

serpapi-zig

Integrate search data into your AI workflow, RAG / fine-tuning, or Zig application using this wrapper for SerpApi.

SerpApi supports Google, Google Maps, Google Shopping, Baidu, Yandex, Yahoo, eBay, App Stores, and more.

Query a vast range of data at scale, including web search results, flight schedules, stock market data, news headlines, and more.

Features

  • persistent → Keep socket connection open to save on SSL handshake / reconnection (3-4x faster on repeated searches).
  • md → Markdown output, token-efficient and ready to feed to LLMs and AI agents. Search API — Markdown
  • uploadImage → upload a local image, then search it with Google Lens. Google Lens with File Upload
  • zero dependency → only the Zig standard library (std.http, std.json), nothing else to fetch.
  • cross platform → Linux, macOS, and Windows.
  • extensive documentation → easy to follow.

Installation

Zig 0.16.0 or higher is required.

Add the dependency to your project:

zig fetch --save 'git+https://github.com/serpapi/serpapi-zig#v1.1.0'

Then wire the module in your build.zig:

const serpapi = b.dependency("serpapi", .{
    .target = target,
    .optimize = optimize,
});
exe.root_module.addImport("serpapi", serpapi.module("serpapi"));

Versioning

Zig has no central package registry, so there is no version range to resolve: a dependency is a URL plus a content hash. Releases are published as git tags named vMAJOR.MINOR.PATCH, following semantic versioning, and the fragment after # selects which one you get:

# a released version (recommended)
zig fetch --save 'git+https://github.com/serpapi/serpapi-zig#v1.1.0'

# the development branch — moves, may break
zig fetch --save 'git+https://github.com/serpapi/serpapi-zig'

# an exact commit; the SHA must be the full 40 characters
zig fetch --save 'git+https://github.com/serpapi/serpapi-zig#4451c6c4b5a2dc68d7249a2a97f032470ab2070d'

Whichever form you use, --save resolves it at fetch time and records the result as an immutable pin, so a tag that is later moved cannot change your build. Pinning v1.1.0, for instance, produced:

.dependencies = .{
    .serpapi = .{
        .url = "git+https://github.com/serpapi/serpapi-zig?ref=v1.1.0#2cdc4e1c8af19139d1c92678c827238712ed8e70",
        .hash = "serpapi-1.1.0-PYmxE5oUAQAIGYd_5Z3eHW6qKfMiekEOF0zNe32ZVamE",
    },
},

The hash — not the URL — is what actually identifies the package, so always upgrade by re-running zig fetch --save with the new tag, which rewrites the URL, the resolved commit and the hash together. Editing the version in the URL by hand does not upgrade anything: the old hash still resolves to the old package, and the build quietly keeps using it.

A release tarball works too, and produces the same hash as its tag:

zig fetch --save 'https://github.com/serpapi/serpapi-zig/archive/refs/tags/v1.1.0.tar.gz'

Released versions are listed on the releases page; changes are recorded in CHANGELOG.md. The version number lives in one place, build.zig.zon: build.zig forwards it to the library as serpapi.version, which is what the client reports to serpapi.com in its User-Agent header, and rake release reads it to name the tag.

Simple Usage

Query parameters are plain anonymous structs — field names are parameter names; values may be strings, integers, floats, or booleans.

const std = @import("std");
const serpapi = @import("serpapi");

pub fn main(init: std.process.Init) !void {
    const api_key = init.environ_map.get("SERPAPI_KEY") orelse
        return error.MissingSerpApiKey;

    var client = try serpapi.Client.init(init.gpa, .{
        .engine = "google",
        .api_key = api_key,
    });
    defer client.deinit();

    var results = try client.search(.{ .q = "coffee" });
    defer results.deinit();

    std.debug.print("{f}\n", .{std.json.fmt(results.value, .{ .whitespace = .indent_2 })});
}

This example runs a search for "coffee" on Google. It returns the results as a std.json.Parsed(std.json.Value) tree. See the playground to generate your own query.

A complete, runnable version of this program lives in oobt/demo.zig — it prints the title and link of every organic result. Run it against the live API with zig build oobt.

For a typed-result example against a different engine, see demo/flight_tracker — a standalone Zig project (its own build.zig/build.zig.zon, not built through this repo's build.zig) that tracks a round trip from Austin to Paris on the Google Flights API. It doubles as a worked example of wiring serpapi into a downstream project's build:

cd demo/flight_tracker
SERPAPI_KEY=<secret_serpapi_key> zig build run

The SerpApi key can be obtained from serpapi.com/signup.

Environment variables are a secure, safe, and easy way to manage secrets: set export SERPAPI_KEY=<secret_serpapi_key> in your shell, and the example above reads it with init.environ_map.get("SERPAPI_KEY") — never hardcode the key in source code.

As everywhere in Zig, the caller owns returned resources: results from JSON APIs are released with deinit(), raw HTML and Markdown slices with allocator.free(). The remaining examples omit the defer cleanup lines for brevity.

Client options

The serpapi.Client.init constructor takes an allocator and an anonymous struct. timeout and persistent configure the client; every other field becomes a default query parameter applied to every request:

var client = try serpapi.Client.init(allocator, .{
    .api_key = api_key,  // read from the SERPAPI_KEY environment variable
    .engine = "google",  // default search engine
    .gl = "us",          // any other field: default query parameter
    .timeout = 30,       // HTTP timeout in seconds [default: 120]
    .persistent = true,  // keep the connection open [default: true]
});

All fields are optional. Parameters passed to a method call override the defaults provided to the constructor. Call client.deinit() when the client is no longer needed; it closes the connection and frees all resources.

The client reports its configuration back:

client.engine()     // ?[]const u8: default engine, "google" here
client.apiKey()     // ?[]const u8: the API key given to the constructor
serpapi.version     // the library version, "1.2.0"
serpapi.user_agent  // "serpapi-zig/1.2.0 zig/0.16.0 (macos; aarch64)"

Every request sends serpapi.user_agent as its User-Agent header, so SerpApi can see which library versions, Zig versions and platforms are in use and focus testing on them. It names the library version, the Zig compiler that built the client, and the build target's OS and CPU architecture; it carries no search parameters and nothing about your account. The client adds no source query parameter: a source you pass yourself, to the constructor or a call, is sent as given, with searches and image uploads alike.

Printing the client masks the API key, as serpapi-ruby's inspect does — the first and last four characters of a key longer than eight, **** otherwise:

std.debug.print("{f}\n", .{client});
// serpapi.Client{ .engine = "google", .timeout = 30, .persistent = true, .api_key = "abcd****wxyz" }

The key is stored apart from the other defaults, so dumping the client's fields with {any} does not reveal it either.

timeout bounds the whole request — connecting, TLS handshake, and reading the response — and a request that overruns it fails with error.Timeout (details in client.errorMessage()), dropping the stalled connection so the next request starts fresh. Set it to 0 to wait indefinitely. The request runs on a worker thread from the client's own std.Io.Threaded pool so it can be interrupted; in a single-threaded build the limit is not enforced and the request simply runs to completion.

APIs

Search API

var results = try client.search(.{
    .q = "coffee",
    .location = "Austin, TX, Texas, United States",
});
const organic = results.value.object.get("organic_results").?.array;

doc: serpapi.com/search-api

Search API — typed results

Following std.json.parseFromSlice, every JSON method has an As variant that decodes into your own struct instead of a dynamic tree. Unknown JSON fields are ignored, so declare only what you need:

const Answer = struct {
    search_metadata: struct { id: []const u8, status: []const u8 },
};

var results = try client.searchAs(Answer, .{ .q = "coffee" });
std.debug.print("status: {s}\n", .{results.value.search_metadata.status});

Also available: locationAs, searchArchiveAs, accountAs, uploadImageAs, and uploadImageBytesAs.

Search API — raw HTML

html returns the raw HTML page from the search engine. It is useful for training AI models, RAG, debugging, or when you need to parse the HTML yourself.

const page = try client.html(.{ .q = "coffee" });

doc: serpapi.com/search-api

Search API — Markdown

md returns the search results as Markdown: the same page the search engine served, rendered by the backend into a compact, token-efficient document. It is useful for feeding search results directly into LLMs, AI agents, and RAG pipelines, where raw HTML would waste most of the context window.

const page = try client.md(.{ .q = "coffee" });

This code prints the search results as Markdown — headings, tables, and links, with no HTML markup to strip. :)

doc: serpapi.com/search-api

Location API

var locations = try client.location(.{ .q = "Austin", .limit = 3 });

doc: serpapi.com/locations-api

Search Archive API

Retrieve a past search by id — the id comes from results.value.object.get("search_metadata").?.object.get("id").

var archived = try client.searchArchive(search_id);

// or as raw HTML:
const page = try client.searchArchiveHtml(search_id);

// or as Markdown:
const markdown = try client.searchArchiveMd(search_id);

Retrieving a past search from the archive is free of charge.

doc: serpapi.com/search-archive-api

Account API

var account = try client.account();

The api_key provided to the constructor is used; override it with client.accountAs(std.json.Value, .{ .api_key = "other key" }).

doc: serpapi.com/account-api

Google Lens with File Upload

Upload an image with the Image API, then use its image ID in a Google Lens search. Uploaded image IDs expire after 10 minutes.

var upload = try client.uploadImage("./image.jpg", .{});
const image_id = upload.value.object.get("image_id").?.string;

var results = try client.search(.{ .engine = "google_lens", .image_id = image_id });
const visual_matches = results.value.object.get("visual_matches");

The image already in memory? Pass its bytes and a file name instead: client.uploadImageBytes(bytes, "image.jpg", .{}). The content type is detected from the image signature (jpg, jpeg, png, webp), falling back to the file name's extension.

The image is sent as multipart/form-data in a POST to https://serpapi.com/image, with the api_key in the form body rather than the URL; override it per call with .{ .api_key = "other key" }. Search defaults from the constructor (engine, output, ...) are not sent. Images larger than 500 KiB (serpapi.image_max_size) fail with error.ImageTooLarge before anything is read or sent, and file errors such as error.FileNotFound are returned as-is.

doc: serpapi.com/image-api · Google Lens image upload

Error handling

Methods return a Zig error union. When serpapi.com reports a failure — an {"error": "..."} payload, whatever the HTTP status or output format — the call returns error.SerpApiError and the backend message is available from client.errorMessage():

const results = client.search(.{}) catch |err| switch (err) {
    error.SerpApiError => {
        std.debug.print("serpapi.com says: {s}\n", .{client.errorMessage().?});
        return err;
    },
    else => return err,
};

Other errors, all with details in client.errorMessage(): error.HttpRequestFailed (non-200 status without an error payload — the message is the raw body, or the status name when the body is empty), error.JsonParseError (response was not valid JSON, or did not fit the requested type), error.Timeout (the request overran the client's timeout), error.ImageTooLarge (an upload over serpapi.image_max_size, never sent), plus any network / TLS / allocation / file errors propagated from the standard library. The client errors are grouped in serpapi.Error.

client.lastError() returns the details of the last failure, mirroring serpapi-ruby's SerpApiError: the message (same as errorMessage()), the HTTP status, the request url with the api_key left out — safe to log — and the search_id when serpapi.com assigned one to the failed search. status is null when no response arrived (error.Timeout).

Both describe the most recent request only: every request clears them first, so they are null after a success, and after a transport error (DNS, connection, TLS) — such errors carry no details beyond the Zig error itself.

var archived = client.searchArchive(search_id) catch |err| {
    if (client.lastError()) |info| {
        // SerpApiError: HTTP 404 https://serpapi.com/searches/<id>.json: Search not found.
        std.debug.print("{t}: HTTP {?d} {?s}: {s}\n", .{
            err, if (info.status) |s| @intFromEnum(s) else null, info.url, info.message,
        });
    }
    return err;
};

A Client is not thread-safe — errorMessage() and lastError() report the last failure seen by that instance — so use one client per thread.

Search asynchronous

Pass async = true to submit a search without blocking on the result, then fetch it later from the Search Archive API:

var submitted = try client.search(.{ .q = "coffee", .async = true });
const search_id = submitted.value.object.get("search_metadata").?.object.get("id").?.string;

// ... later: poll until search_metadata.status is "Success"
var results = try client.searchArchive(search_id);

Search at scale

With persistent = true (the default), the client keeps the TLS connection to serpapi.com open between requests, skipping the TCP + TLS handshake on every search after the first. On repeated searches this is 3-4x faster than reconnecting (10 sequential searches: ~0.5-1.0s persistent vs ~2.2s not; measure it yourself with zig build bench):

for (queries) |query| {
    var results = try client.search(.{ .q = query });
    defer results.deinit();
    // process results...
}

Developer workflow

zig build test    # run unit tests (no network)
zig build itest   # run integration tests against serpapi.com (needs SERPAPI_KEY)
zig build oobt    # out-of-box testing: build + run the demo app (needs SERPAPI_KEY)
zig build bench   # benchmark persistent vs non-persistent connections (needs SERPAPI_KEY)
zig build cov     # measure code coverage (needs kcov + SERPAPI_KEY)
zig build lint    # check formatting (zig fmt --check), demos included
zig build doc     # generate API documentation under zig-out/docs

The two demos are standalone projects; build them from the repo root with --build-file (or rake demos):

zig build --build-file demo/flight_tracker/build.zig
zig build test --build-file demo/wasm/build.zig

A Rakefile wraps the same steps for anyone used to the other SerpApi libraries — rake --tasks lists them all.

Cross compilation

Zig cross-compiles without a toolchain to install, so the library builds for every architecture listed in the cross-compilation guide straight from a laptop:

rake cross           # all six architectures
rake cross:aarch64   # or one at a time
architecture zig target verified
x86_64 x86_64-linux ELF 64-bit x86-64
arm arm-linux ELF 32-bit ARM EABI5
aarch64 aarch64-linux ELF 64-bit ARM aarch64
i386 x86-linux ELF 32-bit Intel 80386
riscv64 riscv64-linux ELF 64-bit UCB RISC-V
wasm32 wasm32-wasi WebAssembly module

Note that Zig names the 32-bit x86 architecture x86, not i386.

To run those foreign binaries — and the test suite — on a macOS host, install QEMU and pass -fqemu:

rake install:qemu    # brew install qemu
rake cross:test      # zig build test -Dtarget=<triple> -fqemu

Browser wasm demo

demo/wasm runs part of the client as WebAssembly inside a web page, with a small native server handling what a browser cannot. It is a standalone Zig project (its own build.zig/build.zig.zon, not built through this repo's build.zig) and doubles as a worked example of wiring serpapi into a downstream project's build:

cd demo/wasm
export SERPAPI_KEY=<secret_serpapi_key>
zig build serve
# open http://127.0.0.1:8080

See demo/wasm/README.md for how it fits together, the JS/wasm interface, and why the whole serpapi.Client cannot run in a browser.

Code coverage

Coverage is measured with kcov, which Zig binaries support out of the box — no instrumentation flags required.

brew install kcov            # macOS; on Debian/Ubuntu: sudo apt-get install kcov
export SERPAPI_KEY=<secret_serpapi_key>
zig build cov
open zig-out/coverage/merged/kcov-merged/index.html

Current state: 95.07% of lines covered (867 of 912) without an API key, since the tests covering html, md, searchArchive, and account skip themselves rather than fail. With SERPAPI_KEY set — as in CI, which publishes the figure to every job summary and fails below 90% — those paths execute too and coverage rises accordingly. CI measures on Linux arm64 in a Debian trixie container; kcov needs --security-opt seccomp=unconfined to run inside Docker.

The lines that remain uncovered either way are errdefer branches that only execute if the operating system refuses an allocation midway through a request.

One caveat specific to Zig: a coverage run over the unit tests alone reports a flattering ~97% while actually exercising far less, because Zig never generates code for a generic (anytype) function that no test instantiates — so every HTTP method disappears from the denominator instead of counting as uncovered. zig build cov therefore measures the unit and integration binaries and merges the two reports.

Changelog

Full details in CHANGELOG.md.

  • [2026-11-30] 1.2.0 Image API, error details, User-Agent usage reporting and a safer client dump
    • Added uploadImage() and uploadImageBytes() (and typed uploadImageAs() / uploadImageBytesAs()) for the Image API, returning the image_id to use with engines such as google_lens. The api_key goes in the form body, never in the URL, and images over 500 KiB fail fast with error.ImageTooLarge
    • Added lastError(), returning a serpapi.ErrorInfo with the message, HTTP status, request URL (without the api_key) and search_id of the last failure
    • Printing a client with {f} masks the API key (abcd****wxyz)
    • errorMessage() and lastError() describe the most recent request only: a success or a transport error clears the previous failure
    • Breaking: the API key moved out of Client.params (use apiKey()), Client.last_error is now ?serpapi.ErrorInfo, and serpapi.Error gains ImageTooLarge. Pin v1.1.0 to keep the old API
    • rake release runs lint, tests, integration tests and oobt, and only from a clean master
    • Every request identifies the library, the Zig version and the platform in its User-Agent header (serpapi.user_agent, e.g. serpapi-zig/1.2.0 zig/0.16.0 (macos; aarch64)) instead of the source query parameter, as serpapi-ruby does
    • A source passed to the constructor is sent once, as given; it was previously sent alongside the library's own
  • [2026-09-23] 1.1.0 Markdown output, timeouts and connection reuse
    • Added md() and searchArchiveMd() for output=md results optimized for LLMs and AI agents
    • serpapi.Error is exported from the module root, and serpapi.version comes from build.zig.zon
    • Fixed persistent connections, which were never actually reused (3-4x faster for repeated searches)
    • Fixed the timeout option, which was never applied; a stalled request now returns error.Timeout
    • One error rule for every decoder: an {"error": ...} payload is SerpApiError whatever the HTTP status
    • Fixed a double free in html() on non-200 responses, and Search Archive ids are percent-encoded
    • Added the browser wasm demo and the flight tracker demo
  • [2026-08-13] 1.0.0 Initial release, ported from serpapi-ruby
    • search(), html(), location(), searchArchive(), searchArchiveHtml() and account()
    • Persistent HTTP connections on by default
    • Zero dependency: Zig standard library only

License

MIT License — see LICENSE.

About

Zig client library for SerpApi.com

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages