Can't get Google Search API to work with Python

I am using the native google search API but I keep getting 403 error. The key is taken from console.developers.google.com under API and auth -> Credentials and I used the browser key with any referrers. The identifier is taken from the basic information of custom search engines.

import requests

search = "https://www.googleapis.com/customsearch/v1"
key = "?key=MY_KEY"
id_ = "&cx=MY_ID"
query = "&q=test"

get = search + key + id_ + query

r = requests.get(get)

print(r)

      

What am I doing wrong?

+3


source to share


1 answer


I don't know if this is the source of your problem or not, but you could use a library better requests

. First, you can put your API key and CX value in a session object, where they can be used in subsequent requests:

>>> import requests
>>> s = requests.Session()
>>> s.params['key'] = 'MY_KEY'
>>> s.params['cx'] = 'MY_CX'

      

And you can pass additional search parameters by passing the dict in the key params

rather than generating the url yourself:

>>> result = s.get('https://www.googleapis.com/customsearch/v1', 
... params={'q': 'my search string'})

      

This all works for me:



>>> result
<Response [200]>
>>> print result.text
{
 "kind": "customsearch#search",
 "url": {
  "type": "application/json",
  "template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe
[...]

      

It is also worth checking out that you have enabled the search API for your API key.

You can see exactly what the library is doing by requests

enabling debug logging through the Python module logging

:

>>> import logging
>>> logging.basicConfig(level='DEBUG')
>>> result = s.get('https://www.googleapis.com/customsearch/v1', params={'q': 'openstack'})
DEBUG:requests.packages.urllib3.connectionpool:"GET /customsearch/v1?q=openstack&cx=0123456789123456789%3Aabcdefghijk&key=THIS_IS_MY_KEY HTTP/1.1" 200 13416

      

+1


source







All Articles