Search code examples
restmicrosoft-graph-apionedrive

How to make REST call to MS Graph/OneDrive method with OAuth2


I am trying to use the OneDrive API and I have successfully registered my app through their Application Registration Portal. I can call successfully call the Javascript FilePicker SDK to upload and download files

That demonstrates that I have my app registered properly and the proper app/client-id's.

Now I'd like to use the REST services to upload and download files but I'm not sure how to send authentication and I don't know how to make the call to the proper URL.

My first question is: How can I use the token I created in the reg service to make a REST call?

My second question is: What syntax should I use to upload a file? I don't know where to put the URL to make the call.

The PUT documentation for their upload is found here

    <script type="text/javascript">
        function launchSaveToOneDrive(){
            var xhttp = new XMLHttpRequest();
            //Authorization: bearer {token} 
            xhttp.open("PUT", "/drive/items/{parent-id}:/{filename}:/content", false);
            xmlhttp.setRequestHeader("Authorization", "Bearer-xxxxxxxxxxxxxxxxxxx");
            xhttp.setRequestHeader("Content-type", "text/plain"); 
            xhttp.send();
            var response = JSON.parse(xhttp.responseText);
        }
        </script>

Solution

  • One option is to use the Microsoft Graph JavaScript SDK that can help with REST calls including uploading files to OneDrive through the MS Graph. The library works with client side JavaScript and Node for JavaScript server apps.

    Check the Browser folder under samples to see how to use the SDK in a client app. Uploading a file would look something like this (see that link for the full code):

        // file variable is from the contents of an input field for example 
        var file = document.querySelector('input[type=file]').files[0];
    
        // after user selects a file from the file picker
    
       client
           .api('/me/drive/root/children/Book.xlsx/content')
           .put(file, (error, response) => {
               // supports callbacks and promises
            });