Python 17 min read

Google Knowledge Graph Search API with Python

Use the Google Knowledge Graph Search API with Python for entity lookup, JSON-LD parsing, and RAG context. See limits and when live SERP data is a better fit.

(Updated: ) 3,312 words

The Google Knowledge Graph Search API is an entity lookup API for finding matching people, places, organizations, and other entities. This Python guide shows the entities:search request, JSON-LD response parsing, quota-aware error handling, and when live SERP or page data is a better fit.

Short answer: Use GET https://kgsearch.googleapis.com/v1/entities:search with a query and Google Cloud API key. The response contains ranked matches in itemListElement; it is not a full graph traversal API and it is separate from a Google Search API.

Key Takeaways

  • Entity lookup: The API returns matching entities and fields such as @id, name, @type, description, and resultScore.
  • Python integration: Python can send the request, parse itemListElement, and add entity context to search, annotation, or RAG workflows.
  • Separate data sources: The official Knowledge Graph API returns entity matches. A SERP API returns live search-result data, and a Reader API extracts selected pages. They solve different parts of a workflow.
  • Practical uses: Entity lookup can support autocomplete, content annotation, entity linking, and a structured context layer for LLM and RAG systems.

What the Google Knowledge Graph Search API Does

The Google Knowledge Graph Search API provides read-only entity search. Its endpoint is GET https://kgsearch.googleapis.com/v1/entities:search. You send a text query and optional filters such as types, languages, limit, and prefix; the response is a JSON object whose itemListElement contains ranked entity matches.

The response uses JSON-LD-oriented entity fields and may include an entity ID, name, description, type, detailed description, and resultScore. It is useful for identifying what a query refers to, but it does not expose a browsable graph of every relationship.

What Is the Google Knowledge Graph?

The Google Knowledge Graph is Google’s system for representing information about real-world entities and their relationships. Search features such as Knowledge Panels can use that system, but the public Search API should not be treated as a direct export of every panel, relationship, or internal ranking signal.

Core Use Cases for Developers

The API is most useful when an application needs a ranked entity match rather than a page from the open web.

Getting Ranked Entity Lists

You can retrieve a ranked list of the most notable entities that match specific criteria. This is useful for identifying prominent individuals, organizations, or concepts related to a search query.

Predictive Entity Completion

Integrate the API to provide predictive entity suggestions in search boxes, improving user experience by offering accurate and relevant completions as they type.

Annotating and Organizing Content

Leverage Knowledge Graph entities to semantically annotate or organize large datasets or content libraries. This enhances discoverability and allows for richer, more intelligent categorization.

Limitations and Operational Considerations

Keep these boundaries visible when designing the integration.

Read-Only Access

The API is strictly read-only, meaning you cannot contribute or modify data within the Knowledge Graph. Its purpose is purely for retrieval.

Entity-Focused, Not Graph-Focused

The API returns individual matching entities and their associated properties, but it does not provide a full graph of interconnected entities. If your application requires complex relationship traversal, a graph database or an open linked-data source may be more suitable.

Quota, Errors, and Availability

Google’s current usage documentation lists up to 100,000 read calls per day per project at no charge and describes a process for requesting higher quota. Check the current project quota before launch. A production integration still needs timeouts, structured error handling, backoff for 429 responses, key restrictions, monitoring, and a fallback or cached result strategy where the use case allows it. A quota is not an uptime guarantee.

Setting Up Your Python Environment

Before interacting with the API, install the small Python dependency and create a restricted API key in a Google Cloud project. Keep the key on the server or in a secret manager; do not put it in browser code or source control.

Obtaining a Google Cloud API Key

To access the Google Knowledge Graph API, you need an API key. This key authenticates your requests and links them to your Google Cloud project.

  1. Google Cloud Project: Ensure you have a Google Cloud project. If not, create one in the Google Cloud Console.
  1. Enable API: In your project, search for “Knowledge Graph API” in the API Library and enable it.
  1. Create API Key: Navigate to “APIs & Services” > “Credentials”. Click “Create Credentials” and select “API Key”.
  1. Restrict API Key (Recommended): For security, restrict your API key to only allow requests to the Knowledge Graph API and, if applicable, limit it to specific IP addresses or HTTP referrers. Store this key securely, ideally not directly in your code.

Pro Tip: Never hardcode your API keys directly into your scripts or commit them to version control. Use environment variables (e.g., os.environ.get('GOOGLE_KG_API_KEY')) or a configuration file (like a .env file) to manage sensitive credentials. This practice is crucial for maintaining security in any AI agent or data-driven application.

Installing Required Python Libraries

You’ll need the requests library for making HTTP requests and urllib.parse for URL encoding, which is standard in Python 3.

pip install requests

Querying the Google Knowledge Graph API with Python

