Python: DNS queries with the Google API

In this article we will see how to make DNS queries with Python using the Google API.

After installing the requests module we need to pass the host name and the DNS record type as parameters of the GET request.

import requests


def get_dns_records(hostname=None, record_type='A'):
    if hostname is None:
        return None
    api_url = 'https://dns.google.com/resolve?'
    params = {'name': hostname, 'type': record_type}
    try:
        response = requests.get(api_url, params=params)
        return response.json()
    except requests.exceptions.RequestException:
        return None

The Google API will return a JSON output with the information related to our request. Usage example:

def main():
    host = input('Enter host name:')
    record = input('Enter record type: ')
    print(get_dns_records(host, record))


if __name__ == '__main__':
    main()

Possible output:

Enter host name:gabrieleromanato.com
Enter record type: NS
{'Status': 0, 'TC': False, 'RD': True, 'RA': True, 'AD': False, 'CD': False, 'Question': [{'name': 'gabrieleromanato.com.', 'type': 2}], 'Answer': [{'name': 'gabrieleromanato.com.', 'type': 2, 'TTL': 1800, 'data': 'pdns1.registrar-servers.com.'}, {'name': 'gabrieleromanato.com.', 'type': 2, 'TTL': 1800, 'data': 'pdns2.registrar-servers.com.'}], 'Comment': 'Response from 2610:a1:1025::100.'}
Back to top