You can use it as below using REST api:
var ctx = SP.ClientContext.get_current();
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Web.CreateAnonymousLink";
console.log(url);
$.ajax(
{
'url': url,
'method': 'POST',
'data': JSON.stringify({
'url': _spPageContextInfo.webAbsoluteUrl + '/Shared Documents/test.txt',
'isEditLink': true
}),
'headers': {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'X-RequestDigest': $('#__REQUESTDIGEST').val()
},
'success': function (data) {
console.log(data.d.CreateAnonymousLink);
},
'error': function (err) {
console.log(JSON.stringify(err));
}
}
);
}
If you are using CSOM C#, you can use it as below:
// Create anonymous link for document
string link = ctx.Web.CreateAnonymousLinkForDocument(
"https://contoso.sharepoint.com/docs/sample.doc",
ExternalSharingDocumentOption.View);
if you want it to expire after certain days, it is as below:
// Create anonymous link with expiration for document
string link = ctx.Web.CreateAnonymousLinkWithExpirationForDocument(
"https://contoso.sharepoint.com/docs/sample.doc",
ExternalSharingDocumentOption.Edit,
DateTime.Now.AddDays(7));
Reference links:
External sharing API for SharePoint and OneDrive for Business
Rest Api Generate Guest Link SharePoint Online
PnP.Core.ExternalSharing