Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Administration

SonarQube Web API: Measures, Issues, Gates and Automation

Use the SonarQube Web API to read quality gate status, measures, issues and hotspots, handle paging, and automate reports and badges, with response parsers you can run.

Everything the SonarQube UI shows comes from a Web API under /api/..., and you can call it from scripts. That makes it easy to build dashboards, nightly reports, release checks, or migrations. Every server documents its own API at /web_api (Administration > Web API in the menu), with the parameters of every endpoint for your exact version: use that page as the reference, because endpoints and parameters evolve.

SonarQube is not runnable on this site, so the requests below are real examples for your server, while the TryIts parse sample responses written for this lesson in the documented shape.

Basics

  • Base URL: your server, for example https://sonar.example.com.
  • Authentication: a token as basic-auth user name with an empty password (curl -u "$SONAR_TOKEN:") or Authorization: Bearer <token>. Anonymous access works only if the project is public and authentication is not forced.
  • Responses are JSON. Read endpoints use GET; changes use POST.
  • Many endpoints take projectKey or component; branches and pull requests use branch= and pullRequest=.
  • Lists are paged with p (page, from 1) and ps (page size, up to 500); the response contains a paging object with pageIndex, pageSize and total.

Quality gate status

Terminal
curl -s -u "$SONAR_TOKEN:" \
  "$SONAR_HOST_URL/api/qualitygates/project_status?projectKey=shop-api"

The response has this structure (values are an example):

JSON
{
  "projectStatus": {
    "status": "ERROR",
    "conditions": [
      { "status": "OK",    "metricKey": "new_security_hotspots_reviewed", "comparator": "LT", "errorThreshold": "100", "actualValue": "100" },
      { "status": "ERROR", "metricKey": "new_coverage", "comparator": "LT", "errorThreshold": "80", "actualValue": "72.4" }
    ],
    "ignoredConditions": false
  }
}

status is OK, WARN, ERROR or NONE. Each condition gives the metric, the comparison (LT means error when actual is less than the threshold, GT when greater), the threshold and the actual value. Add &branch=main or &pullRequest=482 to check a particular one. A release script can fail when projectStatus.status is not OK.

Measures

Terminal
curl -s -u "$SONAR_TOKEN:" \
  "$SONAR_HOST_URL/api/measures/component?component=shop-api&metricKeys=coverage,bugs,vulnerabilities,code_smells,sqale_index,duplicated_lines_density,ncloc"

The measure values come back as strings in component.measures[]. Useful metric keys: ncloc (lines of code), coverage, new_coverage, bugs, vulnerabilities, code_smells, security_hotspots, security_hotspots_reviewed, sqale_index (debt in minutes), sqale_debt_ratio, duplicated_lines_density, cognitive_complexity, alert_status. The list of all metrics is at /api/metrics/search, and the history of values at /api/measures/search_history.

Issues and hotspots

Terminal
# Open vulnerabilities and bugs on main, 100 per page
curl -s -u "$SONAR_TOKEN:" \
  "$SONAR_HOST_URL/api/issues/search?componentKeys=shop-api&branch=main&types=BUG,VULNERABILITY&resolved=false&ps=100&p=1"

# Hotspots still waiting for review
curl -s -u "$SONAR_TOKEN:" \
  "$SONAR_HOST_URL/api/hotspots/search?projectKey=shop-api&status=TO_REVIEW"

Parameter names differ between versions (for example the newer impact-based filters next to the older severities and types), so check /web_api before relying on them. Changing a status, such as marking a hotspot safe, is a POST to /api/hotspots/change_status with the hotspot key, status and resolution. It needs the review permission, the same as in the UI.

Stand-in: evaluate the gate response in a release script

A release script reads the gate JSON and decides. The block below does that on the sample response above.

JS Stand-in: release check on gate JSON

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Paging through all issues

A search returns at most ps items per page, and the API refuses to go beyond 10,000 results in a plain search, so large exports are split by filters (for example by date or rule). A generic paging loop looks like this stand-in, which uses a fake fetch function.

JS Stand-in: collect every page

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Automation ideas

  • Release gate: CI step calls project_status for the release branch and blocks the deploy on ERROR.
  • Weekly report: query measures/component for a list of projects and post a table to chat or email.
  • Badges: the project's Information page offers badge URLs for the gate and metrics; tokens for badges are separate from analysis tokens, so use the badge token settings and not a user token.
  • Bulk setup: create projects (/api/projects/create), set the quality gate (/api/qualitygates/select), grant permissions (/api/permissions/add_group) from a script when onboarding many repositories.
  • Cleanup: find projects with no analysis for N days (/api/projects/search with analyzedBefore) and review them for deletion.
  • Webhooks: the server can POST to your URL when a background task finishes, with the gate result in the JSON; configure it under Administration > Configuration > Webhooks (or per project). Verify the HMAC signature header if you set a secret.

Safe scripting rules

  1. Use a dedicated token with the least permissions needed (a project analysis token cannot read all measures; a user token of a viewer account can).
  2. Do not log tokens; mask them in CI.
  3. Respect rate: the API has no strict limit by default, but loops over thousands of projects should add pauses.
  4. Treat the response shape as versioned; pin your server version in tests, and read deprecation notices in /web_api.
  5. Validate JSON before use and handle errors arrays returned with HTTP 4xx codes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which endpoint returns the quality gate result for a project?

    project_status returns the gate status and its conditions.
  2. 2. In a gate condition, comparator LT with errorThreshold 80 means what?

    LT means 'less than': the condition fails when the actual value falls below the threshold.
  3. 3. Where do you find the exact parameters of every endpoint on your server?

    Each server documents its own API version at /web_api.
  4. 4. What are p and ps?

    They control paging: p is the page, ps the page size.

Summary

  • The Web API exposes everything the UI shows; use /web_api for the exact reference.
  • Authenticate with a token and handle paging with p and ps.
  • Read gate status, measures, issues and hotspots; change statuses with permissioned POSTs.
  • Automate release checks, reports, onboarding and webhooks with least-privilege tokens.

Next: Project: add a quality gate to a repository