Querying the Google Knowledge Graph API programmatically from Python involves constructing HTTP requests and parsing the JSON-LD responses. This process allows developers to search for entities based on keywords, filter results by type, and retrieve detailed descriptions. Understanding the API’s parameters and response structure is crucial for extracting precise, actionable insights, forming the bedrock of data-driven applications.

The API endpoint for searching entities is https://kgsearch.googleapis.com/v1/entities:search.

Let’s start with a simple search query for a well-known entity like “Taylor Swift”. This example demonstrates how to send a request, include your API key, and handle the JSON response.

Python Basic Entity Search Script

import requests
import os
from urllib.parse import urlencode

# Function: Performs a basic search on the Google Knowledge Graph API.
def search_knowledge_graph(query, api_key, limit=10):
   """
   Searches the Google Knowledge Graph for entities matching the query.

   Args:
       query (str): The search term (e.g., "Taylor Swift").
       api_key (str): Your Google Cloud API key.
       limit (int): Maximum number of results to return.

   Returns:
       list: A list of entity search results, or None if an error occurs.
   """
   service_url = 'https://kgsearch.googleapis.com/v1/entities:search'
   params = {
       'query': query,
       'limit': limit,
       'indent': True,  # For pretty-printed JSON response
       'key': api_key,
   }

   # Encode parameters to be part of the URL query string
   url = service_url + '?' + urlencode(params)

   try:
       response = requests.get(url, timeout=10) # 10s network timeout
       response.raise_for_status() # Raise an exception for HTTP errors
       data = response.json()
       return data.get('itemListElement', [])
   except requests.exceptions.RequestException as e:
       print(f"API request failed: {e}")
       return None

# --- Example Usage ---
if __name__ == "__main__":
   # Ensure you have GOOGLE_KG_API_KEY set in your environment variables
   # For local testing, you might load it from a .env file or similar
   google_api_key = os.environ.get('GOOGLE_KG_API_KEY')
   if not google_api_key:
       raise SystemExit("Set GOOGLE_KG_API_KEY before running this example.")

   if google_api_key:
       search_term = "Taylor Swift"
       results = search_knowledge_graph(search_term, google_api_key, limit=3)

       if results:
           print(f"Knowledge Graph results for '{search_term}':")
           for element in results:
               result = element.get('result', {})
               name = result.get('name', 'N/A')
               description = result.get('description', 'N/A')
               result_score = element.get('resultScore', 0)
               entity_types = ', '.join(result.get('@type', []))

               print(f"  Name: {name}")
               print(f"  Description: {description}")
               print(f"  Types: {entity_types}")
               print(f"  Score: {result_score}\n")
       else:
           print("No results or an error occurred.")

Filtering Results by Type

The Knowledge Graph API allows you to filter results by schema.org types, ensuring you retrieve only relevant entities (e.g., only “Person” or “Organization”). This is crucial for applications that need specific categories of information.

Python Filtering by Type Script

import requests
import os
from urllib.parse import urlencode

# Function: Filters Knowledge Graph results by schema.org type.
def search_knowledge_graph_with_type(query, api_key, entity_type, limit=10):
   """
   Searches the Google Knowledge Graph for entities matching the query and a specific schema.org type.

   Args:
       query (str): The search term.
       api_key (str): Your Google Cloud API key.
       entity_type (str): The schema.org type to filter by (e.g., "Person", "Organization", "Place").
       limit (int): Maximum number of results to return.

   Returns:
       list: A list of filtered entity search results, or None.
   """
   service_url = 'https://kgsearch.googleapis.com/v1/entities:search'
   params = {
       'query': query,
       'limit': limit,
       'indent': True,
       'key': api_key,
       'types': entity_type, # Filter by specific type
   }

   url = service_url + '?' + urlencode(params)

   try:
       response = requests.get(url, timeout=10)
       response.raise_for_status()
       data = response.json()
       return data.get('itemListElement', [])
   except requests.exceptions.RequestException as e:
       print(f"API request failed: {e}")
       return None

# --- Example Usage ---
if __name__ == "__main__":
   google_api_key = os.environ.get('GOOGLE_KG_API_KEY')
   if not google_api_key:
       raise SystemExit("Set GOOGLE_KG_API_KEY before running this example.")

   if google_api_key:
       search_term = "Apple"
       entity_type_filter = "Organization" # Try "Company" or "Product" as well
       results = search_knowledge_graph_with_type(search_term, google_api_key, entity_type_filter, limit=3)

       if results:
           print(f"Knowledge Graph results for '{search_term}' (Type: {entity_type_filter}):")
           for element in results:
               result = element.get('result', {})
               name = result.get('name', 'N/A')
               description = result.get('description', 'N/A')
               result_score = element.get('resultScore', 0)
               entity_types = ', '.join(result.get('@type', []))

               print(f"  Name: {name}")
               print(f"  Description: {description}")
               print(f"  Types: {entity_types}")
               print(f"  Score: {result_score}\n")
       else:
           print("No results or an error occurred.")

