Sending values as parameters in HTTP GET using VBA request - vba

So I am trying to send a basic request to a new API I'm testing out with the following script:
Sub CalcDemo()
TargetURL = "https://my-api-url.com"
Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
HTTPReq.Open "GET", TargetURL, False
HTTPReq.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
postData = "user=myUsername&password=myPassword"
HTTPReq.send (postData)
MsgBox (HTTPReq.responseText)
End Sub
But I'm getting the following error message: HTTP Status 401 - user and password should be specified as parameters on the request. I was under the impression that the manner in which postData is being passed above meant they are sent as parameters, but I guess I am wrong. How can I send a string of parameters?

It seems to me that the value of postData is not collecting the values of the variables myUsername or myPassword. you have to create the concatenated data like so:
postData = "user=" & myUsername & "&password=" & myPassword
I suppose that myUsername and myPassword are global variables. Otherwise you also need to pass them as arguments to your function.
Hope this helps!

As one comment has suggested, you are trying to send a post string usin a GET command. If you replace the folowing line, it should work:
HTTPReq.Open "GET", TargetURL, False
replaced by:
HTTPReq.Open "POST", TargetURL, False

Related

How to POST using -x in VBA HTTP API

I have a bunch of API calls to STRIPE which are working well.
Generally I use the cURL version and work out what I need to do.
I have just come across the need to DELETE a subscription:
curl https://api.stripe.com/v1/subscriptions/sub_FpZkRarex4obNX \
-u sk_test_VHkTM0bOtpsE1dBnTxFbMBAk00WnBQnyI5: \
-X DELETE
The issue is I have no idea how to use the -x in VBA
My current code for other calls is:
api_Key = getStripeAPI
req = "DELETE"
Set httpReq = CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "POST", "https://api.stripe.com/v1/subscriptions/" & stripeSubID, False
httpReq.setRequestHeader "Authorization", "Bearer " & api_Key
httpReq.send req
strResponse = httpReq.responseText
Debug.Print strResponse
writeToText strResponse
Set parsed = JsonConverter.ParseJson(strResponse)
I know the above code is incorrect but if someone can let me know how to utilise -X that would be great.
You're already using it, just passing the wrong argument. It's the first argument to .Open:
httpReq.Open "DELETE", "https://api.stripe.com/v1/subscriptions/" & stripeSubID, False
ok wow i just figured it by myself.. after 45 mins of trying.
For those looking fr this:
-x DELETE means use DELETE as the "GET"/"POST" option.
working code:
api_Key = getStripeAPI
Set httpReq = CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "DELETE", "https://api.stripe.com/v1/subscriptions/" & stripeSubID, False
httpReq.setRequestHeader "Authorization", "Bearer " & api_Key
httpReq.send
strResponse = httpReq.responseText
Debug.Print strResponse
writeToText strResponse
Set parsed = JsonConverter.ParseJson(strResponse)

Error Unsupported Grant Type

