2

I am trying to update the multiple choice field in sharepoint online using rest api. I am getting 401 bad request error.

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("XXXXX/_api/web/getfilebyserverrelativeurl('/sites/Sample/TestDoc.docx')/ListItemAllFields/");

string stringData = 
@"{'__metadata': { 'type':'SP.ListItem' }, 
'TestColumn': { '__metadata': { 'type' : 'Collection(Edm.String)', results: ['Test1']}}}";

request.ContentLength = stringData.Length;

StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(stringData);
writer.Flush();

 response = (HttpWebResponse)request.GetResponse();

Any help?

Jacob Santiago
  • 313
  • 3
  • 9

1 Answers1

5

Most likely the payload is invalid in your example:

string stringData = 
@"{'__metadata': { 'type':'SP.ListItem' }, 
'TestColumn': { '__metadata': { 'type' : 'Collection(Edm.String)', results: ['Test1']}}}";

The point is the type SP.ListItem corresponds to Generic list, in your example it is a Documents library.

So, a valid entity type name needs to be provided, you could utilize the following endpoint to determine metadata type:

Endpoint:

Url: /_api/lists/getbytitle('<list title>')?$select=ListItemEntityTypeFullName
Method: GET

Secondly, the Update operation requires the following properties to be specified with request:

  • Create an HTTP request using the POST verb.
  • Add an X-HTTP-Method header with a value of MERGE.
  • Add an If-Match header with a value of the entity’s original ETag.

You could refer this post for a more details.

And last but no least, Content-Type and Accept request headers needs to be specified (follow this article for a more details), for example:

request.Accept = "application/json;odata=verbose";
request.ContentType = "application/json;odata=verbose";

The following example summarizes it and demonstrates how to update multi-choice field value:

var requestUrl = $"{webUrl}/_api/web/getfilebyserverrelativeurl('{fileUrl}')/ListItemAllFields";
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Credentials = GetCredentials(userName, password);
request.Accept = "application/json;odata=verbose";
request.ContentType = "application/json;odata=verbose";
request.Method = "POST";
request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
request.Headers.Add("X-RequestDigest", formDigestVal);
request.Headers.Add("X-HTTP-Method", "MERGE");
request.Headers.Add("If-Match", "*");


var payload = @"{
                        '__metadata': { 'type':'SP.Data.Shared_x0020_DocumentsItem' },
                        '<ColumnName>': { '__metadata': { 'type' : 'Collection(Edm.String)'}, results: ['Val1']}
        }";

request.ContentLength = payload.Length;
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(payload);
writer.Close();

var response = (HttpWebResponse)request.GetResponse();
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193