### Install Google API Client Library for Ruby Source: https://developers.google.com/knowledge-graph/libraries Installs the `google-api-client` gem using RubyGems. This is the primary command for initial setup. Depending on system permissions, `sudo` might be required. ```Ruby gem install google-api-client ``` -------------------------------- ### Install Google Knowledge Graph Search API Client Library for .NET using NuGet Source: https://developers.google.com/knowledge-graph/libraries This instruction guides users on installing the Google Knowledge Graph Search API client library for .NET. It involves using the NuGet package manager to install the 'Google.Apis' package. Refer to the .NET reference documentation for further details. ```bash Install the NuGet package: Google.Apis. ``` -------------------------------- ### Install Google Knowledge Graph Search API Client Library for Python using Setuptools Source: https://developers.google.com/knowledge-graph/libraries This command installs the Google Knowledge Graph Search API client library for Python using setuptools. While pip is preferred, setuptools offers an alternative for managed installation. This method also requires Python 3.7 or higher for the v2 library. ```bash easy_install --upgrade google-api-python-client ``` -------------------------------- ### Manually Install Google Knowledge Graph Search API Client Library for Python Source: https://developers.google.com/knowledge-graph/libraries This section details the manual installation process for the Google Knowledge Graph Search API client library for Python. It involves downloading the library, unpacking the code, and then running the installation script. This method is suitable when package managers cannot be used. ```bash python setup.py install ``` -------------------------------- ### Install Google Knowledge Graph Search API Client Library for Python using Pip Source: https://developers.google.com/knowledge-graph/libraries This code installs the Google Knowledge Graph Search API client library for Python using the pip package manager. It's the preferred method for managed installation and requires Python 3.7 or higher for the v2 library. Ensure you have pip installed and potentially use `sudo` for global installations. ```bash pip install --upgrade google-api-python-client ``` -------------------------------- ### Pass Configuration Object to KGSearchWidget Source: https://developers.google.com/knowledge-graph/how-tos/search-widget This example demonstrates how to create and pass a configuration object to the KGSearchWidget. The config object allows setting parameters like result limits, languages, entity types, description length, and custom event handlers. ```javascript var config = { 'limit': 10, 'languages': ['en', 'fr'], 'types': ['Person', 'Movie'], 'maxDescChars': 100 }; config['selectHandler'] = function(e) { alert(e.row.name + ' selected'); }; config['highlightHandler'] = function(e) { alert(e.row.name + ' highlighted'); }; KGSearchWidget(, document.getElementById('myInput'), config); ``` -------------------------------- ### Sample Knowledge Graph Search Response (JSON-LD) Source: https://developers.google.com/knowledge-graph/index This is an example of a JSON-LD response from the Knowledge Graph Search API for a query. It includes metadata, a list of search results, and details about each entity found, such as its type, name, description, and image. ```json {   "@context": {     "@vocab": "http://schema.org/",     "goog": "http://googleapis.com/",     "resultScore": "goog:resultScore",     "detailedDescription": "goog:detailedDescription",     "EntitySearchResult": "goog:EntitySearchResult",     "kg": "http://g.co/kg"   },   "@type": "ItemList",   "itemListElement": [     {       "@type": "EntitySearchResult",       "result": {         "@id": "kg:/m/0dl567",         "name": "Taylor Swift",         "@type": [           "Thing",           "Person"         ],         "description": "Singer-songwriter",         "image": {           "contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku",           "url": "https://en.wikipedia.org/wiki/Taylor_Swift",           "license": "http://creativecommons.org/licenses/by-sa/2.0"         },         "detailedDescription": {           "articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ",           "url": "http://en.wikipedia.org/wiki/Taylor_Swift",           "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"         },         "url": "http://taylorswift.com/"       },       "resultScore": 4850     }   ] } ``` -------------------------------- ### Update Google API Client Library for Ruby Source: https://developers.google.com/knowledge-graph/libraries Updates the already installed `google-api-client` gem to the latest version. The `-y` flag automatically answers yes to any prompts during the update process. ```Ruby gem update -y google-api-client ``` -------------------------------- ### Knowledge Graph Search API HTTP GET Request Source: https://developers.google.com/knowledge-graph/reference/rest/v1 This snippet demonstrates the base HTTP GET request URL for the Knowledge Graph Search API. It is used to initiate a search for entities within the Knowledge Graph. ```http GET https://kgsearch.googleapis.com/v1/entities:search ``` -------------------------------- ### GET /entities:search Source: https://developers.google.com/knowledge-graph/reference/rest/v1 Searches the Knowledge Graph for entities that match the specified constraints. This endpoint allows for detailed searches using keywords, entity IDs, languages, types, and more. ```APIDOC ## GET /entities:search ### Description Searches Knowledge Graph for entities that match the constraints. ### Method GET ### Endpoint https://kgsearch.googleapis.com/v1/entities:search ### Parameters #### Query Parameters - **query** (string) - Required - A literal string to search for in the Knowledge Graph. - **ids** (string) - Optional - A list of entity IDs to search for in the Knowledge Graph. To specify multiple IDs in the HTTP request, repeat the parameter in the URL as in ...?ids=A&ids=B. - **languages** (string) - Optional - The list of language codes (defined in ISO 639) to run the query with, for instance `en`. - **types** (string) - Optional - Restricts returned entities to those of the specified types. For example, you can specify `Person` (as defined in http://schema.org/Person) to restrict the results to entities representing people. If multiple types are specified, returned entities will contain one or more of these types. - **indent** (boolean) - Optional - Enables indenting of JSON results. - **prefix** (boolean) - Optional - Enables prefix (initial substring) match against names and aliases of entities. For example, a prefix `Jung` will match entities and aliases such as `Jung`, `Jungle`, and `Jung-ho Kang`. - **limit** (number) - Optional - Limits the number of entities to be returned. Maximum is 500. Default is 20. Requests with high limits have a higher chance of timing out. #### Request Body The request body must be empty. ### Response #### Success Response (200) A response message contains a list of entities, presented in JSON-LD format and compatible with schema.org schemas (with limited external extensions). - **@context** (object) - Defines the vocabulary and namespaces used in the JSON-LD response. - **@type** (string) - The type of the JSON-LD object, typically 'ItemList'. - **itemListElement** (array) - A list of EntitySearchResult objects. - **@type** (string) - The type of the search result, typically 'EntitySearchResult'. - **result** (object) - Contains the detailed information about the entity. - **@id** (string) - The unique identifier for the entity. - **name** (string) - The name of the entity. - **@type** (array) - An array of types the entity belongs to (e.g., "Thing", "Person"). - **description** (string) - A brief description of the entity. - **image** (object) - Information about the entity's image. - **contentUrl** (string) - The URL of the image content. - **url** (string) - A URL related to the image (e.g., Wikipedia page). - **license** (string) - The license under which the image is provided. - **detailedDescription** (object) - A more detailed description of the entity. - **articleBody** (string) - The main text content of the detailed description. - **url** (string) - A URL for the detailed description (e.g., Wikipedia URL). - **license** (string) - The license for the detailed description content. - **url** (string) - The primary URL for the entity. - **resultScore** (number) - A score indicating the relevance of the entity to the query. ### Request Example ```json { "example": "Request body is empty for this endpoint." } ``` ### Response Example ```json { "@context": { "@vocab": "http://schema.org/", "goog": "http://schema.googleapis.com/", "resultScore": "goog:resultScore", "detailedDescription": "goog:detailedDescription", "EntitySearchResult": "goog:EntitySearchResult", "kg": "http://g.co/kg" }, "@type": "ItemList", "itemListElement": [ { "@type": "EntitySearchResult", "result": { "@id": "kg:/m/0dl567", "name": "Taylor Swift", "@type": [ "Thing", "Person" ], "description": "Singer-songwriter", "image": { "contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku", "url": "https://en.wikipedia.org/wiki/Taylor_Swift", "license": "http://creativecommons.org/licenses/by-sa/2.0" }, "detailedDescription": { "articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ", "url": "http://en.wikipedia.org/wiki/Taylor_Swift", "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License" }, "url": "http://taylorswift.com/" }, "resultScore": 4850 } ] } ``` ``` -------------------------------- ### Knowledge Graph Search API Response Structure (JSON-LD) Source: https://developers.google.com/knowledge-graph/reference/rest/v1 This example shows the structure of a typical JSON-LD response from the Knowledge Graph Search API. It includes context, entity type, and a list of search results, each with details like ID, name, type, description, image, and relevance score. ```json { "@context": { "@vocab": "http://schema.org/", "goog": "http://googleapis.com/", "resultScore": "goog:resultScore", "detailedDescription": "goog:detailedDescription", "EntitySearchResult": "goog:EntitySearchResult", "kg": "http://g.co/kg" }, "@type": "ItemList", "itemListElement": [ { "@type": "EntitySearchResult", "result": { "@id": "kg:/m/0dl567", "name": "Taylor Swift", "@type": [ "Thing", "Person" ], "description": "Singer-songwriter", "image": { "contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku", "url": "https://en.wikipedia.org/wiki/Taylor_Swift", "license": "http://creativecommons.org/licenses/by-sa/2.0" }, "detailedDescription": { "articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ", "url": "http://en.wikipedia.org/wiki/Taylor_Swift", "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License" }, "url": "http://taylorswift.com/" }, "resultScore": 4850 } ] } ``` -------------------------------- ### Search Knowledge Graph API with Java Source: https://developers.google.com/knowledge-graph/index This Java code snippet demonstrates how to use the Google Knowledge Graph Search API to find entities. It utilizes the Google HTTP client library and JSONPath for parsing. The code reads an API key from a properties file and sends a GET request to the search endpoint, then prints the names of the found entities. ```java package com.google.knowledge.platforms.syndication.entitymatch.codesample; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.jayway.jsonpath.JsonPath; import java.io.FileInputStream; import java.util.Properties; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** Example of Java client calling Knowledge Graph Search API */ public class SearchExample { public static Properties properties = new Properties(); public static void main(String[] args) { try { properties.load(new FileInputStream("kgsearch.properties")); HttpTransport httpTransport = new NetHttpTransport(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); JSONParser parser = new JSONParser(); GenericUrl url = new GenericUrl("https://kgsearch.googleapis.com/v1/entities:search"); url.put("query", "Taylor Swift"); url.put("limit", "10"); url.put("indent", "true"); url.put("key", properties.get("API_KEY")); HttpRequest request = requestFactory.buildGetRequest(url); HttpResponse httpResponse = request.execute(); JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString()); JSONArray elements = (JSONArray) response.get("itemListElement"); for (Object element : elements) { System.out.println(JsonPath.read(element, "$.result.name").toString()); } } catch (Exception ex) { ex.printStackTrace(); } } } ``` -------------------------------- ### Search Knowledge Graph API with Javascript Source: https://developers.google.com/knowledge-graph/index This Javascript code snippet demonstrates how to query the Google Knowledge Graph Search API using jQuery. It makes a GET request to the search endpoint with specified parameters like query and API key. The response is processed to display the names of the found entities directly on the HTML page. ```javascript ``` -------------------------------- ### Acquiring and Using an API Key Source: https://developers.google.com/knowledge-graph/how-tos/authorizing Instructions on how to obtain and manage API keys for accessing the Google Knowledge Graph Search API, including security best practices. ```APIDOC ## Acquiring and Using an API Key ### Description This section details the steps to acquire and manage API keys for the Google Knowledge Graph Search API. API keys are essential for identifying your project and enabling access, quota management, and reporting. ### Steps to Acquire an API Key 1. **Navigate to Credentials Page:** Open the Credentials page in the Google Cloud Console. 2. **Create Credentials:** Choose the appropriate credential type for your project. For public data access, an API key is typically sufficient. * **API keys:** Click **Create credentials > API key**. This key identifies your project and grants API access. * **OAuth 2.0:** Required for requesting private user data. Not strictly necessary for public data to this API. 3. **Restrict API Key (Recommended):** Before using the key in production, click **Restrict key** and apply security restrictions as needed. 4. **Secure Your API Key:** Follow best practices for securely managing your API keys. ### Using the API Key Append the query parameter `key=yourAPIKey` to all request URLs. The API key is safe to embed directly in URLs and does not require encoding. ``` -------------------------------- ### Knowledge Graph Search Widget Integration Source: https://developers.google.com/knowledge-graph/how-tos/search-widget This section details how to add the Knowledge Graph Search Widget to your website, including necessary HTML code, CSS styling, and JavaScript initialization. It also explains how to obtain and use an API key. ```APIDOC ## Knowledge Graph Search Widget Integration ### Description Integrate the Knowledge Graph Search Widget into your website to provide users with auto-suggested topics and relevant data from the Google Knowledge Graph as they type in input fields. ### Method N/A (Client-side JavaScript integration) ### Endpoint N/A (Client-side JavaScript integration) ### Parameters #### Request Body N/A ### Request Example #### HTML Head Section ```html ``` #### HTML Body Section (Input Field and Initialization) ```html ``` ### Obtaining and using an API key An API key is required for the widget to access the Google Knowledge Graph API. Follow the instructions on the Prerequisites page to obtain a key. Pass the obtained key as the first argument to `KGSearchWidget()`. ### Response N/A (Widget provides real-time suggestions) ### Response Example N/A ``` -------------------------------- ### Initialize Knowledge Graph Search Widget in HTML Body Source: https://developers.google.com/knowledge-graph/how-tos/search-widget This JavaScript code should be placed within the `` of your HTML document, typically after an input field. It initializes the Knowledge Graph Search Widget, associating it with a specific input element by its ID and accepting an API key and an optional configuration object. ```javascript KGSearchWidget(, document.getElementById("myInput"), {}); ``` -------------------------------- ### Configuring the Search Widget Source: https://developers.google.com/knowledge-graph/how-tos/search-widget Learn how to customize the behavior of the Knowledge Graph Search Widget by passing a configuration object during initialization. This allows for adjustments to filtering, constraints, and event handling. ```APIDOC ## Configuring the Search Widget ### Description Customize the Knowledge Graph Search Widget's functionality by providing a configuration object as the third argument to the `KGSearchWidget` constructor. This object can specify various options for filtering, setting limits, and defining event handlers. ### Method N/A (Client-side JavaScript configuration) ### Endpoint N/A (Client-side JavaScript configuration) ### Parameters #### Request Body ##### Configuration Object (Third argument to `KGSearchWidget`) - **language** (string) - Optional - Specifies the preferred language for search results. Example: `'en'`. - **limit** (integer) - Optional - Sets the maximum number of results to display. Example: `5`. - **other_options** (object) - Optional - For additional configuration parameters as needed. #### Query Parameters N/A #### Path Parameters N/A ### Request Example #### Passing a configuration object ```javascript KGSearchWidget('', document.getElementById('myInput'), { language: 'en', limit: 10 }); ``` ### Response N/A (Widget provides real-time suggestions) ### Response Example N/A ``` -------------------------------- ### Add Google Knowledge Graph Search API Client Library to Gradle Project Source: https://developers.google.com/knowledge-graph/libraries This snippet demonstrates how to add the Google Knowledge Graph Search API client library to a Java project using Gradle. It involves updating the `build.gradle` file with the necessary dependency. Always refer to Maven Central for the most current versions. ```gradle // Add the following to your `build.gradle` file // See all versions available on the Maven Central Repository. ``` -------------------------------- ### Implement highlightHandler for KGSearchWidget Source: https://developers.google.com/knowledge-graph/how-tos/search-widget This code demonstrates how to implement the `highlightHandler` for the Knowledge Graph Search Widget. This event handler is triggered when a user hovers over an item in the suggestion list, providing event data about the highlighted row. ```javascript KGSearchWidget(, document.getElementById("myInput"), { "highlightHandler": function(e) { alert("highlighted " + e.row.name); } }); ``` -------------------------------- ### Implement selectHandler for KGSearchWidget Source: https://developers.google.com/knowledge-graph/how-tos/search-widget This snippet shows how to implement the `selectHandler` callback for the Knowledge Graph Search Widget. This function is invoked when a user selects an item from the suggestion list, receiving an event object with details about the selected row. ```javascript KGSearchWidget(, document.getElementById("myInput"), { "selectHandler": function(e) { alert("selected " + e.row.name); } }); ``` -------------------------------- ### Sample Knowledge Graph Search Request Source: https://developers.google.com/knowledge-graph/index This is a sample URL request to the Knowledge Graph Search API to find entities matching 'taylor swift'. It includes parameters for the query, API key, result limit, and output indentation. Ensure you replace 'API_KEY' with your actual key. ```url https://kgsearch.googleapis.com/v1/entities:search?query=taylor+swift&key=API_KEY&limit=1&indent=True ``` -------------------------------- ### Add Google Knowledge Graph Search API Client Library to Maven Project Source: https://developers.google.com/knowledge-graph/libraries This snippet shows how to add the Google Knowledge Graph Search API client library to a Java project using Maven. It requires updating the `pom.xml` file with the appropriate dependency. Ensure you check Maven Central for the latest versions. ```xml ``` -------------------------------- ### Include Knowledge Graph Search Widget CSS and JS in HTML Head Source: https://developers.google.com/knowledge-graph/how-tos/search-widget This code snippet should be included in the `` section of your HTML document. It links the necessary CSS stylesheet and the JavaScript module for the Knowledge Graph Search Widget. The CSS includes a style for the dropdown menu width, which you may need to customize. ```html ``` -------------------------------- ### Python Client for Knowledge Graph Search API Source: https://developers.google.com/knowledge-graph/index This Python script demonstrates how to query the Knowledge Graph Search API. It constructs a request URL with a query, API key, and other parameters, then fetches and parses the JSON response to print entity names and their scores. It requires an API key stored in a '.api_key' file. ```python import json import urllib api_key = open('.api_key').read() query = 'Taylor Swift' service_url = 'https://kgsearch.googleapis.com/v1/entities:search' params = { 'query': query, 'limit': 10, 'indent': True, 'key': api_key, } url = service_url + '?' + urllib.urlencode(params) response = json.loads(urllib.urlopen(url).read()) for element in response['itemListElement']: print(element['result']['name'] + ' (' + str(element['resultScore']) + ')') ``` -------------------------------- ### Add Input Field for Knowledge Graph Search Widget Source: https://developers.google.com/knowledge-graph/how-tos/search-widget This HTML snippet defines a standard text input field. This input field will be used by the Knowledge Graph Search Widget to display suggestions as the user types. Ensure the `id` attribute of this input matches the one used when initializing the widget in JavaScript. ```html ``` -------------------------------- ### Knowledge Graph API Response Fields Source: https://developers.google.com/knowledge-graph/reference/rest/v1 This section describes the fields returned by the Google Knowledge Graph API, including their types and descriptions. It also clarifies the use of JSON-LD keywords and Schema.org compatibility, including Google's specific extensions. ```APIDOC ## Knowledge Graph API Response Structure ### Description This endpoint returns information about entities, including their canonical URI, name, type, descriptions, image, and a score indicating how well the entity matched the request. ### Method GET (Implied, as no specific method is mentioned, but typical for data retrieval) ### Endpoint `/websites/developers_google_knowledge-graph` (This appears to be a page path, not a direct API endpoint. A typical Knowledge Graph API endpoint would be more like `/kgsearch/v1`) ### Response #### Success Response (200) - **`@id`** (string) - The canonical URI for the entity. - **`name`** (string) - The name of the entity. - **`@type`** (array) - The list of supported schema.org types that match the entity. - **`description`** (string) - A short description of the entity. - **`image`** (URL) - An image to help identify the entity. - **`detailedDescription`** (string) - A detailed description of the entity. - **`url`** (URL) - The official website URL of the entity, if available. - **`resultScore`** (number) - An indicator of how well the entity matched the request constraints. ### Schema.org Compatibility - The response uses the vocabulary hosted at schema.org. - Google extensions like `resultScore` are compatible with schema.org. - Google schema extensions are hosted at `http://schema.googleapis.com`. - **Type extension:** `EntitySearchResult` - **Property extensions:** `detailedDescription`, `resultScore` ### JSON-LD Keywords For keywords like `@context`, `@vocab`, `@type`, or `@id`, refer to the JSON-LD specification. ``` -------------------------------- ### Search Knowledge Graph API with PHP Source: https://developers.google.com/knowledge-graph/index This PHP code snippet shows how to call the Google Knowledge Graph Search API using cURL. It requires an API key stored in a separate file. The code constructs the API URL with parameters, executes a cURL request, decodes the JSON response, and then iterates through the results to display the names of the entities. ```php 'Taylor Swift', 'limit' => 10, 'indent' => TRUE, 'key' => $api_key); $url = $service_url . '?' . http_build_query($params); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = json_decode(curl_exec($ch), true); curl_close($ch); foreach($response['itemListElement'] as $element) { echo $element['result']['name'] . '
'; } ``` -------------------------------- ### Knowledge Graph Search API - Request with API Key Source: https://developers.google.com/knowledge-graph/how-tos/authorizing This section describes how to authenticate requests to the Google Knowledge Graph Search API using an API key. Public data requests do not require authorization but must include an API key to identify the project. ```APIDOC ## GET /kgsearch/v1/query ### Description Sends a query to the Knowledge Graph Search API to retrieve information about entities. ### Method GET ### Endpoint `/kgsearch/v1/query` ### Parameters #### Query Parameters - **query** (string) - Required - The search query string. - **key** (string) - Required - Your API key for project identification and access. ### Request Example ``` GET /kgsearch/v1/query?query=Barack%20Obama&key=YOUR_API_KEY ``` ### Response #### Success Response (200) - **itemListElement** (array) - A list of results matching the query. #### Response Example ```json { "@context": { "@vocab": "http://schema.org/", "resultScore": "goog:resultScore" }, "@type": "ItemList", "itemListElement": [ { "@context": "http://schema.org", "@type": "Thing", "name": "Barack Obama", "description": "44th president of the United States.", "resultScore": 10.586593 } ] } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.