Lines of code via API


(Aaron Wise) #1

What would be the best way to get the lines of code for a project via the SonarQube API?

Version
6.7.1.35068

None of these endpoints are available but this is the output from our instance.
{
“path”: “api/resources”,
“since”: “2.10”,
“description”: “Removed since 6.3, please use api/components and api/measures instead”,
“actions”: [
{
“key”: “index”,
“description”: “The web service is removed and you’re invited to use the alternatives:

  • if you need one component without measures: api/components/show</li>
  • if you need one component with measures: api/measures/component</li>
  • if you need several components without measures: api/components/tree</li>
  • if you need several components with measures: api/measures/component_tree</li></ul>”,
    “since”: “2.10”,
    “deprecatedSince”: “5.4”,
    “internal”: false,
    “post”: false,
    “hasResponseExample”: true,
    “changelog”: [
          ]
        }
      ]
    }

(Emre Dundar) #2
  • This is the api url to get the lines of code of a project:

http://{your_sonar_url}/api/measures/component?componentKey={your_project_key}&metricKeys=ncloc

  • And here is the basic python code for calling web api and getting LoC metric result:
import json
from base64 import b64encode
from urllib.parse import urlencode
from urllib.request import urlopen, Request

user, password = 'admin', 'xxxxx'
data = urlencode(dict(From='+17035551212', To='+17035551212', Body='test')).encode('ascii')
headers = {'Authorization': b'Basic ' + b64encode((user + ':' + password).encode('utf-8'))}

api_url = "http://_{your_sonar_url}_/api/measures/component?componentKey=_{your_project_key}_&metricKeys=ncloc"
api_response = urlopen(Request(api_url, data, headers)).read().decode()

for project in json.loads(api_response)["component"]["measures"]:
    lines_of_code = project["value"]
print(lines_of_code)

(Aaron Wise) #3

Thank you. That worked.