3
votes

I am struggling with pushing an update to an existing file in a VSTS Git repository. The documentation https://docs.microsoft.com/en-us/rest/api/vsts/git/pushes/create#update_a_file shows what to do.

When I use GET instead of POST, I get all existing pushes. So basically the request is working. This is my URL https://mine.visualstudio.com/_apis/git/repositories/ad3d7615-6e4a-4988-bd3f-ca80d7ec9791/pushes?api-version=4.1-preview.

I am testing the request from a console application. The body is created from a dynamic that is serialized later. The filecontent is a string var x=1;.

dynamic body = new
{
   refUpdates = new[] { new { name = "refs/heads/master", oldObjectId = branchObjectId } },
   commits = new[] {
         new {
            comment = "Updated Configuration" ,
            changes = new[] {
               new {
                  changeType = "edit",
                  item = new { path = "/files/filename.js"},
                  newContent = new { content = filecontent, contentType = "rawtext" }
               }
            }
         }
      }
};

The request looks like this:

using (HttpClient client = new HttpClient())
{
   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
   byte[] login = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalaccesstoken));
   client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(login));

   var content = new StringContent(body, Encoding.UTF8, "application/json");
   using (HttpResponseMessage response = client.PostAsync(url, content).Result)
   {
      response.EnsureSuccessStatusCode();

      string responseBody = await response.Content.ReadAsStringAsync();
      responseBodyAction.Invoke(responseBody);
   }
}

It is not successful, as the following Exception is thrown:

System.Net.Http.HttpRequestException: 'Response status code does not indicate success: 404 (Not Found).

The body is a valid JSON.

Some API calls need the url .vsrm.visualstudio.com instead of .visualstudio.com. But not in this case.

I am out of ideas. Did anybody successfully push an update to VSTS and can show me how to do it?

1
I just tried changeType = "add", instead of edit and it worked. With a new filename of course. Digging further...René

1 Answers

0
votes

As mentioned in a comment I was able to add instead of edit. The solution is to first check in a file and then send an update/edit. If there is no existing file, an edit will fail with the Exception.