Here is a snippet that helps create a folder in a custom list (not a document library) using the SharePoint REST API (and jQuery).
This is the main function – no need to change anything in this one:
function createFolderInList(arg) {
var deferred = jQuery.Deferred();
var folder = {
"__metadata": { "type": "SP.ListItem" },
"ContentTypeId": "0x0120",
"Title": arg.folderName
};
var useGUID = arg.listId.charAt(0) === "{";
jQuery.ajax({
"url": _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/" + (useGUID ? "getById('" + arg.listId + "')" : "getByTitle('" + arg.listId + "')") + "/items",
"type": "POST",
"contentType": "application/json;odata=verbose",
"data": JSON.stringify(folder),
"headers": {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
"success": function (data) {
// Successfully created folder, but needs to update FileLeafRef
var updData = { "__metadata": { "type": data.d.__metadata.type }, "Title": arg.folderName.split("/").pop(), "FileLeafRef": arg.folderName };
jQuery.ajax({
"url": _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/" + (useGUID ? "getById('" + arg.listId + "')" : "getByTitle('" + arg.listId + "')") + "/items(" + data.d.Id + ")",
"type": "POST",
"data": JSON.stringify(updData),
"headers": {
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE",
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
"success": function () {
// Done creating and renaming folder
deferred.resolve();
},
"error": function (err) {
deferred.reject(err);
}
});
},
"error": function (err) {
deferred.reject(err);
}
});
return deferred.promise();
}
This is how you call it from your code:
createFolderInList({
"folderName": "Created from code",
"listId": "MyTestList", // List GUID or display name - if you use GUID it must include the curly braces around the GUID like this: {c5c44b98-34f1-4ade-87d3-ed292eee0d84}
}).done(function () {
alert("Folder created");
}).fail(function (err) {
alert("Failed to create folder:\n" + JSON.stringify(err));
});
You can create a subfolder by specifying the folderName like this:
"folderName": "Created from code/subfolder 1"
Alexander