[Guide] vSphere REST API - Intro
Getting started with the vSphere API
The vSphere REST API, introduced in vSphere 6.5, represents a significant leap forward in managing and automating VMware environments. This modern, developer-friendly interface offers a more streamlined approach to interacting with vSphere compared to its predecessor, the SOAP-based vSphere Web Services API.
Key features of the vSphere REST API include:
- RESTful architecture: It follows REST principles, using standard HTTP methods (GET, POST, PUT, DELETE) for operations.
- JSON-based: Requests and responses use JSON format, making it easier to parse and work with data.
- Simplified interaction: The API is designed to be more intuitive and easier to use than the older SOAP-based API.
To get started with the vSphere REST API, you can use the built-in API Explorer in vCenter Server, accessible at https://< vcenter.example.com >/apiexplorer. This tool provides interactive documentation and allows you to test API calls directly from your browser.
Endpoints
The vSphere API provides several key endpoints for interacting with different aspects of the vSphere environment:
API | Endpoint |
---|---|
vSphere Automation API (REST) | https://< vcenter.example.com >/api |
VIM JSON API (New in vSphere 8.0 Update 1) | http://< vcenter.example.com >/sdk/vim25/8.0.1.0 |
vSphere Web Services API (SOAP) - deprecated | https://< vcenter.example.com >/sdk |
vCenter Server Appliance Management API | https://< vcenter.example.com >:5480/rest |
API Explorer: | https://< vcenter.example.com >/apiexplorer |
vSphere Developer Center
Within your vCenter there a some tools to help you interacting with the vSphere API provided by your vCenter. So you only use API Call that are actually available for your infrastructure.
Code Capture
With Code Capature you can capture a manual configuration and vSphere will give you the code in various languages for that configuration.
Activate Code Capture
From the burger menu, click Developer Center and go to the Code Capture tab. Now a Red Recording Buttons appears on the top right. To start a recording, navigate to your desired pane and click the red record button in the top pane. To start recording immediately, click Start Recording. While a recording is in progress, the red record button in the top pane blinks.
While the recording is in progress, do your things in the GUI (like edit a VM, add a second Disk). After your manual configuration has been made, stop the recording. Now you will be presented with a sample Code.
API Explorer
To explore the vSphere APIs, you can access the API Explorer directly in your vCenter. From the burger menu, click Developer Center and select the API Explorer tab.
Or Directly via: https://< vcenter.example.com >/apiexplorer
Ansible
Ansible can interact with vSphere via Module (mostly the Community.Vmware' module is used). But not all Automation Tasks can be done via this module. Sometimes direct API Calls via the 'uri' module have to be made for certain tasks.
Example Ansible vSphere REST API Call
1- name: Basic vSphere API REST Call
2 hosts: localhost
3 gather_facts: no
4 vars:
5 vcenter_hostname: "vcenter.example.com"
6 vcenter_username: "[email protected]"
7 vcenter_password: "your_password_here"
8
9 tasks:
10 - name: Get vCenter session token
11 uri:
12 url: "https://{{ vcenter_hostname }}/rest/com/vmware/cis/session"
13 method: POST
14 validate_certs: no
15 force_basic_auth: yes
16 user: "{{ vcenter_username }}"
17 password: "{{ vcenter_password }}"
18 register: login_result
vSphere managedObject ID
The Managed Object ID (MOID), also known as the Managed Object Reference ID (MORef ID), is a VMware internal identifier that is generated by vSphere when new objects like VMs are created, or when ESXi hosts are added to vCenter. MOIDs are used to uniquely identify VMware components and are used by all VMware solutions to reference objects within vCenter.
MOIDs typically consist of a prefix indicating the object type, followed by a number. For example, "vm-1024" for a virtual machine or "datacenter-1001" for a datacenter
A lot of times you will need to interact with the MOIDs. You can browse them in your vCenter:
- https://< vcenter.example.com >/mob
To get those MOIDs here is an example:
1---
2- name: Gather ESXi Host Info using vSphere API
3 hosts: localhost
4 gather_facts: no
5 vars:
6 vcenter_hostname: "vcenter.example.com"
7 vcenter_username: "[email protected]"
8 vcenter_password: "your_password_here"
9 cluster_name: "your_cluster_name"
10
11 tasks:
12 - name: Get vCenter session token
13 uri:
14 url: "https://{{ vcenter_hostname }}/rest/com/vmware/cis/session"
15 method: POST
16 validate_certs: no
17 force_basic_auth: yes
18 user: "{{ vcenter_username }}"
19 password: "{{ vcenter_password }}"
20 register: login_result
21
22 - name: Get cluster MoID
23 uri:
24 url: "https://{{ vcenter_hostname }}/rest/vcenter/cluster"
25 method: GET
26 validate_certs: no
27 headers:
28 vmware-api-session-id: "{{ login_result.json.value }}"
29 register: clusters_result
30
31 - name: Set cluster MoID
32 set_fact:
33 cluster_moid: "{{ clusters_result.json.value | selectattr('name', 'equalto', cluster_name) | map(attribute='cluster') | first }}"
34
35 - name: Get ESXi hosts in cluster
36 uri:
37 url: "https://{{ vcenter_hostname }}/rest/vcenter/host?filter.clusters={{ cluster_moid }}"
38 method: GET
39 validate_certs: no
40 headers:
41 vmware-api-session-id: "{{ login_result.json.value }}"
42 register: hosts_result
43
44 - name: Display ESXi host information
45 debug:
46 msg: "Host Name: {{ item.name }}, Host MoID: {{ item.host }}"
47 loop: "{{ hosts_result.json.value }}"
48
49 - name: Get detailed host info
50 uri:
51 url: "https://{{ vcenter_hostname }}/rest/vcenter/host/{{ item.host }}"
52 method: GET
53 validate_certs: no
54 headers:
55 vmware-api-session-id: "{{ login_result.json.value }}"
56 register: host_details
57 loop: "{{ hosts_result.json.value }}"
58
59 - name: Display detailed host information
60 debug:
61 msg: "Host: {{ item.json.value.name }}, Connection State: {{ item.json.value.connection_state }}, Power State: {{ item.json.value.power_state }}"
62 loop: "{{ host_details.results }}"
This approach using the uri module gives you more direct control over the API calls and allows you to customize the requests and responses as needed. It's particularly useful when you need to perform actions that aren't covered by existing Ansible modules or when you want to work directly with the vSphere REST API.
Powershell
If PowerCLI does not have the function you are looking for, you could also you native Powershell to interact with the vSphere API.
This script does the following:
- Sets up the vCenter server details.
- Adds a function to ignore SSL certificate errors (remove this in production environments).
- Authenticates with the vCenter server to get a session token.
- Uses the session token to make an API call to retrieve a list of VMs.
- Displays the results in a table format.
1# vCenter server details
2$vcServer = "vcenter.example.com"
3$vcUser = "[email protected]"
4$vcPass = "YourPassword"
5
6# Ignore SSL certificate errors (remove in production)
7if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type) {
8 add-type @"
9 using System.Net;
10 using System.Security.Cryptography.X509Certificates;
11 public class ServerCertificateValidationCallback {
12 public static void Ignore() {
13 ServicePointManager.ServerCertificateValidationCallback +=
14 delegate (
15 Object obj,
16 X509Certificate certificate,
17 X509Chain chain,
18 SslPolicyErrors errors
19 ) { return true; };
20 }
21 }
22"@
23}
24[ServerCertificateValidationCallback]::Ignore()
25
26# Authenticate and get session token
27$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($vcUser + ':' + $vcPass))
28$headers = @{
29 'Authorization' = "Basic $auth"
30}
31$sessionUrl = "https://$vcServer/rest/com/vmware/cis/session"
32$response = Invoke-RestMethod -Uri $sessionUrl -Method Post -Headers $headers
33$sessionId = $response.value
34
35# Set up headers for subsequent requests
36$headers = @{
37 'vmware-api-session-id' = $sessionId
38}
39
40# Make an API call (e.g., get list of VMs)
41$vmsUrl = "https://$vcServer/rest/vcenter/vm"
42$vms = Invoke-RestMethod -Uri $vmsUrl -Method Get -Headers $headers
43
44# Display results
45$vms.value | Format-Table