Microsoft Graph v1.0 download file content not working - vba

I am trying to download a word document file named Test.docx located in Sharepoint Document Library from within a Visio File macro referring to the Microsoft documentation at
https://learn.microsoft.com/en-us/graph/api/driveitem-get-content?view=graph-rest-1.0&tabs=http
I am able to get my site ID and Item ID ending up to the below URL,
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/items/{item-id}
Since I want to download the file content in binary and save it locally, I add "content" to the url as below,
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/items/{item-id}/content
My code looks as below in VBA environment for the client as below with an active Access Token,
myURL=https://graph.microsoft.com/v1.0/sites/{site-id}/drive/items/{item-id}/content
Set winHttpReq = New XMLHTTP60
winHttpReq.Open "GET", myURL
winHttpReq.setRequestHeader "Authorization", "Bearer " & AccessToken
winHttpReq.send
I am getting an error as "Access is denied." at the line winHttpReq.send and control exits out of the function.
Files.Read.All, Files.ReadWrite.All, Sites.Read.All, Sites.ReadWrite are the permissions already given for the API access.
Also, I did another call fetching the "#microsoft.graph.downloadUrl" download URL but I did not see any binary content in the response.
My questions are,
Is my approach correct?
I need the file binary data to be downloaded using graph API but adding /content to the URL gives this error. How can I get the file using API?
Where can I fetch the binary content from the response to the url of "#microsoft.graph.downloadUrl" of the file to download and save the file locally?
Is there any other approach to download a file using the graph API
that will work in VBA environment?

Related

Send CSV file via Rest API

