SERP API 2 min read

Parse SERP API JSON in Python: Validate the Response Contract

Parse a SERP API response by validating the provider’s envelope before normalizing result rows.

(Updated: ) • 339 words

Parse a SERP API response by validating the provider’s envelope before normalizing result rows. For SearchCans, data is an object and data.organic is the organic-result array. HTTP success, application success and an empty organic result are different cases.

Normalize only a successful response shape

def organic_rows(envelope):
    if envelope.get('code') != 0:
        raise ValueError('Search business error')
    data = envelope.get('data')
    if not isinstance(data, dict):
        raise ValueError('Expected a data object')
    rows = data.get('organic', [])
    if not isinstance(rows, list):
        raise ValueError('Expected an organic array')
    return [r for r in rows if isinstance(r, dict) and isinstance(r.get('link'), str)]

fixture = {"code": 0, "data": {"organic": [{"position": 1, "link": "https://example.org/"}]}}
assert organic_rows(fixture)[0]["link"] == "https://example.org/"
assert organic_rows({"code": 0, "data": {"organic": []}}) == []

The function rejects a business error or a non-object data field. An omitted or empty organic array is allowed by this local organic parser; an application that requires another feature must validate that feature independently.

Retain the raw response for review

Case Parser action
HTTP failure Handle transport status before normalizing JSON
Nonzero business code Keep error status; do not treat as an empty SERP
Object data with no organic rows Record a valid empty observation
Malformed row Skip or quarantine it under an explicit policy
Optional feature absent Mark the feature absent, not fabricated

Keep provider adapters separate

SerpApi organic_results and SearchCans data.organic are not interchangeable envelopes. Put native field mappings inside a provider-specific adapter and test that adapter with saved fixtures. Preserve link, market, engine and observation time when the normalized output leaves the parser.

The example checks local envelope behavior. It does not validate every optional SERP feature or the behavior of an application that consumes the results. Use the request tutorial for authentication and the tracker for ranking history.

Reference documentation: www.searchcans.com — /google-search-api; serpapi.com — /search-api.

Tags:

SERP API JSON Python Google Search API API Integration AI Agents RAG
SearchCans Team

SearchCans Team

SERP API & Reader API Experts

The SearchCans engineering team builds high-performance search APIs serving developers worldwide. We share practical tutorials, best practices, and insights on SERP data, web scraping, RAG pipelines, and AI integration.

Ready to build with SearchCans?

Test SERP API and Reader API with 100 free credits. No credit card required.