1

I am a newbie to python and api queries. However, I am learning python automation in the process. Request your kind help here.

I have a SonarQube API call through which I fetch some metrics or values as a JSON response on my browser. I read that curl or through requests module in python, we would be able to download the response into a variable or file. How much ever I try, I am not able to do through a program. Right now, I am hard coding it in a variable and proceeded with my next steps. Can someone help me here.

Query I use:

https://sonar.com:9000/sonar/api/measures/component?component=abcdef&branch=test&metricKeys=ncloc

I get JSON response like this on the browser:

  "component": {
    "id": "AXK4GYajYOT4RM44Ji",
    "key": "abcdef",
    "name": "test",
    "qualifier": "TRK",
    "measures": [
      {
        "metric": "ncloc",
        "value": "100000"
      }
    ],
    "branch": "test"
  }
}

My intention is to store all of this in a python variable.

agabrys
  • 8,728
  • 3
  • 35
  • 73

1 Answers1

0

If you use the requests package you can store the response in the data variable as follows:

import requests

params = {'component': 'abcdef', 'branch': 'test', 'metricKeys': 'ncloc'}
r = requests.get('https://sonar.com:9000/sonar/api/measures/component', params=params)
data = r.json()

print(data)

if you then want to store it as a JSON file:

import json
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)
dh762
  • 2,259
  • 4
  • 25
  • 44
  • Thank you for responding. I have tried this solution. The error I see is: AttributeError: module 'requests' has no attribute 'get' Any suggestions? – Nirmal Gollapudi Aug 13 '20 at 09:06
  • do you have a custom file called `requests.py` already (which would conflict with the package)? see here also: https://stackoverflow.com/questions/12258816/module-object-has-no-attribute-get-python-error-requests – dh762 Aug 13 '20 at 09:11
  • No. I dont have any requests.py file in my project directory. I have a JSON reponse like this: '''{ "component": { "id": "AXK4GYajYOT4RM44Ji", "key": "abcdef", "name": "test", "qualifier": "TRK", "measures": [ { "metric": "ncloc", "value": "134439" } ], "branch": "test" } }''' I have requests module installed. requests 2.24.0 Error is AttributeError: module 'requests' has no attribute 'get' – Nirmal Gollapudi Aug 13 '20 at 10:31
  • I tested it and it works in a clean environment. Make sure you do not have any folders or files in your `PYTHONPATH` that are named `requests`. – dh762 Aug 13 '20 at 13:00