0

I am a little new to using the REST API for Azure DevOps and have it working fine where I can send my requests that are basically the URIs I see on the website for the API. Then I get that JSON response and de-serialize it into a class from the JSON response and am off running.

Below is an example of a function I use to get a Work Item by it's ID. It uses the URI from the website. I can also test things by pasting the URI into my browser and then see the response.

My question is, How do I use the command for Updating the Workitem (Add Link for example) which is not a URI that I can test by pasting it into my browser. Instead it is a JSON message.

here is API Website which shows the JSON message needed to add a link to a work item.
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-rest-5.1#add-a-link

this is the JSON message they have there for updating a WorkItem Link: [ { "op": "test", "path": "/rev", "value": 3 }, { "op": "add", "path": "/relations/-", "value": { "rel": "System.LinkTypes.Dependency-forward", "url": "https://dev.azure.com/fabrikam/_apis/wit/workItems/300", "attributes": { "comment": "Making a new link for the dependency" } } } ]

Do I need a different function to send it the JSON message and then the function could return me the JSON Response? I can not find an example of what that function might look like.

Any Advice on how to send the JSON message instead of the URI to get a response would be greatly appreciated.

===================== UPDATE =====================

The one answer definitely helped me get this finally working. I pasted in the updated function in case it helps anyone else. I know it is tricky to find VB.NET samples for this. :)

THANKS!

UPDATED CODE==========================================================

Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
    Dim client As HttpClient = New HttpClient()
    SetUpHttpClient(client)
    Dim statusCode As String = "NOTHING"
    Dim responseBody As String = "NOTHING"
    Try
        If jsonMessageBody.Length > 0 Then
            

'##################################################################### '### For all PATCH operations that have a URI and a JSON message ### '##################################################################### Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json") Dim method = New HttpMethod("PATCH") Dim request = New HttpRequestMessage(method, uri) With {.Content = patchValue} Dim response = client.SendAsync(request).Result responseBody = response.Content.ReadAsStringAsync.Result() Else '####################################################### '### For all other operations that have just a URI ### '####################################################### Using response As HttpResponseMessage = client.GetAsync(uri).Result statusCode = response.StatusCode.ToString() response.EnsureSuccessStatusCode() responseBody = response.Content.ReadAsStringAsync().Result End Using End If Catch End Try Dim answer As String() = {statusCode, responseBody} Return answer End Function

Public Function GetTestCase(organization As String, project As String, TestCaseID As String) As WorkItemApi

    Dim dc As New DevCon.DevOpsConnector

    Dim response As String() = dc.GetRequest($"https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{TestCaseID}?api-version=5.1&$expand=all")


    If response(0) <> "OK" Then
        Return Nothing
    End If

    Dim result As WorkItemApi = JsonConvert.DeserializeObject(Of WorkItemApi)(response(1))

    Return result

End Function


Public Async Function GetRequestAsync(ByVal getRequest As String) As Task(Of String())
    Dim client As HttpClient = New HttpClient()
    SetUpHttpClient(client)
    Dim statusCode As String = "NOTHING"
    Dim responseBody As String = "NOTHING"

    Try

        Using response As HttpResponseMessage = client.GetAsync(getRequest).Result


            statusCode = response.StatusCode.ToString()
            ' Console.WriteLine("Response: " & statusCode)
            response.EnsureSuccessStatusCode()
            responseBody = response.Content.ReadAsStringAsync().Result
        End Using

    Catch
    End Try

    Dim answer As String() = {statusCode, responseBody}
    Return answer
End Function

2 Answers 2

0

You need to serialize the fields array into a json string. Check the following sample in C# using the HttpClient class:

    public WorkItem CreateBugUsingHTTP()
    {
        string uri = _uri;
        string personalAccessToken = _personalAccessToken;
        string project = _project;
        string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken)));

        Object[] patchDocument = new Object[4];

        patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = "Authorization Errors" };
        patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http://msdn.microsoft.com/en-us/library/live/hh826547.aspx" };
        patchDocument[2] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "1" };
        patchDocument[3] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Severity", value = "2 - High" };

        using (var client = new HttpClient())
        {
            //set our headers
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

            //serialize the fields array into a json string
            var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");

            var method = new HttpMethod("POST");
            var request = new HttpRequestMessage(method, uri + "/" + project + "/_apis/wit/workitems/$Bug?api-version=5.1") { Content = patchValue };
            var response = client.SendAsync(request).Result;

            //if the response is successfull, set the result to the workitem object
            if (response.IsSuccessStatusCode)
            {
                var workItem = response.Content.ReadAsAsync<WorkItem>().Result;

                Console.WriteLine("Bug Successfully Created: Bug #{0}", workItem.Id);
                return workItem;
            }
            else
            {
                Console.WriteLine("Error creating bug: {0}", response.Content);
                return null;
            }
        }
    }

You could get started from the documentation below:

https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1

Sign up to request clarification or add additional context in comments.

Comments

0
Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
    Dim client As HttpClient = New HttpClient()
    client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
    client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", _accessTokenHttpClient)
    Dim statusCode As String = "NOTHING"
    Dim responseBody As String = "NOTHING"
    Try
        If jsonMessageBody.Length > 0 Then
            '#####################################################################
            '###  For all PATCH operations that have a URI and a JSON message  ###
            '#####################################################################
            Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json")
            Dim method = New HttpMethod("PATCH")
            Dim request = New HttpRequestMessage(method, uri) With {.Content = patchValue}
            Dim response = client.SendAsync(request).Result
            responseBody = response.Content.ReadAsStringAsync.Result()
        Else
            '#######################################################
            '###  For all other operations that have just a URI  ###
            '#######################################################
            Using response As HttpResponseMessage = client.GetAsync(uri).Result
                statusCode = response.StatusCode.ToString()
                response.EnsureSuccessStatusCode()
                responseBody = response.Content.ReadAsStringAsync().Result
            End Using
        End If
    Catch
    End Try
    Dim answer As String() = {statusCode, responseBody}
    Return answer
End Function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.