In this post, we’ll see the syntax and code snippet to create a new webpart page in a document library using REST API.

Syntax:

REST API Endpoint:

https://SharePointSiteURL/_api/web/getfolderbyserverrelativeurl(<URL1>)/files/addtemplatefile(urloffile=<URL2>,templatefiletype=0)

REST API endpoint to use in Add-ins:

<appweburl>/_api/SP.AppContextSite(@target)/web/getfolderbyserverrelativeurl(<URL1>)/files/addtemplatefile(urloffile=<URL2>,templatefiletype=0)”?@target=<hostweburl>

Parameters:

URL1 – Server relative URL of a Folder

URL2 – Server relative URL of file where you want to save the folder

Note: templatefiletype is used to specify the file template for the file creation. 0 (zero) – represents the a standard page template.

Code Snippet:

Embed Code Snippet:

The following code snippet can be added to a SharePoint page or in content editor web part as a script. This example is used to add a new web part page to the Site Pages library in SharePoint.


$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('/SitePages')/files/addtemplatefile(urloffile='/SitePages/newwebpartpage.aspx',templatefiletype=0)",
method: "POST",
data: JSON.stringify(data),
headers: {
"Accept": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
//RESULTS HERE!!
alert('File created successfully!');
},
error: function(err) {
alert('Error: ' + err.responseText);
}
});

Add-in Code Snippet

The following code snippet is used in SharePoint Add-in to add a new web part to the Site Pages library in target SharePoint site.


// Load the js files and continue to the successHandler 
$.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);

// Function to prepare and issue the request to get 
// SharePoint data 
function execCrossDomainRequest() {
 // Initialize the RequestExecutor with the add-in web URL. 
 var executor = new SP.RequestExecutor(appweburl);
 // Issue the call against the add-in web. 
 // To add webpart page, use tempaltefiletype=0 in addtemplatefile method using REST we can hit the endpoint: 
 // The response formats the data in the JSON format. 
 executor.executeAsync({
 url: appweburl + "/_api/SP.AppContextSite(@target)/web/getfolderbyserverrelativeurl('/SitePages')/files/addtemplatefile(urloffile='/SitePages/newwebpartpage.aspx',templatefiletype=0)&@target='" + hostweburl + "'",
 method: "POST",
 data: JSON.stringify(data),
 headers: {
 "Accept": "application/json; odata=verbose",
 "X-RequestDigest": $("#__REQUESTDIGEST").val()
 },
 success: successHandler,
 error: errorHandler
 });
}
// Function to handle the success event. 
function successHandler(data) {
 console.log('File created successfully!')
 alert('File created successfully!');
}

function errorHandler(data, errorCode, errorMessage) {
 console.log("Could not complete cross-domain call: " + errorMessage);
}