I'm not a developer, but recently have been doing lots of automations at work using VBA, Python and AWS. Recently I started learning and working with API's in AWS.
I've been trying to upload a CSV file through a REST API, but it's just not working as expected.
Basically I have used API Gateway to set up my API that triggers a Lambda Function to upload the file to a S3 bucket.
When I tested my API in Postman, it worked fine, I just had to set Headers as Key: "Content-Type" and Value: "application/csv", then in the Body part I selected "Binary" and browsed my csv file that I want to upload.
But the problem is when I tried to call my api from my application (or from Postman using the raw text instead of binary), I am sending the following Body (Also tried without double quotes and didn't work either):
--data-binary "\file-location\file-name.csv"
The api returns a success code, but when I open the file in S3, then content is "--data-binary "\file-location\file-name.csv"" instead of the actual file's content that I selected.
This is the code I'm using in my VBa to call the API:
Dim ws As Worksheet
Dim URL, env, msg, result As String
Dim objHTTP As Object
Set ws = ThisWorkbook.Worksheets("Sheet1")
URL = "https://api-url"
msg = "--data-binary ""\\file_location\file_name.csv"""
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-Type", "application/csv"
objHTTP.send (msg)
result = objHTTP.responseText
'getResponse
ws.Range("s3_api_resp").Value = result
Set objHTTP = Nothing
Uploading a file should be done directly to Amazon S3, the reason I say this, is that AWS Lambda has a limit of 6MBs as an invocation payload.
There are several ways to upload to S3, here are three ways:
SDK
CLI
Rest API
There is no SDK for VB, but if you are using VB .Net you could use the .Net SDK. An example is available here. Alternatively you could invoke the AWS CLI via VB, that is not so slick (more of a hack) but possible. Details are available here. Alternatively you can upload a file using the AWS S3 Rest APIs, details available here.
Files can be uploaded to Amazon S3 without credentials, provided the bucket policy allows open buckets. Examples of bucket policies are available here.
If the bucket is locked down (recommended) then you should use temporary credentials to upload to Amazon S3. You can get temporary credentials by either providing pre-signed URLs for PUT or you can grant temporary credentials using a service such as Amazon Cognito. Amazon Cognito comprises of two parts, User Pools to store credentials and Federated/Identity Pools. You can use Amazon Cognito Identity Pools to generate temporary credentials to Amazon Identity and Access Management using authenticated credentials. Authenticated credentials can be sourced from Apple, Google, Amazon, Cognito, SAML, and OpenID. The authenticated credentials are exchanged for IAM credentials. The IAM credentials are attached to a policy, and that policy should have permissions to upload files.

Web Scraping: xmlHTTP GET request not working

I am trying to scrape flashscore.com with VBA using XMLHTTP request. It is making multiple javascript based requests to the server. One request i am interested in (as visible in the chrome developer tools) is this:
but when I send the request, it fails. The code is
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://d.flashscore.com/x/feed/f_1_0_5_en_1", False
.send
End With
Can anybody guide me why i can not retrieve the content like this? Why the request is failing? Thanks

How to Upload a Local File into sharepoint using Graph API?

I am trying to upload a local PDF file into share point via using Graph API but the PUT method is just letting me to create a new file in the SharePoint but not letting me upload a local existing C:/ Drive PDF file
Here is the API that I am using
PUT https://graph.microsoft.com/v1.0/drives/{drive-id}/root:/SharePointFilePath/file-name:/content
As per here, that is the correct endpoint. however, you need to send ithe file as a binary stream in the body. https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http
This means that you need to read your local pdf file into a binary stream and send it to the endpoint in the body of the put request. as a test for example, you could create a regular text file with the body as string and contenttype as text.
also if it's larger than 4MB, then you need to use a different method. https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_createuploadsession mainly an uploadsession.
Previous test script to upload file to SharePoint by PnP PowerShell.
https://social.technet.microsoft.com/Forums/msonline/en-US/25191b51-41dd-4f4b-93aa-a46594c9a184/uploading-a-file-to-sharepoint-online-using-microsoft-graph-api?forum=onlineservicessharepoint
Connect-PnPOnline -AppId 'yourAzure app id' -AppSecret "yourAzure app secret" -AADDomain 'xxx.onmicrosoft.com'
$accessToken= Get-PnPAccessToken
$apiUrl = "https://graph.microsoft.com/v1.0/sites/xxx.sharepoint.com,x,x/drives/driveid/items/01AKXHS4ELSEOTLPZHZZDYYBOW57WR6HK6:/test.xlsx:/content"
$path="C:\Lee\Script\testdata.xlsx"
$file=[IO.File]::ReadAllBytes($path)
Invoke-RestMethod -Headers #{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Put -Body $file -ContentType "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

Parse.com Push Object/Message from Excel VBA

I am trying to write a VBA script to push messages from Excel to my decives using the Parse.com framework. So far I succeeded in sending push data messages from the Parse.com website to multiple devices so that part should be good.
Problem is getting VBA to send a Push or even data to Parse.com in general.
At the moment I'm just trying to get the connection to work and push some data in to my TestObject Class. I am using the following code and authentication seems to go how it's supposed to be now! The PUT object gives an error: invalid json
Sub Parse()
TargetURL = "https://api.parse.com/1/classes/TestObject"
Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1") '
HTTPReq.Open "POST", TargetURL, False
HTTPReq.setRequestHeader "X-Parse-Application-Id", "xxxxxx"
HTTPReq.setRequestHeader "X-Parse-REST-API-Key", "xxxxxx"
HTTPReq.setRequestHeader "Content-Type", "application/json"
HTTPReq.send ("{foo:bar}")
MsgBox (HTTPReq.ResponseText)
End Sub
New Error:
Invalid Json
Have you set up authentication? From the Parse.com REST API reference:
Request Format
For POST and PUT requests, the request body must be JSON, with the Content-Type header set to application/json.
Authentication is done via HTTP headers. The X-Parse-Application-Id header identifies which application you are accessing, and the X-Parse-REST-API-Key header authenticates the endpoint. In the examples that follow, the keys for your app are included in the command. You can use the drop-down to construct example code for other apps.
You may also authenticate your REST API requests using basic HTTP authentication. For example, to retrieve an object you could set the URL using your Parse credentials in the following format:
https://myAppID:javascript-key=myJavaScriptKey#api.parse.com/1/classes/GameScore/Ed1nuqPvcm
For Javascript usage, the Parse Cloud supports cross-origin resource sharing, so that you can use these headers in conjunction with XMLHttpRequest.
HTTPReq.send ("{""foo"":""bar""}")
Posting will be successful.

401 unauthorized exception while reading data from the document library SharePoint 2010

We developed a WebPart to read the content of the file in the document library in the SiteCollection. I used the following code to read the content.
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultNetworkCredentials;
string documenturl = siteurl+"/" + file.Url.ToString();
content = wc.DownloadData(documenturl);//documenturl is the file path of the document
But, i got the following error 401 unathorized exception
System.Net.WebException: The remote server returned an error:(401) Unauthorized. at System.Net.WebClient.DownloadDataInternal(Uri address,WebRequest& request) at System.Net.WebClient.DownloadData(Uri address)
For your information, i already tried to download document by SPFile openBinary method. But it only works when the document is small. Please refer the below site.
getting ComException while reading the document in SharePoint 2010
Thanks in advance.
Probably the local loopback check. (Verify by trying to access your site using the same URL whilst using IE running on your SharePoint server)
Also - any reason why you're using web services to access local content rather than the SharePoint object model (Microsoft.SharePoint.dll)?