Skip to main content

Example of a simple python project

Below you can see an example of a simple python project that allows you to get categories for a list of domains from a file domains.txt. To work with the code, create a text file domains.txt, add the domains there for categorization line by line and save them in one folder with a code file.

To access the API, you must use the following host(line 6): x.api.safedns.com

 
#!/usr/bin/env python3

import requests
from base64 import b64encode

url_src = "https://x.api.safedns.com/domain/"

credentials = b64encode(b"username:password").decode("ascii")  # replace username:password with your credentials

headers = {
    'Authorization': 'Basic %s' % credentials,
    'Content-Type': 'application/json'
}
domain_src = open("domains.txt", "r")
total_time = 0
while True:
    domain = domain_src.readline()
    if not domain:
        print(f'All requests were processed for {total_time} sec')
        print('ENDofFILE')
        break
    url = url_src + domain
    response = requests.get(url=url, headers=headers)
    if response.status_code == 200:
        print(domain, response.json())
        print(f'Request processing time {response.elapsed.total_seconds()} sec')
        total_time = total_time + response.elapsed.total_seconds()
    elif response.status_code == 404:
        print(f"According to our Data Base {domain} doesn't belong to any category.")
        pass
    elif response.status_code == 403:
        print("Wrong username or password, access denied")
        break
    elif response.status_code == 429:
        print("You run out of queries to x.api, wait for 1 minute")
        break

domain_src.close()