As SharePoint has become a popular way for people to store and share files,

this blog post illustrates how to create/read/delete files on SharePoint from a Microservice.

SAP Business Technology Platform (BTP) provides a fast and easy way to create, run, manage and scale business applications in the cloud.

In a cloud-based business application, Microservices serve as a layer where business logic and technical operations are implemented.

We know that a cloud application no longer has a file system to use like the traditional way,

in cases where dynamic file operations are needed, using SharePoint is one way to achieve this goal from a cloud-based application.

An example business case is that an application needs to load a document template from a directory, generate pdf documents and store them in another directory.

 

The following paragraphs demonstrate how to prepare SharePoint and microservice code samples (in Node.js) that interacts with it.

 

1. Preparation

 

1.1 Getting your Base URL

If you have SharePoint access, you may manage your SharePoint folder structure, files and sharing from a web browser. You need the URL in the steps below.

From the accessing URL, you need to decide the base URL for your SharePoint folder.

For example, you access your shared documents using the following URL:

https://mycompany.sharepoint.com/teams/MyProjectTeam/Shared%20Documents

From this URL, you can figure that your base URL would be:

https://mycompany.sharepoint.com/teams/MyProjectTeam

 

From now on, I’ll refer to it as the “Base URL”.

 

1.2 Register an Application Principal

 

You need to register an Application Principal for your microservice to use. Launch the following URL to start:

 

<Base URL>/_layouts/15/appregnew.aspx

SharePoint Application accessing is guarded by OAuth 2.0. Choose to generate Client Id and Client Secret or enter your own.

** If you generate Client ID or Client Secret, it’s time now to copy and keep it. You will need it in your application later. Once done, you will not be able to retrieve it back.

Enter a Title, App Domain and Redirect URL (optional) and click on “Create”.

When done, you can start managing your App Principal.

1.3 Grant permissions to your application

Now you need to find your App Principal and grant necessary rights for your microservice to use.

If your microservice needs to read/write, you need to grant it full access.

To find your App Principal, launch the following URL:

<Base URL>/_layouts/15/appinv.aspx

Enter the Client Id that you noted down into the “App Id” field and click on “Lookup”. Your App Principal should be found.

In the Permission Request XML box, enter the following:

<AppPermissionRequests AllowAppOnlyPolicy=”true”>

<AppPermissionRequest Scope=”http://sharepoint/content/sitecollection/web” Right=”FullControl” />

</AppPermissionRequests>

 

Notice that in the above, I gave FullControl access to it. If you want to give your microservice less permissions, please refer to the Microsoft document below:

https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/add-in-permissions-in-sharepoint

Click the “Create” button which actually updates your App Principal to give it the permission.

1.4 Getting the Realm and App Principal ID

In order for your microservice to obtain an OAuth token, you need two more attributes about your App Principal beyond the Client Id and Client Secret that you noted down previously. They are:

  • Realm
  • Principal Id

To get the Realm, launch the following URL:

<Base URL>/_layouts/15/appprincipals.aspx

Your App Principal should show up in the list like below:

From the “App Identifier”, the Realm is the string after the “@” character.

For Principal Id, use “00000003-0000-0ff1-ce00-000000000000” which is given by Microsoft.

** In case you need to delete the App Principal, click on the cross button on the left.

In summary, we have done the following so far:

  • Create an App Principal for our shared site
  • Assign the access rights to it
  • Obtained Client Id, Client Secret, Real and Principal Id for our microservice get OAuth tokens.

Next, we’ll give some code examples on how to do create, read and delete files from a microservice using Node.js.

2. Code Samples

2.1 Obtain an OAuth Token

Obtaining an OAuth token is a POST operation. The request payload is a string of name-value pairs.

In our example below, we’ll be using the axios npm package.

