API Authentication - example

Hi all,
I just tripped over the obsolete documentation for API authentication. To save anyone else who is rolling their own client in Python, here is how to do the authentication using an API key and a modern OAuth library.

(Just in case anyone is wondering, I’m rolling my own client because I want a REST client, not because I want a MAAS client. MAAS just happens to be the well documented and easy to use REST API that I have on hand.)

from requests_oauthlib import OAuth1Session

def perform_API_request(site, uri, key, secret, consumer_key):
    session = OAuth1Session(consumer_key,
                         resource_owner_key=key,
                         resource_owner_secret=secret,
                         signature_method='PLAINTEXT')
    url = "%s%s" % (site, uri)
    return session.get(url)

# MAAS API key = '<consumer_key>:<key>:<secret>'
response = perform_API_request('http://server/MAAS/api/2.0', '/machines/',
                               '<key>', '<secret>', '<consumer_key>')
4 Likes