sending payload for post method in VBA - vba

I'm trying to login to a website using VBA Excel, but I'm having trouble to send payload post method like in python request.
Example in python
def login():
s = requests.Session()
payload = {
'username':sett.username,
'password':sett.password1
}
res = s.post(link, json=payload)
ref_t = json.loads(res.content)['content']['refresh_token']
t = json.loads(res.content)['content']['token']
return t
this is what I've tried but fail:
Dim request As New WinHttpRequest
request.Open "POST", auth_url, False
auth = "username=" & user & "," & "password=" & pass
request.SetRequestHeader "content-type", "application/json;charset=UTF-8"
request.SetCredentials "username:" & user, "password:" & pass, 0
request.Send auth
If request.Status <> 200 Then
MsgBox request.ResponseText
Exit Sub
End If
the response text shows "Username is required, but was not received", "Password is required, but was not received", "code":400.
Edit:
Dim auth As New Dictionary
auth.Add "username", user
auth.Add "password", pass
request.Open "POST", auth_url, False
request.SetRequestHeader "content-type", "application/json"
request.Send JsonConverter.ConvertToJson(auth)

Turns out that I need to use SetRequestHeader
Edit:
Dim auth As New Dictionary
auth.Add "username", user
auth.Add "password", pass
request.Open "POST", auth_url, False
request.SetRequestHeader "content-type", "application/json"
request.Send JsonConverter.ConvertToJson(auth)

Related

Upload file to onedrive personel via VBA REST API

