This entry is part 3 of 3 in the series Consuming RESTful APIs in

As we continue our journey of consuming RESTful APIs with different scripting and programming languages we come to Python – and not soon enough – Python, although I know hardly anything about, is one of the easiest languages to consume a RESTful API with. Support for consuming APIs in Python comes from the “requests” library – which needs to be installed separately from Python itself.  Python libraries are similar to gems in Ruby, or to reference assemblies in c# if you are following along…  To install it, simply run the following command…

pip install requests

Once installed consuming APIs is as easy as simply importing the required libraries and making the calls – super easy stuff.  Let’s have a look at the same example we have been using throughout this series of assigning a VM to an SLA Domain.

The first thing we need to do is import some libraries in order to make things easier on us…

import json
import requests
import base64

Next, let’s set up some variables to hold our authentication as well as our vm/sla domain names.

user = ""
passwd = "SuperSecret"
auth_values = (user, passwd)
vmname = "MPRESTON-VM1"
slaname = "Gold AWS DND"

As far as sending an actual request, it’s as easy as calling the appropriate method with the requests library and parsing the response – for example, to get the VM id within Rubrik of our desired VM we can just send our URI and authentication info to the vmware/vm resource as shown below…  As you can see, we don’t have any need to manually encode the authentication in Python as the requests library will do it for us…

response = requests.get(""+vmname, auth=auth_values, verify=False)
vmid = response.json()['data'][0]['id']

Furthermore, to get our SLA Domain ID, it’s pretty much the same call – just targetting the sla_domain resource…

response = requests.get(""+slaname, auth=auth_values, verify=False)
slaid = response.json()['data'][0]['id']

Finally, let’s have a look at a request with a body – again, the update of a VMs SLA Domain requires a patch request – we accomplish this with the following code, targeting our specific VM ID in the URI.  This time, we append some json as an attribute on the end of the patch function, passing the value of the configuredSlaDomainId

response = requests.patch(""+vmid, auth=auth_values, verify=False, json={"configuredSlaDomainId": slaid })

So yeah, that’s about it with RESTful APIs and Python – pretty simple stuff – it’s easy to tell why so many people chose to automate with this language – being able to execute an API call in one line is pretty nice compared to some of the other languages we have looked at. Python is certainly a language I want to dive further into given the time!  Thanks for reading!

Series Navigation<< Consuming RESTful APIs with c#