Parsing the API Response

The API returns data in a JSON-LD format, which is a linked data format based on JSON. Key elements to look for in the response include:

  • itemListElement: A list of search results.
  • resultScore: A confidence score indicating how relevant the entity is to the query.
  • result: Contains the entity’s details.
  • @id: The canonical ID of the entity (e.g., kg:/m/0dl567).
  • name: The common name of the entity.
  • description: A short summary.
  • @type: A list of schema.org types (e.g., ["Person", "Thing"]).
  • detailedDescription: More extensive information, often from Wikipedia.

Parsing these fields lets an application normalize entity IDs, names, types, and descriptions before adding them to its own search or RAG context. Treat the returned fields as API data that still needs validation for the application’s language, freshness, and confidence requirements.

Enhancing Applications with Knowledge Graph Data

Integrating entity data can add a structured layer to an application. It can enrich LLM context, support search features, and help content systems distinguish entities from similarly named strings. The application remains responsible for validating how an entity is used.

Augmenting LLMs and RAG Systems

Large Language Models (LLMs) and Retrieval Augmented Generation (RAG) systems can use entity data as one input. Knowledge Graph results can:

  • Add an entity layer: Provide IDs, names, types, and descriptions that help a pipeline resolve references before retrieval.
  • Enrich RAG context: Use a resolved entity as a filter or metadata field when retrieving documents, rather than treating the API response as a complete answer.
  • Improve entity linking: Map mentions in unstructured text to candidate entity IDs, then apply application-specific disambiguation. For page context, a Reader API can convert selected URLs into clean Markdown after discovery.

SEO and Content Optimization

For SEO professionals and content strategists, the API can provide an entity-oriented signal, but it does not guarantee a Knowledge Panel or ranking change.

  • Identify entity coverage: Compare the entities in a topic with the entities your content explains, without assuming that an API match guarantees a search feature.
  • Semantic SEO: Move beyond keyword stuffing to semantic SEO, organizing content around entities and their relationships, which aligns with how modern search engines understand information. You can use advanced strategies for content cluster SEO.

Predictive Search and Autocompletion

Building robust search functionalities is critical for many applications.

  • Intelligent Autocomplete: Enhance search bars with intelligent autocompletion features that suggest recognized entities from the Knowledge Graph, leading users to more precise results faster.
  • Contextual Search: Develop search experiences that understand user intent based on entities, rather than just keywords, providing more relevant and contextually appropriate results.

Official Knowledge Graph Data vs. Live SERP and Page Data

The official Knowledge Graph API and live web data answer different questions. The first returns entity matches from Google’s knowledge system. Live SERP data shows what a search engine returned for a query at a particular time, while page extraction gives the text of a selected source.

Structured Entity Lookup vs. Dynamic Context

The key difference lies in the nature of the data:

  • Google Knowledge Graph Search API: Useful for entity lookup, IDs, types, and descriptions. It is not a full graph traversal endpoint or a general web search API.
  • Live web data: Useful for current rankings, news, product pages, documentation, and other facts that can change after the entity record was produced.

For example, an entity lookup can help identify a person or organization, while a Google Search API can retrieve the current SERP for a query and the Reader API can extract a selected source page.

When to Use SearchCans Search and Reader APIs

SearchCans is separate from Google’s Knowledge Graph Search API. Its products cover live search-result retrieval and selected-page extraction.

SearchCans Google Search API

The SearchCans Google Search API uses POST /api/v1/search for structured SERP data. With knowledgeGraph: true, the response can include the Knowledge Graph panel found in the live SERP response. This is not the official Google Knowledge Graph Search API and should not be described as the same endpoint.

  • Capture current SERP features: Inspect the Knowledge Graph panel, organic results, and other returned SERP fields for the query and request settings.
  • Contextualize entities: Compare an entity lookup with the live search result and its surrounding sources.
  • Monitor search visibility: Track current result pages and features when the workflow needs ranking or competitor evidence.

SearchCans Reader API

The SearchCans Reader API uses POST /api/v1/url to convert a selected URL into clean Markdown for downstream processing. Use it after entity or SERP discovery when the application needs page-level evidence.

  • RAG grounding: After identifying an entity and finding relevant URLs, extract the source pages and attach their URL, retrieval time, and page context to the RAG record.
  • Clear separation: Reader extracts a selected page; it does not replace entity lookup or live SERP retrieval.
  • Product fit: Check the current SearchCans pricing and credit terms for the workload instead of copying a fixed price into an implementation guide.

