Reader small image

You're reading from  Mastering PowerCLI

Product typeBook
Published inOct 2015
Reading LevelIntermediate
PublisherPackt
ISBN-139781785286858
Edition1st Edition
Languages
Right arrow
Author (1)
Sajal Debnath
Sajal Debnath
author image
Sajal Debnath

Sajal Debnath is a highly certified Cloud computing technocrat with more than 12 years of experience in virtualized data center design, Cloud computing, and BC/DR solutions. He is an EMCISA, VCAP-DCD/DCA, VCAP-CID/CIA, RHCE 4/5/6, RHCVA, Openstack, and ITIL certified person. He is presently associated with VMware Software India Pvt. Ltd. as a senior system engineer. Previously, he worked with France Telecom, Hewlett Packard, and many more in multiple roles. He is involved in prestigious Indian government projects, such as National Cloud, Digital Locker, and so on.
Read more about Sajal Debnath

Right arrow

Chapter 10. Using REST APIs

In the previous chapter, we discussed how to manage vSphere APIs using PowerCLI. In this chapter, we are going to cover another interesting and helpful topic, REST APIs. In the first part of this chapter, we are going to discuss REST APIs in brief and see how we can manage them using PowerShell. In the next part, we are going to discuss how to manage the vRealize Automation Center by utilizing REST APIs through PowerShell.

We are going to cover the following topics in this chapter:

  • Introducing REST APIs

  • Introduction to JSON

  • The Invoke-RestMethod cmdlet

  • vRealize Automation REST APIs

  • Authenticating and getting a vRealize Automation token

  • Managing tenants

  • Manage machines

  • Managing approvals

  • Managing provisioned resources

  • Managing network profiles

So let's start our discussion on REST APIs and find out more about them.

Introducing REST APIs


Representational State Transfer (REST or ReST) is a software architecture style for building scalable Web services. It relies on a stateless, client-server, and cacheable communications protocol. REST is a simple way to manage communication between independent systems. It is inspired by HTTP and HTTP is used in virtually all cases (though it is not limited to HTTP only). Actually, the four most common actions, view, create, edit, and delete, map directly to the HTTP verbs that are already implemented: GET, POST, PUT, and DELETE. So in the case of REST APIs, we use these verbs a lot.

Before we go ahead and talk about the verbs, let's discuss a bit more about REST APIs. The term REST was coined by Roy T. Fielding in his PhD thesis (you can have a look at the thesis at http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm). The primary idea behind REST is to have one standard interface for any service. Instead of exposing an interface with methods, we expose a few...

Introducing JSON


So far, we talked about REST APIs, the resources that we manage through REST APIs, and the verbs using which we typically manage the resources. But the point is whenever we talk to a resource, we either gather some information about it or do something on it by passing some information to the handling method. Obviously, data passing between a client and server is the main objective. We discussed how we can pass data between client and server, but how do we ensure that the client and server understand each other, the data returned by server is in the same format that the client is expecting, or vice versa? As mentioned earlier, different types of data format are supported since REST is not a protocol. It depends on the protocol that you are using. If the protocol supports a data format, REST can work with it. Two of the frequently used formats are JSON and XML. Because of its simplicity, JSON has become very popular as the format of choice in RESTful services.

