I am trying to use VBA Excel to access the API provided by the website www.myfxbook.com. The API documentation is here(https://www.myfxbook.com/fr/api). The Steps to get the data are as follows:
Login through Login API
Get session ID of the session from response of Login API
Get data based on this Session ID through various other APIs
Logout through the Logout API to generate a new session
The Problem I am facing is that even though the Login and Logout APIs are being used and throwing no error, I am always getting the same Session ID when I am trying to use it through Excel VBA. On the other hand, using the same URLs through Python or even the browser is giving me a different session ID each time. i can only use Excel for this project. Could someone please help me how to get different session ID on successful logout?
I am using the code below to do this. I have hidden (*******) the Email ID and password for security purposes.
Sub extract()
Dim sht1 As Worksheet
Dim email As String
Dim password As String
Dim accountName As String
Dim url As String
Dim hreq As Object
Set hreq = CreateObject("MSXML2.XMLHTTP")
Dim accountID As String
Set sht1 = Sheets(1)
email = "*******"
password = "********"
accountName = "all day multiple currency coinexx"
loginURL = "https://www.myfxbook.com/api/login.xml?email=" + email + "&password=" + password
hreq.Open "GET", loginURL, False
hreq.Send
Dim xmlDoc As New MSXML2.DOMDocument60
Dim response As String
response = hreq.ResponseText
If Not xmlDoc.LoadXML(response) Then
MsgBox ("Load Error")
End If
Dim xnodelist As MSXML2.IXMLDOMNodeList
Set xnodelist = xmlDoc.getElementsByTagName("session")
Dim sessionID As String
sessionID = xnodelist(0).Text
'Do Something here to get data. This part is working fine.
logoutURL = "https://www.myfxbook.com/api/logout.xml?session=" + sessionID
hreq.Open "GET", logoutURL, False
hreq.Send
response = hreq.ResponseText
If Not xmlDoc.LoadXML(response) Then
MsgBox ("Load Error")
End If
End Sub
I think it likely you are hitting caching. Try to force an avoidance of this with an additional header
hreq.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
Related
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.
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
I am trying to use VBA-Web for submitting REST API via Excel VBA and running into issues
https://github.com/VBA-tools/VBA-Web
I tried to modify this example to use HttpBasicAuthenticator but unsuccessful it says HTTP error 401. When I use Postman to submit the rest request it is fine.
https://github.com/revisohq/api-samples/tree/master/rest/excel
If I use this Url that does not need to authenticate. It works as expected
https://rest.reviso.com/customers?demo=true
Private Sub Worksheet_Activate()
Dim Client As New WebClient
Dim Request As New WebRequest
Client.TimeoutMs = 30000 ' 30 seconds
Client.BaseUrl = "https://postman-echo.com/basic-auth"
'Client.BaseUrl = "https://rest.reviso.com/customers?demo=true"
Request.Format = WebFormat.Json
Dim Auth As New HttpBasicAuthenticator
Auth.Setup _
Username:="postman", _
Password:="password"
Dim Response As WebResponse
Set Response = Client.Execute(Request)
If Response.StatusCode <> Ok Then
Sheets("Test").Range("A1") = Response.StatusDescription
Exit Sub
End If
Dim Json As Object
Set Json = WebHelpers.ParseJson(Response.Content)
FillData Json
End Sub
I have a HTML web page at work that I want to query data from tables into excel 2007. This web page requires I sign on with a password. I sign in with my normal IE7 browser, then I go to DATA -> connections -> my connections and edit the query. This reads the IE7 cookie cache and I re-POST the data to connect to the server's security by clicking "retry" when it says "the web query returned no data". After I do this, the data imports fine.
I can do this just fine and it only needs to be done once a day. Other users of my application find this difficult which leads to my question:
Is there a way to automatically POST this data back with VB? I'm thinking maybe I should use the cookie property of the IE.Document.cookie?
I'm calling the following login script, before I continue with the web query (set reference to XML library). Look around to find some instructions how you can find your POST parameters.
Sub XMLHttpLogin()
Dim i As Integer
Dim sExpr As String
Dim sPar As String, sURL as String
Dim sResp As String
Dim XMLHttp As MSXML2.XMLHTTP60
Set XMLHttp = New MSXML2.XMLHTTP60
sPar = "name=user1&pass=pass1&form_id=form1" 'The parameters to send.
sURL = "http://www.stackoverflow.com"
With XMLHttp
.Open "POST", sURL, True 'Needs asynchronous connection
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (sPar)
i = 0 'wait until data has been downloaded
Do While i = 0
If .readyState = 4 Then
If .Status = 200 Then Exit Do
End If
DoEvents
Loop
sResp = .responseText 'contains source code of website
sExpr = "not-logged-in" 'look for this string in source code
If InStr(1, sResp, sExpr, vbTextCompare) Then
MsgBox "Not logged in. Error in XMLHttpLogin"
End If
End With
End Sub
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.