Back to Blog

Use SerpBase API With Python, Node, Go

Learn how to call the SerpBase API with Python, Node.js, and Go, including authentication, request examples, error handling, and integration tips quickly.

April 8, 2026
By SerpBase Teamserpbase apipythonnodejsgotutorial

Integration Examples

SerpBase uses a simple REST API -- a single POST endpoint that accepts JSON and returns JSON. Here are ready-to-use examples in the three most common backend languages.


Authentication

All requests require your API key in the X-API-Key header. Get yours at serpbase.dev.


Python

import requests

def search(query: str, country: str = "us", lang: str = "en") -> dict:
    response = requests.post(
        "https://api.serpbase.dev/google/search",
        headers={
            "X-API-Key": "YOUR_API_KEY",
            "Content-Type": "application/json",
        },
        json={"q": query, "gl": country, "hl": lang, "page": 1},
        timeout=15,
    )
    response.raise_for_status()
    return response.json()


if __name__ == "__main__":
    data = search("open source llm")
    for result in data.get("organic", []):
        print(f"{result['position']:>2}. {result['title']}")
        print(f"    {result['link']}")

With async (aiohttp):

import aiohttp
import asyncio

async def search_async(query: str) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.post(
            "https://api.serpbase.dev/google/search",
            headers={"X-API-Key": "YOUR_API_KEY"},
            json={"q": query, "gl": "us", "hl": "en"},
        ) as resp:
            resp.raise_for_status()
            return await resp.json()

results = asyncio.run(search_async("best python frameworks"))

Node.js

const search = async (query, country = 'us', lang = 'en') => {
  const response = await fetch('https://api.serpbase.dev/google/search', {
    method: 'POST',
    headers: {
      'X-API-Key': 'YOUR_API_KEY',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ q: query, gl: country, hl: lang, page: 1 }),
  });

  if (!response.ok) {
    throw new Error(`SERP API error: ${response.status}`);
  }

  return response.json();
};

// Usage
const data = await search('javascript runtime comparison');
data.organic.forEach(({ position, title, link }) => {
  console.log(`${position}. ${title}`);
  console.log(`   ${link}`);
});

Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

type SearchRequest struct {
    Q    string `json:"q"`
    GL   string `json:"gl"`
    HL   string `json:"hl"`
    Page int    `json:"page"`
}

type OrganicResult struct {
    Position int    `json:"position"`
    Title    string `json:"title"`
    Link     string `json:"link"`
    Snippet  string `json:"snippet"`
}

type SearchResponse struct {
    Organic []OrganicResult `json:"organic"`
}

func search(apiKey, query string) ([]OrganicResult, error) {
    payload, _ := json.Marshal(SearchRequest{Q: query, GL: "us", HL: "en", Page: 1})

    req, _ := http.NewRequest("POST", "https://api.serpbase.dev/google/search", bytes.NewReader(payload))
    req.Header.Set("X-API-Key", apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var result SearchResponse
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        return nil, err
    }
    return result.Organic, nil
}

func main() {
    results, _ := search("YOUR_API_KEY", "golang web scraping")
    for _, r := range results {
        fmt.Printf("%2d. %s\n    %s\n", r.Position, r.Title, r.Link)
    }
}

Request Parameters

ParameterTypeDefaultDescription
qstringrequiredSearch query
glstringusCountry code (ISO 3166-1 alpha-2)
hlstringenLanguage code
pageinteger1Results page (1 = positions 1-10)

Error Handling

HTTP StatusMeaning
200Success
400Invalid request (check your JSON body)
401Missing or invalid API key
402Insufficient credits -- top up at serpbase.dev
429Rate limit exceeded

A successful response always contains "status": 0 in the JSON envelope.


Next Steps

Integration Checklist

Before putting a SERP API into production, make the integration boring on purpose. The fewer surprises your wrapper allows, the easier it is to debug ranking reports, AI agents, and SEO dashboards later.

ConcernImplementation note
API key storageRead from environment variables, not source code
Query defaultsSet country, language, and search type explicitly
TimeoutsFail fast enough for user-facing tools
RetriesRetry only safe transient errors
LoggingLog request ID, query, status, and cost-related metadata
CachingCache repeated searches when freshness is not required

An AI agent may need fresh results for breaking news, while a weekly SEO report can reuse cached data for stable keywords. Treat those as different jobs instead of one generic search function.

Related guides: Google Search Results JSON API, SERP API for AI agents, and SERP API pricing explained.

FAQ

Which language should I use first? Use the language your application already uses.

Should raw SERP API responses be exposed to users? For developer tools, sometimes yes. For dashboards, transform them into stable fields.