A nova API Search Ads 360 Reporting já está disponível. Participe do grupo do Google searchads-api-announcements para ficar por dentro das próximas melhorias e versões.
[null,null,["Última atualização 2025-08-29 UTC."],[[["\u003cp\u003eThis Python script generates OAuth2 refresh tokens for the Search Ads 360 Reporting API.\u003c/p\u003e\n"],["\u003cp\u003eThe script requires a client secrets JSON file from the Google Cloud Console and utilizes a local web server for authorization.\u003c/p\u003e\n"],["\u003cp\u003eUsers must add "http://127.0.0.1" to the "Authorized redirect URIs" list in their Google Cloud project for web app client types.\u003c/p\u003e\n"],["\u003cp\u003eUpon successful execution, the script outputs the refresh token that can be used to access the Search Ads 360 Reporting API.\u003c/p\u003e\n"],["\u003cp\u003eYou can download the \u003ccode\u003egenerate_user_credentials.py\u003c/code\u003e script to get started.\u003c/p\u003e\n"]]],["This Python script generates an OAuth2 refresh token for the Search Ads 360 Reporting API. It uses the `google-auth-oauthlib` library, requiring installation via `pip install google-auth-oauthlib`. The script initiates an OAuth2 flow, directing the user to a generated authorization URL. Upon granting permission, it captures a callback to a local server, extracts the authorization code, and uses it to retrieve and print the refresh token, along with client credentials in the required format. The script also provides the command to install the required library.\n"],null,["# Generate User Credentials\n\n| **Note:** The sample code below needs the Google authentication library installed. You can use pip to get it. \n|\n| ```text\n| $ pip install google-auth-oauthlib\n``` \n\n### Python\n\n\n```python\n#!/usr/bin/env python\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"This example will create an OAuth2 refresh token for the Search Ads 360 Reporting API.\n\nThis example works with both web and desktop app OAuth client ID types.\n\nhttps://console.cloud.google.com\n\nIMPORTANT: For web app clients types, you must add \"http://127.0.0.1\" to the\n\"Authorized redirect URIs\" list in your Google Cloud Console project before\nrunning this example. Desktop app client types do not require the local\nredirect to be explicitly configured in the console.\n\nOnce complete, download the credentials and save the file path so it can be\npassed into this example.\n\nThis example is a very simple implementation, for a more detailed example see:\nhttps://developers.google.com/identity/protocols/oauth2/web-server#python\n\"\"\"\n\nimport argparse\nimport hashlib\nimport os\nimport re\nimport socket\nimport sys\nimport urllib.parse\n\n# If using Web flow, the redirect URL must match exactly what's configured in\n# GCP for the OAuth client. If using Desktop flow, the redirect must be a\n# localhost URL and is not explicitly set in GCP.\nfrom google_auth_oauthlib.flow import Flow\n\n_SCOPE = \"https://www.googleapis.com/auth/doubleclicksearch\"\n_SERVER = \"127.0.0.1\"\n_PORT = 8080\n_REDIRECT_URI = f\"http://{_SERVER}:{_PORT}\"\n\n# The environment variable used historically to read credentials.\n_DSAPICRED_ENV = \"DSAPICRED\"\n\n\ndef main(client_secrets_path, scopes):\n \"\"\"The main method, starts a basic server and initializes an auth request.\n\n Args:\n client_secrets_path: a path to where the client secrets JSON file is\n located on the machine running this example.\n scopes: a list of API scopes to include in the auth request, see:\n https://developers.google.com/identity/protocols/oauth2/scopes\n \"\"\"\n flow = Flow.from_client_secrets_file(client_secrets_path, scopes=scopes)\n flow.redirect_uri = _REDIRECT_URI\n\n # Create an anti-forgery state token as described here:\n # https://developers.google.com/identity/protocols/OpenIDConnect#createxsrftoken\n passthrough_val = hashlib.sha256(os.urandom(1024)).hexdigest()\n\n authorization_url, unused_state = flow.authorization_url(\n access_type=\"offline\",\n state=passthrough_val,\n prompt=\"consent\",\n include_granted_scopes=\"true\",\n )\n\n os.environ[\"OAUTHLIB_RELAX_TOKEN_SCOPE\"] = \"1\"\n\n # Prints the authorization URL so you can paste into your browser. In a\n # typical web application you would redirect the user to this URL, and they\n # would be redirected back to \"redirect_url\" provided earlier after\n # granting permission.\n print(\"Paste this URL into your browser: \")\n print(authorization_url)\n print(f\"\\nWaiting for authorization and callback to: {_REDIRECT_URI}\")\n\n # Retrieves an authorization code by opening a socket to receive the\n # redirect request and parsing the query parameters set in the URL.\n code = urllib.parse.unquote(get_authorization_code(passthrough_val))\n\n # Pass the code back into the OAuth module to get a refresh token.\n flow.fetch_token(code=code)\n refresh_token = flow.credentials.refresh_token\n\n print(f\"\\nYour refresh token is: {refresh_token}\\n\")\n\n credentials = flow.credentials\n cid = credentials.client_id\n csc = credentials.client_secret\n print('# DSAPI credentials: \"client_id,client_secret,refresh_token\"')\n print('%s=\"%s,%s,%s\"' % (_DSAPICRED_ENV, cid, csc, refresh_token))\n\n\ndef get_authorization_code(passthrough_val):\n \"\"\"Opens a socket to handle a single HTTP request containing auth tokens.\n\n Args:\n passthrough_val: an anti-forgery token used to verify the request\n received by the socket.\n\n Returns:\n a str access token from the Google Auth service.\n \"\"\"\n # Open a socket at _SERVER:_PORT and listen for a request\n sock = socket.socket()\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind((_SERVER, _PORT))\n sock.listen(1)\n connection, unused_address = sock.accept()\n data = connection.recv(1024)\n # Parse the raw request to retrieve the URL query parameters.\n params = parse_raw_query_params(data)\n\n try:\n if not params.get(\"code\"):\n # If no code is present in the query params then there will be an\n # error message with more details.\n error = params.get(\"error\")\n message = f\"Failed to retrieve authorization code. Error: {error}\"\n raise ValueError(message)\n elif params.get(\"state\") != passthrough_val:\n message = \"State token does not match the expected state.\"\n raise ValueError(message)\n else:\n message = \"Authorization code was successfully retrieved.\"\n except ValueError as error:\n print(error)\n sys.exit(1)\n finally:\n response = (\"HTTP/1.1 200 OK\\n\"\n \"Content-Type: text/html\\n\\n\"\n f\"\u003cb\u003e{message}\u003c/b\u003e\"\n \"\u003cp\u003ePlease check the console output.\u003c/p\u003e\\n\")\n\n connection.sendall(response.encode())\n connection.close()\n\n return params.get(\"code\")\n\n\ndef parse_raw_query_params(data):\n \"\"\"Parses a raw HTTP request to extract its query params as a dict.\n\n Note that this logic is likely irrelevant if you're building OAuth logic\n into a complete web application, where response parsing is handled by a\n framework.\n\n Args:\n data: raw request data as bytes.\n\n Returns:\n a dict of query parameter key value pairs.\n \"\"\"\n # Decode the request into a utf-8 encoded string\n decoded = data.decode(\"utf-8\")\n # Use a regular expression to extract the URL query parameters string\n match = re.search(r\"GET\\s\\/\\?(.*) \", decoded)\n params = match.group(1)\n # Split the parameters to isolate the key/value pairs\n pairs = [pair.split(\"=\") for pair in params.split(\"&\")]\n # Convert pairs to a dict to make it easy to access the values\n return {key: val for key, val in pairs}\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=(\n \"Generates OAuth2 refresh token using the Web application flow. \"\n \"To retrieve the necessary client_secrets JSON file, first \"\n \"generate OAuth 2.0 credentials of type Web application in the \"\n \"Google Cloud Console (https://console.cloud.google.com). \"\n \"Make sure 'http://_SERVER:_PORT' is included the list of \"\n \"'Authorized redirect URIs' for this client ID.\"),)\n # The following argument(s) should be provided to run the example.\n parser.add_argument(\n \"-c\",\n \"--client_secrets_path\",\n required=True,\n type=str,\n help=(\"Path to the client secrets JSON file from the Google Developers \"\n \"Console that contains your client ID, client secret, and \"\n \"redirect URIs.\"),\n )\n parser.add_argument(\n \"--additional_scopes\",\n default=None,\n type=str,\n nargs=\"+\",\n help=\"Additional scopes to apply when generating the refresh token.\",\n )\n args = parser.parse_args()\n\n configured_scopes = [_SCOPE]\n\n if args.additional_scopes:\n print(\"Using additional scopes: \", args.additional_scopes)\n configured_scopes.extend(args.additional_scopes)\n\n main(args.client_secrets_path, configured_scopes)\n```\n\n\u003cbr /\u003e\n\n[Download generate_user_credentials.py](/static/search-ads/reporting/download/python/generate_user_credentials.py)"]]