How to do a POST and GET in VBscript? - chilkat

I am new to VBscript and am looking for some help to do a POST to an API and pass it a JSON string containing id, password and a scope, then get an answer and parse it. Here is the call I need to make:
POST https://integrations.ezyvet.com/call/getAccessToken { "partner_id": "id8888", "client_id": "id12345", "client_secret": "secret12345", "grant_type": "client_credentials", "scope": “read-diagnosticresult,read-diagnosticresultitem, read-diagnosticrequest,write-diagnosticresult,write-diagnosticresultitem" }
Here is my code:
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set outFile = fso.CreateTextFile("c:\temp\JSONoutput.txt", True)
set json = CreateObject("Chilkat_9_5_0.JsonObject")
jsonStr = "{""partner_id"": ""id8888"", ""client_id"": ""id12345"", ""client_secret"": ""secret12345"", ""grant_type"": ""client_credentials"", ""scope"": ""read-diagnosticresult,read-diagnosticresultitem, read-diagnosticrequest,write-diagnosticresult,write-diagnosticresultitem""}"
success = json.Load(jsonStr)
If (success <> 1) Then
outFile.WriteLine(json.LastErrorText)
WScript.Quit
End If
set http = CreateObject("Chilkat_9_5_0.Http")
I need to make my POST here and get a response and am not sure how. Please help.
Thanks a million.

Hi and welcome to stack overflow!
You have tagged chilkat in your question, however you haven addressed it anywhere in the body or the tittle of it, so I was not sure if answer pointing this or not, so I will try to make a bit of both.
without chilkat
You can do this in pure vbs by using ajax, the short answer would be
Dim request
Set request = CreateObject("MSXML2.XMLHTTP")
request.open "GET", "http://www.example.com", False '(1)
request.send infoToSend '(2)
'(3)
Here you set eather "POST" or "GET"
infoToSend contains the information data, formatted as "key=value&key2..."
request.responseText here contains the servers answer as text, parse it as json if you need
You can find information here.
with chilkat
If you still want to use chilkat the main documentation of the http object is here, here is everything you need. If you need an example tho here I've found two:
making a request: https://www.example-code.com/vbscript/http_xmlHttpRequestVerbs.asp
sending a json: https://www.example-code.com/vbscript/http_put_json.asp
I wont paste it here because its too long but the core part of your interest is that you is:
set request = CreateObject("Chilkat_9_5_0.HttpRequest") '(1)
request.HttpVerb = "PUT" '(2)
success = request.LoadBodyFromString(xmlStr,"utf-8") '(3)
Set response = http.SynchronousRequest(endpointDomain,endpointPort,endpointSsl,request)' (4)
you have to create a httpRequest
you set here eather get or post
3.you load here your content, it is your json or what you will send but formatted appropiately
here you have response contain a HttpResponse object with the result
documentation on the HttpResponse, and the HttpRequest

Related

Postman - Use part of the response data from one test in another test

I require help to execute a postman test which requires a response output from another test. I have checked with various forums but a solution is not available for this particular scenario.
Example
Test 1 response:
{
"items": [
{
"email": "archer+qa01#gmail.com",
"DocumentName": "tc",
"type": "URL",
"url": "https://localhost:8443/user/terms?statusno=a5f2-eq2wd3ee45rrr"
}
]
}
Test 2:
I need to use only the a5f2-eq2wd3ee45rrr part of the response data from Test 1, this can be seen in the url value above. I need to use this value within Test 2
How can I make this work with Postman?
Not completely sure what the response data format is from the question but if it's a simple object with just the url property, you could use something simple like this:
var str = pm.response.json().url
pm.environment.set('value', str.split('=', 2)[1])
This will then set the value you need to a variable, for you to use in the next request using with the {{value}} syntax in a POST request body or by using pm.environment.get('value') in one of the test scripts.
Edit:
If the url property is in an array, you could loop through these and extract the value that way. This would set the variable but if you have more than 1 url property in the array it would set the last one it found.
_.each(pm.response.json(), (arrItem) => {
pm.environment.set('value', arrItem[0].url.split('=', 2)[1])
})
If you get JSON response and then send JSON in body, I would do the following:
1) In test script(javascript):
var JsonBody = pm.response.json();
var strToParse = JsonBody.url;
var value = strToParse.slice(indexOf("?status=")+"?status=".length);//parse string
//manually but you can google for a better solutions.
pm.environment.get("varName" , value)
2) You can use it! In scripts like: pm.environment.get("varName"), and everywhere else using {{varName}}

Pass dynamic value to url in Postman

