Get list of recent documents in SharePoint

Similar to my last post Get list of frequent sites in SharePoint , this time I’m using the same approach to query a different API and get the recent documents for the current user.

SharePoint offers an OOB web part that you can use to list the recent documents for the current user. But what if you need the exact same information for a custom SharePoint Framework solution?

WARNING

Unfortunately, it seems that this is not currently possible using the SharePoint REST API or MS Graph. The API used on the sample code below is currently not documented and you should understand the risks when using it!

Hopefully, Microsoft will make this information available soon via MS Graph or document this API.

Recent documents

[4th Nov 2019 – Update – Added new required HTTP headers when requesting data from the service: X-Office-Platform, X-Office-Application, X-Office-Version]

You can also get the code from this gist

// within your web part onInit method, get the request digest token
const digestCache: IDigestCache = this.context.serviceScope.consume(DigestCache.serviceKey);
const requestDigest = await digestCache.fetchDigest(this.context.pageContext.web.serverRelativeUrl);


//now on your data access layer
// get token
const authRequestHeaders: Headers = new Headers();
authRequestHeaders.append("Accept", "application/json;odata.metadata=minimal");
authRequestHeaders.append("Content-Type", "application/json; charset=utf-8");
authRequestHeaders.append("odata-version", "4.0");
authRequestHeaders.append("x-requestdigest", this._requestDigest);

var resourceData = {
  "resource": "https://officeapps.live.com",
};

const authRequestOptions: IHttpClientOptions = {
  headers: authRequestHeaders,
  body: JSON.stringify(resourceData),
};

const authEndpointUrl = this._webAbsoluteUrl + '/_api/SP.OAuth.Token/Acquire';
const authRawResponse = await this._httpClient.post(authEndpointUrl, HttpClient.configurations.v1, authRequestOptions);
const auth = await authRawResponse.json();

// get data
const dataRequestHeaders: Headers = new Headers();
dataRequestHeaders.append("Authorization", "Bearer " + auth.access_token);
dataRequestHeaders.append("Content-Type", "application/json");
dataRequestHeaders.append("X-Office-Platform", "Web");
dataRequestHeaders.append("X-Office-Application", "120");
dataRequestHeaders.append("X-Office-Version", "*");

const dataRequestOptions: IHttpClientOptions = {
  headers: dataRequestHeaders,
};

const dataEndpointUrl = `https://ocws.officeapps.live.com/ocs/v2/recent/docs?apps=Word,Excel,PowerPoint,Visio,OneNote,Sway,PdfViewer&show=${count}&sort=Date`;
const dataRawResponse = await this._httpClient.get(dataEndpointUrl, HttpClient.configurations.v1, dataRequestOptions);
const data = await dataRawResponse.json();

Leave a Reply

Your email address will not be published. Required fields are marked *