There is simple code for upload file to dropbox.
Does someone have an example of a similar code for Onedrive
Function uploadSave(stm As ADODB.Stream, fname As String, token As String) As integer
Const lngTimeout = 890000
Dim http As WinHttp.WinHttpRequest
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
http.SetTimeouts lngTimeout, lngTimeout, lngTimeout, lngTimeout
http.Open "POST", "https://content.dropboxapi.com/2/files/upload", False
http.setRequestHeader "Content-Length", stm.Size
http.setRequestHeader "Authorization", "Bearer " & token
http.setRequestHeader "User-Agent", "api-explorer-client"
http.setRequestHeader "Content-Type", "application/octet-stream"
http.setRequestHeader "Dropbox-API-Arg", "{""path"":""" & fname & """,""mode"":{"".tag"":""overwrite""},""autorename"":true}"
http.Send (stm.Read)
Set stm = Nothing
uploadSave = http.Status
End Function

Access JIRA API from Excel with VBA-Web

I'm trying to access the JIRA API from Excel. Using the MSXML2.XMLHTTP.6.0 object works fine but using the WinHttp.WinHttpRequest.5.1 from the VBA-Web WebClient does not.
This works fine:
Function getJiraSessionId()
Set JiraAuth = CreateObject("MSXML2.XMLHTTP.6.0")
With JiraAuth
.Open "POST", "https://<our JIRA server>/tracker/rest/auth/1/session", False
.SetRequestHeader "Content-Type", "application/json"
.SetRequestHeader "Accept", "application/json"
.SetRequestHeader "User-Agent", "Jira-Automation"
.Send " {""username"" : ""...."", ""password"" : ""....""} "
sErg = .ResponseText
End With
...
End Function
This does not:
Function JiraLogin()
Dim JiraClient As New WebClient
JiraClient.BaseUrl = "https://<our JIRA server>/tracker/"
JiraClient.Insecure = True
JiraClient.TimeoutMs = 50000
Dim Abruf As New WebRequest
Abruf.Resource = "rest/auth/1/session"
Abruf.Method = WebMethod.HttpPost
Abruf.Format = WebFormat.Json
Abruf.UserAgent = "Jira-Automation"
Set Body = New Dictionary
Body.Add "username", "...."
Body.Add "password", "...."
Set Abruf.Body = Body
Dim Response As WebResponse
Set Response = JiraClient.Execute(Abruf)
...
End Function
The error message is:
ERROR - WebClient.Execute: -2147210493 (11011 / 80042b03), An error occurred during execute
-2147012739 (80072f7d): Im Support des sicheren Channels ist ein Fehler aufgetreten
I want to use VBA-Web because of its great tools but I can't. Any idea what is wrong? Thanks, Manfred.

"Run-Time error '13': Type mismatch" in VBA for JSON extraction with JIRA API

New to the community here. I've done a decent amount of programming but I'm completely new to VBA. Never used it before until now and I was tasked with extracting JSON data from a Jira API into an Excel spreadsheet. I keep getting the error "Run-Time error '13': Type mismatch" and I'm not sure why. I know the error has to do with passing in incorrect types but I've tried changing the Json variable to a String with no success. Anyone have any ideas? Thanks!
By the way, this is just a trial Jira instance for testing the API functionality.
Sub test()
'Authenticate the user
Dim response As String
With CreateObject("Microsoft.XMLHTTP")
.Open "POST", "https://apitestsite.atlassian.net/rest/auth/1/session", False, "admin", "password"
.setRequestHeader "X-Atlassian-Token:", "nocheck"
.Send
response = .responseText
End With
'Query through JSON
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", "https://apitestsite.atlassian.net/rest/api/2/issue/CC-1", False, "admin", "password"
MyRequest.Send
Dim Json As Object
Set Json = JsonConverter.ParseJson(MyRequest.responseText)
MsgBox Json("fields")("summary")
End Sub
UPDATE: This is where I am at right now. Updated the code for the authentication and now no errors display from the compiler. Here is the JSONConverter class I am using: github.com/VBA-tools/VBA-JSON/blob/master/JsonConverter.bas. The issue now is that the returned JSON string says, "{"errorMessages":["Issue does not exist or you do not have permission to see it."],"errors":{}}". So I am able to connect to Jira just fine and return the JSON as a string, it's just that Jira is rejecting my credentials :/
Private JiraService As New MSXML2.XMLHTTP60
Private JiraAuth As New MSXML2.XMLHTTP60
Sub test()
'Authenticate the user
With JiraAuth
.Open "POST", "https://apitestsite.atlassian.net/rest/auth/1/session", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "X-Atlassian-Token:", "nocheck"
.send " {""username"" : ""admin"", ""password"" : ""password""}"""
sErg = .responseText
sCookie = "JSESSIONID=" & Mid(sErg, 42, 32) & "; Path=/Jira" '*** Extract the Session-ID
End With
With JiraService
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", "https://apitestsite.atlassian.net/rest/api/2/issue/CC-1", False
MyRequest.setRequestHeader "Content-Type", "application/json"
MyRequest.setRequestHeader "Accept", "application/json"
MyRequest.setRequestHeader "Set-Cookie", sCookie '*** see Create a "Cookie"
MyRequest.send
Dim Json As String
Json = MyRequest.responseText
MsgBox Json
End With
End Sub
This seems to return a valid JSON from the API, which is parseable from the Jsonconverter module.
You were using MyRequest object as possibly the wrong type of object. Elsewhere, you're relying on the MSXML2.XMLHTTP60 class.
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
So I removed the MyRequest and just worked with the JiraService object instead. You had a With JiraService block but you weren't actually using that object at all, you were executing against the WinHttpRequest object within that block.
I also declared all variables, and modified the auth string to use Const strings defined at top of module for user/password.
Option Explicit
Private JiraService As New MSXML2.XMLHTTP60
Private JiraAuth As New MSXML2.XMLHTTP60
Const user As String = "jiratestemail82#gmail.com"
Const pw As String = "password"
Sub test()
Dim sErg$, sCookie$, Json$
'Authenticate the user
With JiraAuth
.Open "POST", "https://apitestsite.atlassian.net/rest/auth/1/session", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "X-Atlassian-Token:", "nocheck"
.send " {""username"" : """ & user & """, ""password"" : """ & pw & """}"""
sErg = .responseText
sCookie = "JSESSIONID=" & Mid(sErg, 42, 32) & "; Path=/Jira" '*** Extract the Session-ID
End With
With JiraService
.Open "GET", "https://apitestsite.atlassian.net/rest/api/2/issue/CC-1", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Set-Cookie", sCookie '*** see Create a "Cookie"
.send
Json = .responseText
End With
Dim j As Object
Set j = JsonConverter.ParseJson(Json)
MsgBox j("fields")("summary")
End Sub

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.

Non-interactive api login after windows 10 update

I was using this method to login to betfair api. Everything works fine, but after Windows 10 update (KB3140741) not working anymore. ResponseText = {"loginStatus":"CERT_AUTH_REQUIRED"} Anyone solved this?
Windows 10 Build 10586.218, version 1511
Microsoft Office 2016
Dim oHTTP As Object: Set oHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim uri As String: uri = "https://identitysso.betfair.com/api/certlogin"
oHTTP.Open "POST", uri, False
oHTTP.SetClientCertificate "Common Name"
oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oHTTP.setRequestHeader "X-Application", App_key
oHTTP.setRequestHeader "Accept", "application/json"
oHTTP.send "username=" & UserName & "&password=" & Password & ""
I would try with Msxml2.ServerXMLHTTP.6.0 instead :
Const uri = "https://identitysso.betfair.com/api/certlogin"
Dim req As Object
Set req = CreateObject("Msxml2.ServerXMLHTTP.6.0")
req.Open "POST", uri, False
req.setOption 2, 13056 ' ignore all certificate errors '
req.setOption 3, "Common Name" ' set the client certificate from the local store '
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.setRequestHeader "X-Application", App_key
req.setRequestHeader "Accept", "application/json"
req.send "username=" & UserName & "&password=" & Password & ""