I have 2 requests
1st Request
After did my first request, I get the response where I can parse for a taskId
In my test tab, I will then parse and store it like this
let taskId = pm.response.json().body.result[0].data.task
console.log(taskId)
I can see taskId printing in my console as 938
2nd Request
I require making a GET with this dynamic URL with the taskId that I got from the first one
http://localhost:3000/fortinet/monitor/{{taskId}}
So I set the above URL , set the HTTP verb to GET
in my Pre-request Script tab, I did this
let taskId = pm.globals.get("taskId")
Result
ReferenceError: taskId is not defined
Image Result
How can I debug this further?
The most suggested way is to use :key as in
http://localhost:3000/fortinet/monitor/:taskId
See the colon before taskId. The reason being, URI values sometimes many not be environment dependent. So, based on the usecase, you can use like I said or {{taskId}}
You have to set variable, but you are doing it wrong.
try this:
pm.globals.set("taskID", pm.response.json().body.result[0].data.task)
more you can read here:
https://learning.postman.com/docs/postman/variables-and-environments/variables/
Please note, that URL which ends with resource identified like https://example.com/:pathVariable.xml or https://example.com/:pathVariable.json will not work.
You can go with https://example.com/:pathVariable with Accept: application/json header.
For passing dynamic value, first you have to set it in environment or global variable in Tests tab because tests runs after request and you will get response value after request sent, but because you get response in json you have to first parse it, so what you can write in Tests tab is as follows:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("taskId", jsonData.token); // OR
postman.setGlobalVariable("taskId", jsonData.token);
Then you can use taskId as {{taskId}} wherever you want in url parameters or in request body or form data wherever.
If you want to know in detail how to extract data from response and chain it to request then you can go to this postman's official blog post which is written by Abhinav Asthana CEO and Co Founder of Postman Company.

Why does this request return an empty string?

I have the following function which makes a get request to a url.
def fetch_data(session = None):
s = session or requests.Session()
url = 'http://www.moldelectrica.md/utils/load4.php'
response = s.get(url)
print response.status_code
data = response.text
return data
I expect to get a string back in the form.
169,26,0,19,36,151,9,647,26,15,0,0,0,0,0,150,7,27,-11,-27,-101,-19,-32,-78,-58,0,962,866,96,0,50.02
But instead I get an empty unicode string. The status code returned is 200.
I've looked at the request headers but nothing in them suggests that any headers will require being set manually. Cookies are used but I think the session object should handle that.
Figured it out. As I said this url provides data for a display so it wouldn't normally be visited directly. Usually it would be requested by the display page and that page would provide a cookie.
So the solution is to make a request to the display url then reuse the session and make another request to the data url.

OAuth1Session Encoding of URL Django

Alright, I need some assistance with what I think is an easy question, but after digging for quite a while I'll leave it to you brilliant people to show me why I'm not!
I'm attempting to access a provider api, with the URL I'm attempting to access being: .../proposals/AnotherTestProposal/city_furniture/items?filter=description$CONT"Ag" :: this is the way they want it passed, and it should return all items who's descriptions contain the string "Ag". I know I have two of those currently.
I'm using Django 1.9.4, and requests_oauthlib to create an OAuth1Session, I'm doing this successfully also, because I can access resources without URL params. The trouble is I can't get the "?filter=description..." part to encode properly and it's giving me a 401.
When I render the .contents to HTML I get:
{"status": 404, "message": "", "data": [], "arguments": {"id": "items?filter=description$CONT\"Ag\"", "collection": "city_furniture"}}
which is telling telling me that the "AG" part is being escaped, which I don't want. As in: I don't want \"Ag\", I want "Ag".
So, my question: how can I pass the URL, with params, so they are not containing the slashes as these are causing the URL to be invalid and therefore keeping me from accessing the data correctly?
Other, possibly irrelevant info:
The params part of the URL string I'm passing to the OAuth1Session object now is: '/city_furniture/items%3Ffilter%3Ddescription%24CONT%22Ag%22'
An example of filtering from the API's website: proposals/master/roads/items?filter=description$CONT"highway"
I tried passing an 'encoding' arg to .get (in order to change the encoding used by to_native_string) but requests rejected it saying it was an invalid arg
Per comments, some additional code.
Using a function name get_protected_code() to get the OAuth info passed correctly, then in views.py:
api_filter_url = settings.IW_API_MODEL_COLLECTION + '/' + model_id + '/' + settings.IW_API_PROPOSAL_COLLECTION + '/' + proposal_name + '/city_furniture/items%3Ffilter%3Ddescription%24CONT%22Ag%22'
json_model_info_pull = get_protected_data(api_filter_url)
find_vendor = json_model_info_pull.content
def get_protected_data(url_str):
## ...stuffs to create OAuth1Session...
adsk_pull = OAuth1Session(key,
client_secret=secret,
resource_owner_key=oauth_token_use,
resource_owner_secret=oauth_token_secret_use,
)
headers = {'accept': 'application/vnd.autodesk.infraworks-v1+json'}
api_url = settings.ADSK_IW_INFO_BASE_URL + url_str
json_model_info_pull = adsk_pull.get(api_url, headers=headers)
return json_model_info_pull
Looks like you're passing the parameters incorrectly by appending them to the end of the URL in URL-encoding, which requests is respecting as intentional, and the API endpoint is translating in an unintended manner.
From the documentation for requests, you should provide a params keyword argument to requests.get: a dict containing the key-value pairs that should be encoded and sent as the query string for the request. For example, to run a query against the GitHub API, we can pass an API token as a query parameter:
requests.get('http://api.github.com/user',
params={ 'access_token' : MY_OAUTH_TOKEN })
The resultant request will contain a query string with an access_token parameter set to the value stored in MY_OAUTH_TOKEN and escaped properly, as needed. (Such tokens typically contain = characters, for example, that are invalid inside query string values.)

