Using VBA to get data from API with bearer token to Excel - excel

So far I have been using Postman to GET data with our bearer token.
I need to get this data into Excel. So far what we've done is download the .json using postman, convert the .json to .xml and open the file with Excel.
Can I use VBA to pull data from the web that requires bearer token authentication and also can I automatically convert the .json data to .xml?
I have done some research and found a code
Sub GetData()
Dim hReq As Object, Json As Dictionary
Dim sht As Worksheet
Dim authKey As String
authKey = {my token key}
Set sht = Sheet1
Dim strUrl As String
strUrl = "https://myurl"
Set hReq = CreateObject("MSXML2.XMLHTTP")
With hReq
.Open "GET", strUrl, False
.SetRequestHeader "Authorization", "Bearer " & authKey
.Send
End With
Dim response As String
response = hReq.ResponseText
MsgBox response
End Sub
But whenever I insert the authKey bearer token I have it gives 2 types of errors. Firstly it doesn't like the {} brackets Compile error: invalid character so okay I removed the curly brackets. But my bearer token key has .12 in the middle of the code (ex. 125ffhuhf901h201.12afjsfklajflksajkl) says Compile error: Expected: end of statement and highlights the .12 part.

Related

Excel VBA API Request

So I don't have any experience coding whatsoever but I'm working on pulling some vehicle data from an government site with an API using VBA. so i don't have to manually adjust data in our vehicle list.
the code i wrote/stole:
Sub SendAPIRequest()
Dim httpreq As Object
Dim url As String
Dim response As String
Dim headers As Collection
Set headers = New Collection
headers.Add "SVV-Authorization", "Apikey {1234}"
Set httpreq = CreateObject("MSXML2.XMLHTTP")
url = "https://www.vegvesen.no/ws/no/vegvesen/kjoretoy/felles/datautlevering/enkeltoppslag/kjoretoydata?kjennemerke=AA91620" + kjennemerke
With httpreq
.Open "GET", url, False
.setRequestHeader "SVV-Authorization", "1234}"
.send
End With
response = httpreq.responseText
Debug.Print response
End Sub
the request goes out but the with the following response: "status":403,"error":"Forbidden","path":"/enkeltoppslag/kjoretoydata"}
403 The API key does not exist in the database, has the status active and/or the user is blocked.
Additional info: REST service - Json response.
https://autosys-kjoretoy-api.atlas.vegvesen.no/api-ui/index-enkeltoppslag.html
key is legit so I'm sending the header out wrong?
Thanks in advance :)
copy & paste other code, etc.

vba run time error '- 2146697208 800c0008 )': the download of the specified resource has failed telegram

Request your help to solve the below issue,I am struck for two days,
vba run time error '- 2146697208 (800c0008 )': The download of the specified resource has failed
This is my code for your reference:
Sub telebot15status155555()
'Program Excel Messeger
' Purpose : Send Message to Telegram
' Author : John Eswin Nizar
' Date : 09 October 2017
Dim objRequest As Object
Dim strChatId As String
Dim strMessage1 As String
Dim strMessage2 As String
Dim strPostData As String
Dim strResponse As String
strChatId = "#messstatus"
strMessage1 = ""
strMessage2 = Now()
'strMessage = "hallo"
strPostData = "chat_id=" & strChatId & "&text=" & strMessage1 & strMessage2
Set objRequest = CreateObject("MSXML2.XMLHTTP")
With objRequest
.Open "POST", "https://api.telegram.org/sendMessage?", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (strPostData)
GetSessionId = .responseText
MsgBox GetSessionId
End With
End Sub
My advice here is to perform this API call in Chrome with DevTools open. Or access the page, where this happens, and find the Request on the 'Network' tab. Then look at the headers.
debug.print strPostData is returning:
chat_id=#messstatus&text=2/7/2020 9:40:23 AM
That format does not look correct for an API that is form-urlencoded. You need to see what the website is actually sending and receiving in the DevTools in order to replicate it.
IOW, The resource isn't found because the API is incorrectly formatted. From the base api, it looks like its actually a QueryString too because it ends with ? which might mean you have to url-encode format the POST Data into the QueryString for the main HTTP request. Have a look here: Pass Parameters in VBA HTTP Post Request

Which format of the url is correct while using an api with xml

When I try to access common/example api url with vba (excel), there is no problem.
The required URL is as follows: "hppts://user:password#www.site.com/events/"
When I copy the url in web-browser there is no problem.
But when using VBA is returning an error: "Method of Open object IServerXMLHTTPRequest2 has failed"
Code:
Dim http As Object, str As Variant
Set http = CreateObject("MSXML2.XMLHTTP")
With http
.Open "GET", "https://user:password#www.site.com/events/", False
.send
str = .responseText
End With
x = UBound(str)

