I am using Python request module to get API response. The response is should be JSON format. From the response how do I retrieve the specific value?
Example of API response:
{
id: 2337975,
sha: "eac6910f89883110e673db27456b67f542df6d75",
ref: "mail-gun",
status: "manual",
created_at: "2021-03-01T09:15:02.409Z",
updated_at: "2021-03-01T09:19:14.983Z",
web_url: "https://gitlab.com/optimus/optimus-ci/-/pipelines/2337975"
}
From here I want retrieve on ID :2337975 assign into a variable in Python.
Here is my code
url = f'https://gitlab.com/api/v4/projects/{pid}/pipelines?updated_after={update_after}&ref={branch}&status=manual'
headers = {'Authorization' : 'Bearer xxxxxxxx'}
response = requests.get(url, headers=headers)
output = json.loads(response.text)
print(output)
I can print the whole JSON format by print(output), but I only want to get a Id value.
Anybody can help?
change this:
output = json.loads(response.text)
to this: (using json function you can receive the json response in string format)
load the response into a python dictionary
response_json = json.loads(response.json())
and access the id key from response dictionary
variable = response_json["id"]
You should save this JSON code in a .json file, then you can open it, load it and then use variable ["id"].
parse the json and use the id as key in json to extract.
loaded_json = json.loads(json_data)
for x in loaded_json:
print("%s: %d" % (x, loaded_json[id]))
since the returned value of a json is an object (JavaScript Object Notation) you can treat it as such and just destructure the object with the [] notation as other pointed out response_json["id"]
I solve this using a naive way. which is convert the object to JSON > python list > python dictionary
response = requests.get(url, headers=headers, proxies=proxyDict)
response_list = response.json()
response_dict = response_list[0]
print(response_dict["id"])
Related
I've been trying to get JSON response out of the following code, but it's throwing an error
from requests import get
import json
url = "https://api.wheretheiss.at/v1/satellites/25544"
response = get(url)
for item in response:
print(item, response[item])
I wanna print the JSON in the following format:
https://i.stack.imgur.com/ZWMbr.png
your code works well to get the correct respone from the url. The problem is that you should parse the raw respone as the json format. Please refer to the following code:
from requests import get
import json
url = "https://api.wheretheiss.at/v1/satellites/25544"
response = get(url)
# dump response into json
result = response.content.decode('utf-8')
result = json.loads(result)
print(result) # print raw json
# print as key-value pairs
for item in result:
print("{0} : {1}".format(item, result[item]))
The output is like following:
Example output
I think you're misunderstanding what the response contains.
Your initial code is good.
from requests import get
import json
url = "https://api.wheretheiss.at/v1/satellites/25544"
response = get(url)
You now have a response. see here for more info.
In this response you have status_code, content, encoding, and the response content as text. it also contains other information about the request. eg we don't want to continue if the request failed
You can simply parse the json by calling json.loads on the decoded response via response.text
parsed_json = json.loads(response.text)
or
parsed_json = response.json()
for item in json_:
print(item, json_[item])
I hope it helps. it is also duplicate to HTTP requests and JSON parsing in Python
I've been stuck trying to pull a certain bit from this api response for a while.
my code:
payload = {
'symbol':'RPX-ETH',
'from':'100603756',
'to':'9516619507'
}
request = requests.get('https://api.kucoin.com/v1/open/chart/history',
params=payload)
jdata = json.loads(request)
print jdata['c']
However I keep getting this error:
TypeError: expected string or buffer
The api response only using .json() for reference:
{u'c': [0.00024, 0.000171, 0.000163, 0.000151, 0.000159, 0.000164}
request is the whole requests response object. You need to pass request.body.
However there is no need to do that at all because request.json() does it for you and returns a parsed Python data structure.
You can use the request.json to access the return data as a dictionary.
Replace
jdata = json.loads(request)
print jdata['c']
With
jdata = request.json()
print jdata['c']
I'm using this :
import requests
url = "https://api.bitfinex.com/v1/pubticker/btcusd"
response = requests.request("GET", url)
print (response.text)
The output is:
{"mid":"4432.95","bid":"4432.9","ask":"4433.0","last_price":"4432.9","low":"4276.9","high":"4482.0","volume":"32877.86104158","timestamp":"1506955900.864889"}
I would like to grab the last price, as a float, in order to use it for some calculations....
I cannot figure out how to do that...
Can you help me please ?
Thx
Try like this:
import requests
url = "https://api.bitfinex.com/v1/pubticker/btcusd"
response = requests.request("GET", url)
data = response.json()
last_price = float(data.get('last_price'))
print(last_price)
Response is a JSON so requests will do the job of parsing it for you, if you call the .json() method on your response. You just need to do:
import requests
resp_json = requests.get("https://api.bitfinex.com/v1/pubticker/btcusd").json()
# resp_json is a native Python dict representing the JSON response content. But since all values are strings in the response, you need to convert them to a float manually.
print(float(resp_json["last_price"]))
I'm implemented a code to return Json value like this
{ "key1":"1", "key2":"2", ......}
But I want to get only value of key1. so I first defined info to get Json.
info = requests.get(url, headers=headers)
And use info.text['key1'] to get value of key1. but i got error. could anyone suggest any solution?
JSON is a format, but the data are included as text. Inside the info.text you have a string.
If you want to access the json data you can do info.json()['key1']. This will work only if the response content type is defined as JSON, to check that do
info.headers['content-type'] should be application/json; charset=utf8
http://docs.python-requests.org/en/master/
Otherwise you will have to manually load the text to json, with json library for example
import json
response = requests.get(url, headers=headers)
data = json.loads(response.text)
import json
info = requests.get(url, headers=headers)
jsonObject = json.loads(info)
key1= jsonObject['key1']
or
jsonObject = info.json()
key1= jsonObject['key1']
I am using Python, and I sent a request to a URL and received a reply using httplib2. The reply I got was in JSon, how do I access a specific parameter. What I have at the moment is:
resp, content = parser.request(access_token_uri, method = 'POST', body = params, headers = headers)
raise Exception(content['access_token'])
and I get the error
string indices must be integers, not str
How do I do it?
Thanks
Well if the response type is json and it comes in type str.
If you are running 2.4 of Python use simplejson if 2.6 use json:
import json
# Your code
retdict = json.loads(content)
Then treat it like a dictionary.
accesstoken = retdict['access_token']
You can use dump;
result = json.dumps(content)
result = json.loads(result)