Receiving SOAP notifications from eBay api into ASP variable?

I am trying to receive ebay api transaction notifications into an ASP hosted on a web server. The notifications are sent as SOAP messages and can be sent to a URL with a query string. Notifications must be responded to with HTTP 200 OK. I would like the notification to land inside a variable so that I can parse it and send it on to the next part of the system.
http://developer.ebay.com/DevZone/guides/ebayfeatures/Notifications/Notifications.html#ReceivingPlatformNotifications
In the documentation they mention that this is possible, but the sample they give goes the route of subscribing to an email server. This ASP would not necessarily need to make SOAP requests, just accept SOAP messages from the ebay servers.
I am studying ASP, SOAP, and query strings, but a little guidance would be truly appreciated. Thanks!
This should be pretty straight forward, your Classic ASP page becomes the endpoint for the eBay Notification API (as long as you have configured it to send notifications and what URL to send them to).
You should be able to test this with a simple Classic ASP page
<%
Dim isPost: isPost = (UCase(Request.ServerVariables("REQUEST_METHOD") & "") = "POST")
Dim hasSoapAction
'Is it a HTTP POST?
If isPost Then
'Do we have a SOAPACTION header (check both because
'it can be either HTTP_ or HEADER_ depending on IIS version)?
hasSoapAction = ( _
Len(Request.ServerVariables("HEADER_SOAPACTION") & "") > 0 Or _
Len(Request.ServerVariables("HTTP_SOAPACTION") & "") > 0 _
)
If hasSoapAction Then
'Process the notification here.
'Use Request.BinaryRead to read the SOAP
End If
'Let eBay know we have received and processing the message.
Response.Status = "200 OK"
Else
'Return method not allowed
Response.Status = "405 Method Not Allowed"
End If
Response.End
%>
You might also want to check REMOTE_HOST to make sure that you are only getting sent messages for the expected source (this isn't bulletproof though as the information can be spoofed).
Useful Links
Accessing a request's body (great existing answer that explains how to use Request.BinaryRead() to read the content and convert it to a string which you can then use in a variable or for parsing with XMLDocument.LoadXML()).
How to generate MD5 using VBScript in classic ASP? (If you want to look at a way of verifying the MD5 signature)
This is what i have so far in my notifications.asp. When I try to send it a basic SOAP post through Postman nothing is happening. Does this look like it should work?
I tested this without the If statements checking for SOAP headers, and I posted just regular string data and it works. So the binary to string conversion and output to file is all good. Now I just need to test it with actual ebay api notifications. ;-)
<%
Function BytesToStr(bytes)
Dim Stream
Set Stream = Server.CreateObject("Adodb.Stream")
Stream.Type = 1 'adTypeBinary
Stream.Open
Stream.Write bytes
Stream.Position = 0
Stream.Type = 2 'adTypeText
Stream.Charset = "iso-8859-1"
BytesToStr = Stream.ReadText
Stream.Close
Set Stream = Nothing
End Function
Dim isPost: isPost = (UCase(Request.ServerVariables("REQUEST_METHOD") & "") = "POST")
Dim hasSoapAction
'Is it a HTTP POST?
If isPost Then
'Do we have a SOAPACTION header?
hasSoapAction = (Len(Request.ServerVariables("HEADER_SOAPACTION") & "") > 0)
If hasSoapAction Then
'Process the notification here.
'Use Request.BinaryRead to read the SOAP
If Request.TotalBytes > 0 Then
Dim lngBytesCount, text
lngBytesCount = Request.TotalBytes
text = BytesToStr(Request.BinaryRead(lngBytesCount))
dim fs, tfile
set fs=Server.CreateObject("Scripting.FileSystemObject")
set tfile=fs.CreateTextFile("C:\inetpub\wwwroot\ASPtest\notifications.txt")
tfile.WriteLine(text)
tfile.Close
set tfile=nothing
set fs=nothing
End If
End If
'Let eBay know we have received and processing the message.
Response.Status = "200 OK"
Else
'Return method not allowed
Response.Status = "405 Method Not Allowed"
End If
Response.End
%>