/api/qualitygates/get_by_project Rest API failed with 400 Response code

  • which versions are you using (SonarQube Server / Community Build, Scanner, Plugin, and any relevant extension) - Community BUild v25.5.0.107428 - MQR MODE
  • how is SonarQube deployed: zip
  • what are you trying to achieve - I am trying to get the Sonar Quality Gate - Coverage value using Rest API
  • what have you tried so far to achieve this - Below is the Azure DevOps Task where I am trying to use the REST API approach
- task: PowerShell@2
        name: GetCodeCoverage
        displayName: 'Get Code Coverage from SonarQube'
        condition: succeeded()
        inputs:
          targetType: 'inline'
          script: |
            $projectKey = "$(cliProjectKey)"
            $sonarHost = "$(SONARHOST)"
            $sonarToken = "$(SONAR_TOKEN)"

            $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${sonarToken}:"))
            $headers = @{ Authorization = "Basic $base64AuthInfo" }

            try {
                # Step 1: Get the Quality Gate ID assigned to this project
                $qgProjectUrl = "$sonarHost/api/qualitygates/get_by_project?projectKey=$projectKey"
                Write-Host "🔍 Fetching Quality Gate info: $qgProjectUrl"
                $qgProjectResp = Invoke-RestMethod -Uri $qgProjectUrl -Headers $headers -Method Get
                $qualityGateId = $qgProjectResp.qualityGate.id
                Write-Host "✅ Quality Gate ID: $qualityGateId"

                # Step 2: Get the quality gate details to find the coverage threshold
                $qgDetailsUrl = "$sonarHost/api/qualitygates/show?id=$qualityGateId"
                Write-Host "📋 Fetching Quality Gate details: $qgDetailsUrl"
                $qgDetailsResp = Invoke-RestMethod -Uri $qgDetailsUrl -Headers $headers -Method Get

                $coverageThreshold = 0
                foreach ($cond in $qgDetailsResp.conditions) {
                    if ($cond.metric -eq "coverage") {
                        $coverageThreshold = [double]$cond.errorThreshold
                        break
                    }
                }

                if ($coverageThreshold -eq 0) {
                    throw "❌ Could not find coverage threshold in Quality Gate."
                }

                Write-Host "📊 Coverage threshold from Quality Gate: $coverageThreshold%"

                # Step 3: Get actual coverage value
                $metrics = "coverage,line_coverage,branch_coverage"
                $coverageUrl = "$sonarHost/api/measures/component?component=$projectKey&metricKeys=$metrics"
                Write-Host "📦 Fetching actual coverage: $coverageUrl"
                $coverageResp = Invoke-RestMethod -Uri $coverageUrl -Headers $headers -Method Get

                $actualCoverage = $null
                foreach ($measure in $coverageResp.component.measures) {
                    $metric = $measure.metric
                    $value = $measure.value
                    Write-Host "📊 ${metric}: ${value}"
                    if ($metric -eq "coverage") {
                        $actualCoverage = [double]$value
                    }
                    # Export each metric to pipeline variable
                    $varName = "sonar_${metric}"
                    Write-Host "##vso[task.setvariable variable=$varName;isOutput=true]$value"
                }

                if ($null -ne $actualCoverage) {
                    if ($actualCoverage -ge $coverageThreshold) {
                        Write-Host "✅ Code coverage is sufficient: $actualCoverage% (Threshold: $coverageThreshold%)"
                        Write-Host "##vso[task.setvariable variable=codeCoverageStatus;isOutput=true]PASSED"
                    } else {
                        Write-Warning "❌ Code coverage too low: $actualCoverage% (Threshold: $coverageThreshold%)"
                        Write-Host "##vso[task.setvariable variable=codeCoverageStatus;isOutput=true]FAILED"
                        throw "Code coverage is below threshold."
                    }
                } else {
                    throw "❌ Actual coverage metric not found in SonarQube response."
                }

            } catch {
                Write-Warning "❌ Failed to process coverage: $_.Exception.Message"
                Write-Host "##vso[task.setvariable variable=codeCoverageStatus;isOutput=true]FAILED"
                throw "Error fetching or comparing coverage from SonarQube."
            }
        continueOnError: false

ERROR

Error fetching or comparing coverage from SonarQube.
At C:\Users\azureadmin\agent\nprod\_temp\737693a0-b860-4b22-a0f3-6bdd72f1c677.ps1:73 char:5
+     throw "Error fetching or comparing coverage from SonarQube."
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (Error fetching ...from SonarQube.:String) [], RuntimeException
    + FullyQualifiedErrorId : Error fetching or comparing coverage from SonarQube.
 
Generating script.
========================== Starting Command Output ===========================
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\Users\azureadmin\agent\nprod\_temp\737693a0-b860-4b22-a0f3-6bdd72f1c677.ps1'"
🔍 Fetching Quality Gate info: http://localhost:9000/api/qualitygates/get_by_project?projectKey=***
WARNING: ❌ Failed to process coverage: The remote server returned an error: (400) Bad Request..Exception.Message
##[error]PowerShell exited with code '1'.
Finishing: Get Code Coverage from SonarQub

Hey there.

As noted in the Web API docs, the only valid query parameter to use here is project, not projectKey.

So you should change this line:

to

$qgProjectUrl = "$sonarHost/api/qualitygates/get_by_project?project=$projectKey
1 Like