Search code examples
c#tfsazure-devops-rest-apitfs-sdk

TFS REST API Get items that failed to build


Someone know the way to get projects that failed to build, through the TFS REST API?


Solution

  • You can download the build logs with Build - Get Build Log Rest API. You need to know which log id is the build log (if you have few tasks so each task has a log), so you can check all the available logs with Build - Get Build Logs Rest API, then iterate them and check the what is the build. after you have the log you can search and filter the errors.

    A small example with PowerShell:

    $collection = "http://tfs-server:8080/tfs/collection"
    $project = "team-project"
    $buildId = 10
    
    #"api-version=4.1" is for TFS 2018, for other versions you need to change the number
    $logsUrl = "$collection/$project/_apis/build/builds/$buildId/lgos?api-version=4.1"
    $logs = Invoke-RestMethod -Uri $logsUrl -Method Get -UseDeafultCredntials -ContentType application/json
    
    $buildLog = ""
    ForEach($log in $logs.value)
    {
        $urlLog = "$collection/$project/_apis/build/builds/$buildId/logs/$($log.id)?api-version=4.1"
        $logDetails = Invoke-RestMethod -Uri $urlLog -Method Get -UseDefaultCredntials -ContentType application/json
        if($logDetails.Contains("msbuild"))
        {
             $buildLog = $logDetails
             break
        }
    }
    # Now you have the logs in your hand and you can find in which projects have errors
    

    If you want to do it with C# you can call the Rest API with HttpClient:

    using (HttpClient client = new HttpClient(new HttpClientHandler() { UseDeafultCredntials = true } )
    {
         string url = "the-url-from-above-powershell-script";
         var method = new HttpMethod("GET");
         var reqeust = new HttpRequestMessage(mehtod,url);
         var result = await client.SendAsync(rqeuest);
    }
    // In this way you get the Rest API response, so you need to it once for the logs, iterate them to get each log and then filter the errors.