getOAuthToken : async function() {

    let realm = <the realm obtained in step 1>;

    let principal = "00000003-0000-0ff1-ce00-000000000000";

    let spClientId = <the client Id obtained in section 1> + “@” + realm;

let clientSecret = < the client secret obtained in section 1>

// find the domain name: if my SharePoint access url is

//  https://mycompany.sharepoint.com/teams/MyProjectTeam/Shared%20Documents

// then the domain name would be “mycompany.sharepoint.com”

let domainName = " mycompany.sharepoint.com ";

    let resource = principal + "/" + domainName + "@" + realm;

    let url = "https://accounts.accesscontrol.windows.net/" + realm + "/tokens/OAuth/2";

    let data =

            "client_id="     + encodeURIComponent(spClientId)     + "&" +

            "client_secret=" + encodeURIComponent(client_secret) + "&" +

            "resource="      + encodeURIComponent(resource)      + "&" +

            "grant_type="    + "client_credentials";

       

    return new Promise( async (resolve, reject) => {

        try {

            let response = await axios.post(url, data);

            resolve(response.data.access_token)

        }

        catch (error)

        {       

            reject(error)

        }

    });

}

2.2 Creating a new file under a given folder

For file or directory operation APIs, please refer to this Microsoft document:

https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/sharepoint-net-server-csom-jsom-and-rest-api-index

The following code sample writes the passed-in “content” to the passed-in “fileName” under a folder.

“accessToken” is the one we obtained in the previous step.

createFile : async function(accessToken, fileName, content) {

    let folderName = 'Documents/' + <rootfolder/myfolder/mysubfolder…>;

    //Notice the single quotes in the URL below. They should be part of the URL

    let spUrl = <Base URL>/_api/web/GetFolderByServerRelativeUrl('<folderName>');

    spUrl += "/Files/add(url='" + fileName + "',overwrite=true)";

    return new Promise( async (resolve, reject) => {

        try {

            let result = await axios({method:"POST", url:spUrl, data:content,

                 headers:{Authorization:'Bearer ' + accessToken, "Accept":"application/json"}});

            resolve("Success");

        }

        catch(error) {

            reject(error);

        }

});

}

 

2.3 Delete File

Deleting file is similar to creating file however the operation is “DELETE” instead of “POST”:

deleteFile: async function(accessToken, fileName) {

    let folderName = 'Documents/' + <rootfolder/myfolder/mysubfolder…>;

    //notice the single quote in the URL below.

    let spUrl = <Base URL>/_api/web/GetFolderByServerRelativeUrl('<folderName/fileName>');

    return new Promise( async(resolve, reject) =>{

        try {

            let processResult = await axios({method:"DELETE", url: spUrl, data:{},

                   headers:{Authorization:'Bearer ' + accessToken, "Accept":"application/json"}});

            resolve("Succeed.");

        }

        catch(error) {

            reject(error);

        }

        });

    }

2.4 Get List of Files Under a Folder

The following code sample retrieves the list of files under a folder:

getFilesList : async function(accessToken) {

    let folderName = 'Documents/' + <rootfolder/myfolder/mysubfolder…>;

    //notice the single quote in the URL below.

    let url = <Base URL>/_api/web/GetFolderByServerRelativeUrl('<folderName>')/files?&$format=json;

    return new Promise((resolve, reject)=>{

        try {

axios({method:"GET", url:url, data:{}, headers:{Authorization:'Bearer ' + accessToken, "Accept":"application/json"}}).then(async (dataResp) => {

                    let filesArray = [];

                    for( let i=0; i< dataResp.data.value.length; i++) {

filesArray.push({Name:dataResp.data.value[i].Name, Timestamp: dataResp.data.value[i].TimeLastModified});

                    }

                })

                resolve (filesArray);

            });

        }

        catch(error) {

            reject(error);

        }

    });

}

2.5 Read File Content

The following code sample reads content of a given file.

 

getFileContent : async function(fileName, accessToken) {

    let folderName = 'Documents/' + <rootfolder/myfolder/mysubfolder…>;

    //notice the single quote in the URL below.

    let spUrl = <Base URL>/_api/web/GetFolderByServerRelativeUrl('<folderName>')/files('<fileName>')/$value

    return new Promise( async(resolve, reject) => {

        try {

            let response = await axios({method:"GET", url:spUrl, data:{},

                 headers:{Authorization:'Bearer ' + accessToken, "Accept":"application/json"}});

            resolve(response.data);

        }

        catch(error) {

            reject(error);

        }

    });

}

Summary:

In this post, we introduced how to setup application access to SharePoint folders and files and microservice code samples that create/list/read/delete files. For other file or folder operations, please refer to the Microsoft API document:

https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/sharepoint-net-server-csom-jsom-and-rest-api-index

 

Randa Khaled

Randa Khaled

Author Since: November 19, 2020

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x