Search code examples
restdelphisharepointmetadataindy

Updating Sharepoint metadata using REST api gives 400 bad request error


I am trying to update a Sharepoint file's metadata using the Indy TidHTTP component in my Delphi program.

Within this program I have successfully managed to do everything else I need to do with the Sharepoint files (create/rename/delete/edit/Checkout etc). But whenever I try to update some metadata property I get a "400 Bad Request" exception. I know that my RequestDigest string is correct because I am able to upload new contents to the file.

I have seen many similar problems reported and have tried all of the suggestions without success. (One suggestion was to access the file as a list item rather than using the file url, which I have done in the code below.)

var
   str,body,MyUrl: string;
   stream: TStringStream;
begin
   MyUrl:=MySite+'_api/web/Lists/getByTitle(''CM Library'')/Items(2)';
   body:='{"__metadata":{"type":"SP.Data.CM_x0020_LibraryItem"},"Title":"UpdatedTitle"}';
   stream := TStringStream.Create(body, TEncoding.UTF8);
   try
      IdHTTP.Request.Accept:='application/json;odata=verbose';
      IdHTTP.Request.ContentType:='application/json';
      IdHTTP.Request.ContentLength:=stream.size;
      IdHTTP.Request.CustomHeaders.Values['X-RequestDigest']:=RequestDigest;
      IdHTTP.Request.CustomHeaders.Values['IF-MATCH']:='*';
      IdHTTP.Request.CustomHeaders.Values['X-HTTP-Method']:='MERGE';
      try
        str := IdHTTP.Post(MyUrl,stream);
      except
         on E : Exception do
            ShowMessage('Exception: '+E.Message);  
      end;
   finally
     stream.Free;
   end;
    // Displays 'Exception: HTTP/1.1 400 Bad Request'

Solution

  • I found it! I needed to add ";odata=verbose" to Request.ContentType (as well as Request.Accept)

    Sorry to trouble the community, but I was struggling with this for several days!!