Sample Python Code for the D&B Direct 2.0 API

At the DC Tech Hackathon, I had access to the Dun & Bradstreet Direct 2.0 API. Their documentation isn’t great, so I wrote a quick Python example of authenticating and requesting data (also available as a Gist):

#!/usr/bin/env python

"""Sample code for authenticating and requesting data from D&B Direct API.  See for more information.

import requests  # pip install requests

# Register at

def get_dnb_token(username, password, url=""):
    """Get a new authentication token.


    :param username: D&B username
    :type username: str
    :param password: D&B password
    :type password: str
    :returns: authentication token or "INVALID CREDENTIALS"
    :rtype: str
    r =
            "x-dnb-user": username,
            "x-dnb-pwd": password,
    return r.headers["Authorization"]

def get_rtng_trnd(duns, token):
    """ Get a D&B Rating & Trend


    :param duns: DUNS number
    :type token: str
    :param token: authentication token
    :type token: str
    :returns: dict
    :rtype: dict
    url = ""
    headers = {"Authorization": token}
    r = requests.get(url % duns, headers=headers)
    return r.json()["OrderProductResponse"]

if __name__ == '__main__':
    token = get_dnb_token(DNB_USERNAME, DNB_PASSWORD)
    sample_duns = "804735132"  # Gorman Manufacturing
    print get_rtng_trnd(sample_duns, token)

One comment on “Sample Python Code for the D&B Direct 2.0 API

  1. Thanks for your patience this weekend, Dylan! And for sharing this. We learned so much from everyone, and came away with some very useful enhancement ideas – including a library for Python and other languages.

Leave a Reply

Your email address will not be published. Required fields are marked *