Jump to content
venkatklr

GET data from API to variable and match with value and then POST it.

Recommended Posts

  • Active Members

Hello,

 

In Python, it's really easy to work with API calls using the requests module.

 

To install it, just do:

pip install requests

Unfortunately, depending on your version, the API is largely SOAP based. The simplest way to consume VMWare's API is via one of the existing SDKs. Now, moving further and looking at a newer version of VMWare docs, we can see that there's an already developed module to interfere with it named pyvmomi. You can follow the instructions from the github to set everything up. If you follow carefully those steps you will find this https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/ which contains tons of examples.

 

Now, literally speaking, if you specifically need to play a bit with requests, you can do the following:

 

1. Import the needed modules

2. Make GET requests

3. Process the data

4. POST processed data

 

1. Import the needed modules

import requests

 

2. Make GET requests

GET_URL = 'https://httpbin.org/get'
POST_URL = 'https://httpbin.org/post'

data = requests.get(GET_URL).json()  # this will be a json data structure containing the data you need

The output of the above is:

{'args': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.18.1'},
 'origin': '86.120.146.226',
 'url': 'https://httpbin.org/get'}

 

3. Process the data

Let's suppose you want to modify the origin value into something else:

data['origin'] = 'something else'

 

4. POST processed data

r = requests.post(POST_URL, data=data)
print(r.text)

Now, the output of the above will be:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "headers": [
      "Accept", 
      "Accept-Encoding", 
      "Connection", 
      "Host", 
      "User-Agent"
    ], 
    "origin": "something else", 
    "url": "https://httpbin.org/get"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "147", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.1"
  }, 
  "json": null, 
  "origin": "86.120.146.226", 
  "url": "https://httpbin.org/post"
}

Now, regarding your unicode issue, the error was raised because the data is a unicode/str variable, which means that you first have to make it a JSON object (which is basically a dict). In my example, you can see that I already called .json() which makes sure the data is a JSON object.

 

But, if the returned data is a string, you won't be able to do that. To do that, you can use the json module:

 

import json

data = json.loads(data)

 

 

Edited by MrGrj
  • Like 1
  • Thanks 1
  • Upvote 2
Link to comment
Share on other sites

here is my code.

 

from xml.etree.ElementTree import Element, SubElement, Comment,XML
from schedularConf import EXECUTION_CONST
(Execution_Const is in different python script and here is the code.
import json
import xmltodict
import requests
from xml.etree import ElementTree
from string import Template


class EXECUTION_CONST():
    # Header for HTTP request.
    headers = {'Content-Type': 'application/xml'}
    # Availability Tests
    SCHEDULAR_LISTS = {
        " Availability Test": "https://servername/vco/api/workflows/workflowID"
    })
 



class schedule:

    def getData(self):
        try:

            list = EXECUTION_CONST.SCHEDULAR_LISTS;

            for name, url in list.iteritems():
                mainUrl = url.split("workflows")[0]+"/tasks";
                nameSch = name.split("-")[1];
                # print (nameSch)
                list = requests.get(mainUrl,auth = ('username', 'password'),verify=False).text
                print (list)
                lists = json.dumps(list)
                #print (lists)

                # for l in lists:
                #     if l == " Availability Test":
                #         print(" Availability Test is available" )
                #     else:
                #         print ("Availability Test is not available")


                # XML = '<task xmlns="http://www.vmware.com/vco"><name>'+nameSch+'</name><recurrence-cycle>one-time</recurrence-cycle><recurrence-start-date>2017-09-30T11:52:00+03:00</recurrence-start-date><workflow href="'+url+'"></workflow><start-mode>normal</start-mode></task>'
                #
                # print (XML)
                # res = requests.post(mainUrl,data=XML,headers=EXECUTION_CONST.headers,
                #                     auth = ('username', 'password'),verify=False).text
                # print  (res);

        except Exception, e:
            print e
            return ;
Edited by venkatklr
Link to comment
Share on other sites

3 hours ago, MrGrj said:

Hello,

 

In Python, it's really easy to work with API calls using the requests module.

 

To install it, just do:


pip install requests

Unfortunately, depending on your version, the API is largely SOAP based. The simplest way to consume VMWare's API is via one of the existing SDKs. Now, moving further and looking at a newer version of VMWare docs, we can see that there's an already developed module to interfere with it named pyvmomi. You can follow the instructions from the github to set everything up. If you follow carefully those steps you will find this https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/ which contains tons of examples.

 

Now, literally speaking, if you specifically need to play a bit with requests, you can do the following:

 

1. Import the needed modules

2. Make GET requests

3. Process the data

4. POST processed data

 

1. Import the needed modules


import requests

 

2. Make GET requests


GET_URL = 'https://httpbin.org/get'
POST_URL = 'https://httpbin.org/post'

data = requests.get(GET_URL).json()  # this will be a json data structure containing the data you need

The output of the above is:


{'args': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.18.1'},
 'origin': '86.120.146.226',
 'url': 'https://httpbin.org/get'}

 

3. Process the data

Let's suppose you want to modify the origin value into something else:


data['origin'] = 'something else'

 

4. POST processed data


r = requests.post(POST_URL, data=data)
print(r.text)

Now, the output of the above will be:


{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "headers": [
      "Accept", 
      "Accept-Encoding", 
      "Connection", 
      "Host", 
      "User-Agent"
    ], 
    "origin": "something else", 
    "url": "https://httpbin.org/get"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "147", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.1"
  }, 
  "json": null, 
  "origin": "86.120.146.226", 
  "url": "https://httpbin.org/post"
}

Now, regarding your unicode issue, the error was raised because the data is a unicode/str variable, which means that you first have to make it a JSON object (which is basically a dict). In my example, you can see that I already called .json() which makes sure the data is a JSON object.

 

But, if the returned data is a string, you won't be able to do that. To do that, you can use the json module:

 


import json

data = json.loads(data)

 

 

MrGrj,

Thank you for providing article. it is very informative.

I am getting dic type output after adding .json() to GET request.

my requirement is first check for (Availability Test) for multiple urls and then post to vro. please refer XML (I am using that to create task in vro) here nameSch is for the name create like Availability and href="'+url+ is the server url .  Please let me know how can do it.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...