Podio items to excel sheet

I need to have a vba macro that downloads data from my Podio app to an excel sheet. Right now I am running a code I found on Podio community website, which I am pasting below:
Dim winHttpReq As Object
Dim access_token As String
Function ProjectsFromPodio()
Dim result As String
Dim postData As String
Dim myURL As String
Dim token_pos As Long
'Initialisierung
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
myURL = "https://api.podio.com/oauth/token"
postData = "grant_type=app&app_id=ABC&app_token=DEF&client_id=GHI&client_secret=JKL"
If winHttpReq.Open("POST", myURL, False) = S_OK Then
'MsgBox ("Open successfull")
End If
winHttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
winHttpReq.Send (postData)
result = winHttpReq.responseText
token_pos = InStr(result, "access_token")
access_token = Mid(result, token_pos + 15)
token_pos = InStr(access_token, Chr(34)) - 1
access_token = Mid(access_token, 1, token_pos)
OAuthAppAuthorization = result
'MsgBox (OAuthAppAuthorization)
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
myURL = "https://api.podio.com/item/app/XYZ"
winHttpReq.Open "GET", myURL, False
winHttpReq.SetRequestHeader "Authorization", "OAuth2 " & access_token
winHttpReq.Send
result = winHttpReq.responseText
'MsgBox (result)
End Function
This works nice, data is downloaded and I can use it. My question is how to download this data in CSV format, rather than JSON? Is it possible?
If it is not possible, how can I parse it to a sheet in a smart way?
Thanks for any help
You may send the POST request to /item/app/{app_id}/export/{exporter}which creates a batch for exporting the items.
Here you can export the items as xls and xlsx formats.
Your myURL must be like,
myURL = "https://api.podio.com/item/app/XYZ/export/xls"
You will get a batch_id as a result of this request.
Then make a GET call to /batch/{batch_id} to get the status of the batch. You can download the output xls file by making a GET request to /file/{file_id} using the podio_file_id from the batch response.
References
Podio - Export Items
Podio - Get Batch
Podio - Get File

Excel VBA using XMLHTTP with Siteminder Secured site

I am completely new to using XMLHTTP and experimenting with trying to download a report off of our company's internet site using Excel VBA. The problem I seem to be running into is that the site is protected by Siteminder. I think I need to use an XMLHTTP.Open with GET but anyway I try all I just seem to get is the Siteminder HTML code. So I am trying to first use a post to send my username and password to Siteminder something like:
Function PostXmlData(vUrl As String, UserName As String, Password As String, xmlText
As String
Dim XMLHttp As Object
Set XMLHttp = CreateObject("MSXML2.XMLHTTP")
XMLHttp.Open "POST", vUrl, False, UserName, Password
XMLHttp.setRequestHeader "Content-Type", "text/xml;charset=utf-8"
XMLHttp.send (xmlText)
PostXmlData = XMLHttp.responseText
End Function
Sub Posttest ()
Dim add As String
Dim User As String
Dim Pass As String
Dim send As String
Dim ret As Variant
add = "https://mycompanywebsite.com/apps/application/Main/"
User = "username"
Pass = "password"
Send="DashboardId=http://mycompanywebsite.com/DAVCatalog/Dashboards/Teams/Client%20_
Extranet%20AM"
ret = PostXmlData(add, User, Pass, send)
End Sub
Am I on the right track or is this not even possible? Any suggestions would be greatly appreciated or if there is some site someone could direct me to that would be helpful. THanks.
You'll need to load the responseText into an XMLDocument so that you can parse it. See example below (make sure you add the Microsoft XML reference to the reference library)
Dim xmldoc As MSXML2.DOMDocument
' Create a new XMLDocument to which to load the XML text
Set xmlDoc = New DOMDocument
xmldoc.LoadXML (xmlhttp.responseText)
' Fetch the XML
Set xmlhttp = CreateObject("Microsoft.xmlHTTP")
xmlhttp.Open "Get", yourURL, False
xmlhttp.send
' Create a new XMLDocument to which to load the XML text
Set xmlDoc = New DOMDocument
xmldoc.LoadXML (xmlhttp.responseText)
From here, you should be able to parse the XML using objects like NodeList, DOMElement, etc.
Could you post the SiteMinder HTML response? Looks like authentication may be failing. Try sending the credentials as a base64 encoded header instead of supplying them to the XMLHttp componet.
This is the format.
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
The string after 'Basic' is base64 encoded credentials in the 'id:password' format.

Resources