JSON (short...

The Invoke-RestMethod cmdlet


The Invoke-RestMethod is the PowerShell cmdlet using which we can send an HTTP or HTTPS request to a RESTful Web service. This is the single most important cmdlet for this chapter, as we are going to manage the REST APIs of vRealize Automation using this cmdlet. The syntax for the cmdlet is as follows:

Invoke-RestMethod [-Uri] <Uri> [-Body <Object>] [-Certificate 
<X509Certificate>] [-CertificateThumbprint <String>] [-ContentType 
<String>] [-Credential <PSCredential>] [-DisableKeepAlive] [-Headers 
<IDictionary>] [-InFile <String>] [-MaximumRedirection <Int32>] [-
Method <WebRequestMethod>] [-OutFile <String>] [-PassThru] [-Proxy 
<Uri>] [-ProxyCredential <PSCredential>] [-
ProxyUseDefaultCredentials] [-SessionVariable <String>] [-TimeoutSec 
<Int32>] [-TransferEncoding <String>] [-UseDefaultCredentials]   [-
UserAgent <String>] [-WebSession <WebRequestSession...

vRealize Automation REST APIs


So far, we talked about REST APIs and how we can work with them in PowerShell. In this section, we are going to talk about vRealize Automation (vRA) REST APIs as well as how and where we can access them.

There are two documents that are related to vRA REST APIs and they will be very helpful to us: Programming Guide and REST API Reference. They can be found at https://www.vmware.com/support/pubs/vcac-pubs.html. From the link, you can either download the PDF version or explore them in the browser. While the second document provides the reference to all the available REST API in vRA, the first one provides a programming guide to using these REST APIs to manage the vRA environment. While exploring the RESTful services for vRA, we can see that the vRA REST API provides consumer-level, administrator-level, and provider-level access to the service catalog of the same services that are available from the user interface. Whenever a service request is done with a resource...

Authenticating and getting a vRA token


To manage the vRA environment through REST API, we will need HTTP bearer tokens in request headers for the authentication of requests. So we get a bearer token and use that instead of supplying a user ID and password each and every time we want to connect to vRA. Once we get a bearer token, we can use it until it expires or we purposefully delete it. By default, a bearer token is valid for 24 hours. If for some reason you need to change the default duration, follow the instructions provided in the following Web page: http://pubs.vmware.com/vra-62/index.jsp#com.vmware.vra.programming.doc/GUID-FDB47B40-F651-4FBD-8D1E-AC6FC8FA7A96.html.

For example, if for security purposes, you want to change the default validity time to a smaller number of hours.

To get a bearer token, we need to POST a request to https://<vRA>/identity/api/tokens. Since we would use the HTTP protocol, we need to build Header and the Body. We need to pass two parameters in Header...

Managing tenants


Since we have the token, we can start exploring the vRA environment. We will start by managing the tenants. First, let's get a list of existing tenants. From now onwards, we need to provide authorization for working with the resources. Since we already have a token, we need to pass the authorization as a parameter in the header itself. We will use the following format:

Authorization: Bearer $token

Here, $token holds the authorization token. For this, we will build out the header. So, define a new object:

PS C:\>$headers = New-Object 
"System.Collections.Generic.Dictionary[[String],[String]]"

Next, add the components of the header:

PS C:\> $headers.Add('Accept', 'application/json')
PS C:\> $headers.Add('Authorization', "Bearer $token")

Note the Authorization parameter; there needs to be a space between bearer and token. Next, get the information:

PS C:\> Invoke-RestMethod -Method Get -Uri 
"https://vra.lab.com/identity/api/tenants" -Headers $headers | FL

Putting...

Managing machines


Now, we will look at ways to manage the machines in a tenant. For this, we will start by checking a list of all available catalog items.

Listing shared and private catalog items

To get a list of catalog items, first build the header:

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Content-Type', 'application/json')
$headers.Add('Authorization', "Bearer $token")

Next, simply query the resources:

PS C:\> (Invoke-RestMethod -Method Get -Uri 
"https://vra.lab.com/catalog-
service/api/consumer/entitledCatalogItems" -Headers 
$headers).Content.catalogItem[0] | ConvertTo-Json

We get a list of items. For readability and easy understanding, we will select only one output. Since the output is a PowerShell object (in this case, it is an array of objects), we are just selecting the first element and then converting it to JSON format:

[
    {
        "id":  "bda84bcb-d3f6-4332-8781-89d146ef5e28",
        "version":  2,
        "name": ...

Managing approvals


In this section, we will discuss how to manage approvals in the vRA environment. First, let's see a list of workitems that are available. In the following command, I am just getting a list of the content:

PS C:\> (Invoke-RestMethod -Method Get -Uri 
"https://vra.lab.com/workitem-service/api/workitems" -Headers $headers).content | ConvertTo-Json

Part of the output is provided here:

{
    "@type":  "WorkItem",
    "id":  "2a11c987-dd8f-4a2d-a15a-b048ca64d729",
    "version":  1,
    "workItemNumber":  2,
    "assignees":  [
                      {
                          "principalId":  "vradmin@lab.com",
                          "principalType":  "USER"
                      }
                  ],
    "subTenantId":  "5c91a267-581a-4e00-9895-cf6e9c6b313a",
    "tenantId":  "vsphere.local",
    "callbackEntityId":  "2a11c987-dd8f-4a2d-a15a-b048ca64d729",
    "workItemType":  {
           "id":  "com.vmware.csp.core.approval.workitem.request",
                      ...

Managing provisioned resources


In this section, we will discuss how to manage provisioned resources. To get a list of all provisioned resources, we can use the following command. Note the page number and limit parameter, and change them according to your requirements:

PS C:\> (Invoke-RestMethod -Method Get -Uri 
"https://vra.lab.com/catalog-
service/api/consumer/resources/?page=1&limit=20" -Headers 
$headers).Content | ConvertTo-Json

Part of the output is provided here:

{
    "@type":  "CatalogResource",
    "id":  "4998df9f-1ada-4cdb-843c-a7d61a256e94",
    "iconId":  "bda84bcb-d3f6-4332-8781-89d146ef5e28",
    "resourceTypeRef":  {
                            "id":  "Infrastructure.Virtual",
                            "label":  "Virtual Machine"
                        },
    "name":  "vc-01",
    "description":  "TEST machine",
    "status":  "ACTIVE",
    "catalogItem":  {
                        "id":  "bda84bcb-d3f6-4332-8781-
                        89d146ef5e28",
        ...

Managing network profiles


Let's see how to manage network profiles in the vRA environment. We will start this discussion with the procedure on how to get a list of network profiles.

For this, we need to query the https://$host/iaas-proxy-provider/api/network/profiles URL and the method we need to use is Get. We can bring everything together and get the information by running the following command.

PS C:\> Invoke-RestMethod -Method Get -Uri "https://vra.lab.com/iaas-
proxy-provider/api/network/profiles" -Headers $headers | ConvertTo-
Json
{
    "links":  [

              ],
    "content":  [
                    {
                        "@type":  "ExternalNetworkProfile",
                        "id":  "be64956f-52d3-4eb7-9a9e-
                        29a7db7372b0",
                        "name":  "Cloud-External",
                        "description":  "",
                        "createdDate":  "2015-08-07T12:58:16.000Z",
                        "lastModifiedDate":  "2015-08-
     ...

Summary


In this chapter, we provided a short conceptual discussion on REST API and how we can use PowerShell to manage RESTful services. Next, we discussed how to manage a vRA environment using the PowerShell and REST APIs.

In the next chapter, we are going to talk about building a Windows GUI, and how we can utilize PowerShell to build a frontend GUI for our backend scripts.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering PowerCLI
Published in: Oct 2015Publisher: PacktISBN-13: 9781785286858
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
Sajal Debnath

Sajal Debnath is a highly certified Cloud computing technocrat with more than 12 years of experience in virtualized data center design, Cloud computing, and BC/DR solutions. He is an EMCISA, VCAP-DCD/DCA, VCAP-CID/CIA, RHCE 4/5/6, RHCVA, Openstack, and ITIL certified person. He is presently associated with VMware Software India Pvt. Ltd. as a senior system engineer. Previously, he worked with France Telecom, Hewlett Packard, and many more in multiple roles. He is involved in prestigious Indian government projects, such as National Cloud, Digital Locker, and so on.
Read more about Sajal Debnath