Code for How to Use Google Custom Search Engine API in Python

You can also view the full code on github.

import requests

# get the API KEY here:
# get your Search Engine ID on your CSE control panel
# the search query you want
query = "python"
# constructing the URL
# doc:
url = f"{API_KEY}&cx={SEARCH_ENGINE_ID}&q={query}"

# make the API request
data = requests.get(url).json()
# get the result items
search_items = data.get("items")
# iterate over 10 results found
for i, search_item in enumerate(search_items, start=1):
    # get the page title
    title = search_item.get("title")
    # page snippet
    snippet = search_item.get("snippet")
    # alternatively, you can get the HTML snippet (bolded keywords)
    html_snippet = search_item.get("htmlSnippet")
    # extract the page url
    link = search_item.get("link")
    # print the results
    print("="*10, f"Result #{i}", "="*10)
    print("Title:", title)
    print("Description:", snippet)
    print("URL:", link, "\n")