Google Cloud Web Risk Python Client

1.21.0 · active · verified Thu Apr 16

The `google-cloud-webrisk` library is the official Python client for the Google Cloud Web Risk API (current version 1.21.0). This service allows applications to check URLs against Google's continually updated lists of unsafe web resources, including phishing, malware, and unwanted software sites, to protect users and prevent the spread of harmful content. Google Cloud client libraries are actively maintained and receive regular updates to support new API features and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate the WebRiskServiceClient and use the `search_uris` method to check a URL against various threat lists (MALWARE, SOCIAL_ENGINEERING, UNWANTED_SOFTWARE). It shows examples for both a safe and a known unsafe URI. Ensure your Google Cloud credentials are set up for the client to authenticate automatically.

import os
from google.cloud import webrisk_v1
from google.cloud.webrisk_v1 import WebRiskServiceClient, ThreatType

def search_uri(uri: str, threat_types: list[ThreatType]) -> dict:
    """Checks whether a URI is on a given threatList."""
    client = WebRiskServiceClient()
    request = webrisk_v1.SearchUrisRequest(
        uri=uri,
        threat_types=threat_types,
    )
    response = client.search_uris(request=request)
    return response.threat.to_dict() if response.threat else {"threatTypes": []}

if __name__ == "__main__":
    # Ensure GOOGLE_APPLICATION_CREDENTIALS is set, e.g.:
    # export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"
    # or use `gcloud auth application-default login`
    # The client library will automatically find credentials if set.

    test_uri_safe = "http://example.com"
    # This is a known test URI for malware from Google Safe Browsing.
    test_uri_unsafe = "http://testsafebrowsing.appspot.com/s/malware.html"

    threat_types_to_check = [
        ThreatType.MALWARE,
        ThreatType.SOCIAL_ENGINEERING,
        ThreatType.UNWANTED_SOFTWARE,
    ]

    print(f"Checking safe URI: {test_uri_safe}")
    result_safe = search_uri(test_uri_safe, threat_types_to_check)
    print(f"Result for {test_uri_safe}: {result_safe}")

    print(f"\nChecking unsafe URI: {test_uri_unsafe}")
    result_unsafe = search_uri(test_uri_unsafe, threat_types_to_check)
    print(f"Result for {test_uri_unsafe}: {result_unsafe}")

view raw JSON →