I am trying to connect to an API, using MS Excel VBA. The parameters needed for login are grant type, username, and password.
I have came up with the code below, however i am getting the error :
{"error":"unsupported_grant_type"}
Can anyone enlighten me where i am doing it wrongly?
Sub test()
Dim objHttp As Object
Dim json As String
Dim user, password As String
user = "user1"
password = "password1"
json = "{""grant_type"":""password"",""username"":""" & user & """,""password"":""" & password & """}"
MsgBox json
Dim result As String
Set objHttp = CreateObject("MSXML2.XMLHTTP")
url = "http://dummywebsite.com"
objHttp.Open "POST", url, False
objHttp.SetRequestHeader "Content-type", "application/json"
objHttp.Send (json)
result = objHttp.ResponseText
MsgBox result
End Sub
The code is actually working, and it is due to user rights after testing with another user account.
Try:
Headers:
- Content-Type: application/x-www-form-urlencoded
- Accept-Charset: UTF-8
- Authorization: [Your Authorization Code]
Body:
username=[username]&password=[password]&grant_type=password

VBA RESTful API GET Method issue

Hi I'm calling an API and using the winhttp request and the GET method. I'm passing a json style parameter in the send method but it just can't get accepted. I end up with the error message:
{"code":"INS03","description":"Event ID required","requestId":"_181603230829162847306080","data":{},"validationErrors":null}
Which seems weird because I am indeed passing the event id parameter, as follows:
inventory_URL = "https://api.stubhub.com/search/inventory/v1"
Dim oRequest As WinHttp.WinHttpRequest
Dim sResult As String
Set oRequest = New WinHttp.WinHttpRequest
With oRequest
.Open "GET", inventory_URL, True
.setRequestHeader "Authorization", "Bearer " & access_token
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Accept-Encoding", "application/json"
.send ("{""eventid"":""9445148""}")
.waitForResponse
sResult = .responseText
Debug.Print sResult
sResult = oRequest.Status
Debug.Print sResult
End With
Is there any issue with my code?
Thank you in advance,
Vadim
For GET request query string should be composed.
Your data can't be passed in Send but in query string:
.Open "GET", inventory_URL & "?eventid=9445148", True
Check GET vs POST.

Custom header with MSXML2.ServerXMLHTTP

I am currently trying to use MSXML2.ServerXMLHTTP to send a POST http request.
I need to add a custom header "Auth" so that my requests get authorized but it doesn't seem to work.
Here is the code for my post function:
Function post(path As String, authToken As String, postData As String) As String
Dim xhr As Object
Dim message As String
On Error GoTo error:
Set xhr = CreateObject("MSXML2.ServerXMLHTTP")
xhr.Open "POST", path, False
xhr.setRequestHeader "Content-Type", "application/json"
xhr.setRequestHeader "Auth", authToken
xhr.send postData
If xhr.Status = 200 Then
message = xhr.responseText
Else
message = xhr.Status & ": " & xhr.statusText
End If
Set xhr = Nothing
post = message
error:
Debug.Print "Error " & Err.Number; ":" & Err.Description
End Function
And I end up with "Error -2147012746 Requested Header was not found" (The message is actually translated since I use a different language on my computer).
However I didn't have this problem with the "Microsoft.XMLHTTP" Object.
Am I doing something wrong ?
Thank you for your time.
Try changing the call to SetRequestHeader to use a string literal. I duplicated the problem when authToken does not have a value set.
Change from this
xhr.setRequestHeader "Auth", authToken
To this
xhr.setRequestHeader "Auth", "testdatahere"

Exchanging Authorization Code for Access Token for Google Calendar API with VBA and Oauth2

After successfully obtaining the authorization code, I am having trouble exchanging it for an access token and refresh token while trying to access the Google Calendar API. I get Error 404 Not Found. Here is my code:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/auth2/token"
Dim getTokenBody As String
getTokenBody = "code=" & code & _
"&redirect_uri=urn:ietf:wg:oauth:2.0:oob" & _
"&client_id=xxxxxxx-xxxxxxxx.apps.googleusercontent.com" & _
"&client_secret={myLittleSecret}" & _
"&grant_type=authorization_code"
Dim Http As MSXML2.XMLHTTP60
Set Http = CreateObject("MSXML2.XMLHTTP.6.0")
With Http
.Open "POST", getTokenUrl, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send(getTokenBody)
End With
Do While Http.ReadyState <> 4
Loop
Debug.Print Http.responseText
I have also tried putting everything in the url parameter of the .Open method and nothing in the .Send method:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/oauth2/token&code=" & code & "&client_id=xxxxxx-xxxxxx.apps.googleusercontent.com&client_secret={myLittleSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code"
Dim Http As MSXML2.XMLHTTP60
Set Http = CreateObject("MSXML2.XMLHTTP.6.0")
With Http
.Open "POST", getTokenUrl, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send("")
End With
I have tried using WinHttp.WinHttpRequest instead of MSXML2.XMLHTTP.
I have tried using http://localhost instead of urn:ietf:wg:oauth:2.0:oob.
I have tried making http://localhost and urn:ietf:wg:oauth:2.0:oob url encoded.
All give Error 404 Not Found.
Can someone help point me in the right direction?
Finally figured it out--
The URL I was using was wrong--a one-letter type-o /forehead-slap/
instead of:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/auth2/token"
it should have been:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/oauth2/token"
note the oauth2 instead of just auth2
Geesh. Sometimes I just need more sleep.
Incidentally, I could only get it to work when I put only the base URL in the .Open request and the parameters in the .send() (rather than stringing them all together in to one URL and "POST"ing it).
Working like a charm now!