Workflow example: Resolve an entity with the official API, use SearchCans Search when the workflow needs current SERP evidence, and use Reader for the source pages that deserve closer inspection. Keep these outputs labeled separately so a live snippet is not mistaken for an entity fact.

Common Pitfalls and Best Practices

The main risks are simple to name: exposing the API key, assuming every query has one unambiguous entity, ignoring quota responses, and treating a partial entity record as a complete source of truth.

API Key Management and Security

As previously mentioned, never embed your API key directly in your code. Use environment variables or a secure configuration system. Review key usage in the Google Cloud Console and restrict the key to the required API and, where appropriate, the caller’s IP address or HTTP referrers.

Error Handling and Rate Limits

API integrations must be resilient. Handle network errors, invalid queries, empty result sets, and non-2xx responses explicitly. Respect the published project quota and use bounded exponential backoff for transient 429 responses. Retries should have a cap so a failing dependency cannot stall the whole workflow.

Optimizing Queries for Performance

To make requests easier to operate:

  • Specify limit and types: Always use the limit parameter to fetch only the necessary number of results, and apply types filters to narrow down the search to relevant entity categories.
  • Cache carefully: For frequently queried entities, a short-lived cache can reduce duplicate calls. Define an expiry and refresh policy so stale entity data is not presented as current.

Comparison: Entity Search, Live SERP, and Reader Data

Choose the source by the question you need to answer. The official API handles entity lookup; SearchCans handles live SERP JSON; Reader handles page extraction.

Feature Google Knowledge Graph Search API SearchCans Google Search API SearchCans Reader API
Data source Google Knowledge Graph entity matches Live Google SERP response Selected URL content
Output JSON with itemListElement and JSON-LD-oriented entity fields Structured SERP JSON, with an optional Knowledge Graph panel Clean Markdown from the requested URL
Best use Entity lookup, entity linking, and structured context Current search results, SERP features, and rank evidence Page-level context for RAG or downstream parsing
Request GET https://kgsearch.googleapis.com/v1/entities:search POST /api/v1/search POST /api/v1/url
Freshness Depends on Google’s entity data and query response Retrieved from the live SERP request Retrieved from the selected page request
Operational boundary Not a full graph traversal or general web search endpoint Not the official Google Knowledge Graph Search API Not an entity database or a search-result endpoint
Cost Check current Google Cloud project quota and pricing Check current SearchCans plan terms Check current SearchCans plan terms

FAQ: Google Knowledge Graph Search API

Q: What is the Google Knowledge Graph Search API?

A: It is a read-only Google API for searching entity records. The endpoint is GET https://kgsearch.googleapis.com/v1/entities:search, and matches are returned in itemListElement with fields such as IDs, names, types, descriptions, and scores.

Q: Does the API return the full Knowledge Graph?

A: No. It returns ranked matches for an entity query. It does not provide a complete graph export, unrestricted relationship traversal, or the full live content of search-result pages.

Q: What is the daily usage limit?

A: Google’s current usage documentation lists up to 100,000 read calls per day per project at no charge and explains how to request higher quota. Verify the quota shown for your project before relying on that number in production.

Q: How is it different from a Google Search API?

A: The Knowledge Graph Search API searches entity records. A Google Search API retrieves a live search-result page and its structured result fields. SearchCans’ Google Search API is a separate product that can return SERP JSON and an optional Knowledge Graph panel from the live result.

SearchCans and Knowledge Graph Summary

The Google Knowledge Graph Search API with Python is a focused way to resolve entity queries and add structured context to an application. It is not a general Google Search API, a full graph export, or a substitute for source-page evidence.

For dynamic web data, use SearchCans’ API hub to choose the separate search and Reader paths. The Google Search API can retrieve live SERP JSON, while Reader can extract selected source pages into Markdown.

Ready to test the workflow? Get a SearchCans API key for the live search and page-extraction parts, and keep the official Knowledge Graph API key in a restricted Google Cloud project.

What SearchCans Is NOT For

SearchCans is designed for live search and page extraction, it is NOT designed for:

  • Browser automation testing (use Selenium, Cypress, or Playwright for UI testing)
  • Form submission and interactive workflows requiring stateful browser sessions
  • Full-page screenshot capture with pixel-perfect rendering requirements
  • Custom JavaScript injection after page load requiring post-render DOM manipulation

Boundary: SearchCans complements the official entity API with live SERP and page data. It does not replace the official entity lookup endpoint.

Conclusion

The official Google Knowledge Graph Search API provides entity matches. SearchCans provides separate live SERP and Reader endpoints when an application also needs current search results or source-page text. Keep the three outputs separate in code and in citations.

Get Your API Key Now , Start Free!

Tags:

Python Google API Knowledge Graph Entity Extraction Semantic Web AI Developers
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.