Back to Blog

How to Use the SerpBase API with Python, Node.js, and Go

Complete code examples for calling the SerpBase SERP API in Python, Node.js, and Go. Get up and running in under 5 minutes.

April 8, 2026
By SerpBase Teamtutorialpythonnodejsgodevelopers

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