In this blog post we will learn how to use REST API to interact with vCenter.
Just like NSX, vCenter provides programmatic access through REST APIs. First we will use POSTMAN for API calls, then we will use cURL. We will also take a look at vCenter API Explorer.
Using POSTMAN client
vCenter uses api-key authentication for REST API. To get authentication token we will use POST method and make API call to URL https://<vcenter-ip-or-fqdn>/api/session.
The response to this API call is 201 Created and we will get a token.
Once we have authentication token available, we can start making further API calls. VMware developer documentation is a good place to find available APIs. It is easier to search for API for any task.
You can search for API using the search bar.
https://developer.vmware.com/apis/vsphere-automation/latest/vcenter/
Here I searched APIs for datastore.
Let’s see how to get list of data stores. Click on List Datastore option to understand the API call. We will do GET operation on the following URL, https://{api_host}/api/vcenter/datastore.
This will return information about at most 2500 visible datastores in vCenter.
Let’s see how to use this API call to get list of datastores. To authenticate this API, we will use API key authentication type and use key ‘vmware-api-session-id’ the value will be token obtained in previous API call. This will be added to header. Successful API request will have 200 OK response type.
To clear authentication session we need terminate the validity of token. This is done using DELETE operation. This is equivalent to logout. The response to this is 204 No Content.
Let’s try the same steps using cURL
Let’s get session token. The response to this API call is a token. You can add -v argument to get verbose output.
root@ mngr-01:~# curl -X POST 'https://vcsa-01.corp.local/api/session' -H 'Authorization: Basic YWRtaW5pc3RyYXRvckB2c3BoZXJlLmxvY2FsOlZNd2FyZTEh' -k
"f5af3f5ceb65dec41847ba7374aea04d"root@ mngr-01:~#
Now let’s get datastore information,
root@nsx-mngr-01:~# curl -X GET 'https://vcsa-01.corp.local/api/vcenter/datastore' -H 'vmware-api-session-id: 58f2fd987ed036758ed7ef0ac646e091' -k
[{"datastore":"datastore-22","name":"stgb01","type":"VMFS","free_space":231209959424,"capacity":412048424960}]root@nsx-mngr-01:~#
This is how we can use cURL and POSTMAN to interact to vCenter using REST APIs.
vCenter API explorer
You can also use the API explorer built in vCenter to https://vcenter/apiexplorer. You can find available APIs and use the Try it Out feature to test API calls.
Here I got API call for getting list of datastores. This is very helpful and easy to search as well.