Skip to content

Instantly share code, notes, and snippets.

@nicogaspa
Last active May 15, 2021 09:52
Show Gist options
  • Save nicogaspa/f6f138889794c4ff3580c39a45b3e6cb to your computer and use it in GitHub Desktop.
Save nicogaspa/f6f138889794c4ff3580c39a45b3e6cb to your computer and use it in GitHub Desktop.
Google Knowledge Search API class
import requests
from typing import List
API_KEY = "" # TODO
VERSION = "v1"
class GoogleKnowledgeSearchService:
def __init__(self):
self.api_key = API_KEY
self.base_url = f"https://kgsearch.googleapis.com/{VERSION}"
def search(
self,
query: str,
languages: List[str] = None,
types: List[str] = None,
prefix: str = None,
):
"""
:param query: Literal string to search for in the Knowledge Graph
:param languages: List of language codes (defined in ISO 639) to run the query with
:param types: Restricts returned entities to those of the specified types.
:param prefix: Initial substring match against names and aliases of entities
"""
params = {"query": query, "key": self.api_key}
if languages is not None:
params["languages"] = ",".join(languages)
if types is not None:
params["types"] = ",".join(types)
if prefix is not None:
params["prefix"] = prefix
result = requests.get(f"{self.base_url}/entities:search", params=params)
return result.json()
if __name__ == "__main__":
service = GoogleKnowledgeSearchService()
results = service.search("Armani")
results = service.search("Armani", types=["Person"], languages=["it"])
results = service.search("Binance", types=["Organization"])
results = service.search("Musk", languages=["es"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment