JavaScript, SharePoint, Web Services

Using SharePoint REST to create a folder

I was tasked with creating some folders in a Picture Library and I thought that this would be the perfect opportunity to use the SharePoint 2013 REST API for the first time.
It was actually quite easy:

function CreateFolder (){
    var url_web;
    var pictureLibrary
    var folder_name;
    var folder_path;

    url_web = _spPageContextInfo.webAbsoluteUrl;
    pictureLibrary = 'Pictures';
    folder_name = 'jasonscript';
    folder_path = pictureLibrary + '/' + folder_name;

    jQuery.ajax({
        'url' : url_web + "/_api/Web/Folders/Add('"+ folder_path + "')",
        'type' : 'POST',
        'headers' : { 
            'accept' : 'application/json; odata=verbose', 
            'content-type' : 'application/json; odata=verbose',
            'X-RequestDigest' : $('#__REQUESTDIGEST').val()
        },
        'success' : function (evt){
            // folder has been created
        },
        'error' : function (jqXHR, textStatus, errorThrown){
            // handle the error
        } 
    }); 
 }

The biggest problem that I had was that I found that the Add method seems to only accept values wrapped in single quotes.
I typically use single quotes to define my strings

    var myString = 'wrapped in single quotes';

However, when I tried this

    url_web + '/_api/Web/Folders/Add("'+ folder_path + '")'

I kept getting ‘bad request’ errors. Switching the quotes around resolved this problem.

    url_web + "/_api/Web/Folders/Add('"+ folder_path + "')"

Weird

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s