如何通过SonarQube API获取指定组件在各分析版本下的指标详情
Great question! I’ve worked with SonarQube’s API extensively, and here’s exactly how you can get the metrics you need for all or specific analysis versions:
1. The Missing Parameter: analysisId
You’re right that the api/measures/component endpoint is the way to go for metric data, but you might have missed that it supports an optional analysisId parameter. This lets you target metrics from a specific historical analysis instead of just the latest one.
2. Step-by-Step Workflow
a. Get the Full List of Analysis IDs
First, use the api/project_analyses/search endpoint you already have to fetch all analysis records for your project:
curl "http://sonar63.rd.tut.fi/api/project_analyses/search?project=org:apache:zookeper2&ps=500"
From the JSON response, extract the key field from each entry in the analyses array—this is your analysisId for each run.
b. Fetch Metrics for Each Analysis ID
For every analysisId you extracted, call the metrics endpoint with the analysisId parameter added. Here’s an example call targeting your specific component and metrics:
curl "http://sonar63.rd.tut.fi/api/measures/component?metricKeys=complexity,ncloc&componentKey=org:apache:zookeper2:src/java/main/org/apache/zookeeper/server/quorum/AuthFastLeaderElection.java&analysisId=YOUR_ANALYSIS_ID"
Replace YOUR_ANALYSIS_ID with each key from the previous step.
c. Aggregate the Results
Parse each response to pull out:
- The analysis ID (from your input or the response’s
analysisIdfield) - Component path
complexityvaluenclocvalue
Then format them into the table you want:
| Analysis | Component | Complexity | ncloc |
|---|---|---|---|
| f1234 | /mypackage/a.java | 10 | 150 |
| f1235 | /mypackage/a.java | 10 | 155 |
3. Bonus: Filter to Specific Analyses
If you don’t need all analyses, you can filter the api/project_analyses/search results first:
- Use the
from/toparameters to target a date range - Look for the
versionfield to match specific project versions - Check the
statusfield to only include successful analyses
Notes to Keep in Mind
- If your project has more than 500 analyses, use the
pageparameter inapi/project_analyses/searchto paginate through results. - Ensure your API token (if required) has the necessary permissions to access historical analysis data.
- Some older SonarQube versions might have slight differences in API response structures, but the
analysisIdparameter has been supported for several major versions.
内容的提问来源于stack exchange,提问作者Davide Taibi

