Get Specific Data form request.post response in Python - python

I am using sendgrid api to send email to users and then check the status,
res = requests.post(url)
print type(res)
and it prints type as <class 'requests.models.Response'>
on the Postman API client I am getting this:
{
"message": "error",
"errors": [
"JSON in x-smtpapi could not be parsed"
]
}
I want to fetch only the message value from response. I have written the following piece of code but doesn't work:
for keys in res.json():
print str(res[keys]['message'])

You don't need to loop; just access the 'message' key on the dictionary returned by the response.json() method:
print res.json()['message']
It may be easier to follow what is going on by storing the result of the response.json() call in a separate variable:
json_result = res.json()
print json_result['message']
The reason Postman API returns an error message is because your POST didn't actually contain any data; you probably want to send some JSON to the API:
data = some_python_structure
res = requests.post(url, json=data)
When you use the json argument, the requests library will encode it to JSON for you, and set the correct content type header.

Related

Getting different responses from postman vs. python API call

I'm trying get the same data from an API call in Postman using Python.
The call is relatively simple. It uses Basic Authorization that only requires the API key being passes as the username, and a dynamic component: csv_key variable that is passed from earlier codes.
I was able to successfully made the request (status code 200), but the response from Python is different from the one in Postman. It's missing all key-value pairs except the firs two: id and description.
I'm getting this response from postman:
response from postman
{
"id": "63c9c0927885bf003ecd3a1b",
"description": "Streaming analytics",
"download_url": "https://storage.googleapis.com/***-static/***.csv?GoogleAccessId=888211540537-r3m40kms2upicdr07e5rl2q67feg9loh%40developer.gserviceaccount.com&Expires=4070908800&Signature=WvuuKdddCFKjSNpst5n8yKFNR5qtC1m1o1mQZFWLHmKomJtc7npa6PbwfRoTj9FhIIqbta98VPOYKMGW89XaqXtITh15V%2Bf9opAD3BnuLjTzWC6X24RC5kMCZATXpp9DWi1Our061%2FdKlpUozi1ir7b8AwBWWf%2Bs8u5J6VoelvtEyiZIO4l%2FQdeJ26GqDLRgWElEMAlBE3TJo7m3UuE8gOQPsYBCwBSfLI1bTIytNOHZMUlWuVtMQxEHzUOujAp%2Fgqn1Q8TGGzy5GoeEmzw%2FD80xs%2BALjhT%2BxdiN9riG6%2BEcObrhPoudxl32jUhVH0EmGJwjgiJFQpz%2FLfKr86LrCQ%3D%3D",
"error": "Cannot read property 'email' of undefined",
"completed_at": "2023-01-19T22:13:39.219Z"
}
But I'm only getting the first two key-value pairs using a Python script of the same API call:
response from Python
csv key: 63c9c0927885bf003ecd3a1b
api url: https://api.eventive.org/temporary_exports/63c9c0927885bf003ecd3a1b
<Response [200]>
response:[{'id': '63c9c0927885bf003ecd3a1b', 'description': 'Streaming analytics'}]
Process finished with exit code 0
My code for the Python script is:
import requests
import json
url_for_key = 'https://api.***.org/reports/streams?event_bucket=63279b48d8f8f1009209694f&start=1674111600000&end=1674198000000&tz=America%2FDenver'
api_key = '*************************'
header = {'content-type': 'application/json'}
r1 = requests.get(url=url_for_key, auth=(api_key, ''))
csv_obj = [r1.json()]
csv_key = csv_obj[0]['temporary_export']
#print(csv_obj)
print(f'csv key: {csv_key}')
url_for_link = 'https://api.***.org/temporary_exports/{}'.format(csv_key)
print(f'api url: {url_for_link}')
r2 = requests.get(url=url_for_link, headers=header, auth=(api_key, ''))
print(r2)
print(f'response:{[r2.json()]}')
csv_key is the same as id. Could anyone help me understand what's going on?
Many thanks,

How to get value from JSON format

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"])

How do I allow for passage of function parameters into a cURL request using requests in Python

I'm trying to convert bitcoin RPC calls into functions to use in python, some of the RPC API calls have parameters such as the block height for the command getblockhash.
I have a function that works and returns the genesis block by passing [0] in the params keyword:
def getblockhash():
headers = {
'content-type': 'text/plain;',
}
data = '{"jsonrpc": "1.0", "id":"curltest", "method": "getblockhash", "params": [0]}'
response = requests.post('http://127.0.0.1:8332/', headers=headers, data=data,
auth=(USERNAME, PASSWORD))
response = response.json()
return response
I get this response:
{'result': '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', 'error': None, 'id': 'curltest'}
I want to be able to pass a variable into this spot instead of hardcoding it such as:
def getblockhash(height):
headers = {
'content-type': 'text/plain;',
}
data = {"jsonrpc": "1.0", "id":"curltest", "method": "getblockhash", "params": [height]}
data = str(data)
response = requests.post('http://127.0.0.1:8332/', headers=headers, data=data,
auth=(USERNAME, PASSWORD))
response = response.json()
return response
I get this result:
"{'result': None, 'error': {'code': -32700, 'message': 'Parse error'},
'id': None}"
I've tried testing various things and found that the error shows up when adding
data = str(data)
So how can I pass a function parameter into this without getting the parsing error?
You are directly posting the string representation of a dictionary to the server. However, the string representation of a dictionary is not valid JSON. Example:
>>> example = {"hello": "world"}
>>> str(example)
"{'hello': 'world'}"
Note that the key and value in the string representation are encapsulated by single quotes. However, JSON requires strings to be encapsulated by double quotes.
Possible solutions are: use the json kwarg instead of data to let requests convert the dictionary to valid JSON, manually convert the dictionary to JSON data using the json module, or (as jordanm suggests in their comment) use a JSON-RPC module.

Unable to use json.loads() due to 'expected string or buffer'

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']

Retrieve the access token from POST request and use in GET request

I am using the requests library to make a POST request in order to obtain an access token. My request works properly, but, I'm not sure how to extract it and then use it in a GET request.
url = 'https://login.insideview.com/Auth/login/v1/token'
payload = {'clientId' : '****', 'clientSecret' : '****','grantType':'cred'}
headers = { 'Accept' : 'application/json'}
r = requests.post(url, headers=headers, params=payload)
solution:
data = json.loads(r.text)
data['accessTokenDetails']['accessToken']
Returns:
{"accessTokenDetails":{"accessToken":"the_access_token","tokenType":"bearer","expirationTime":"Fri, Mar 25, 2016 09:59:53 PM GMT","userInfo":{"userId":null,"firstName":null,"lastName":null,"userName":null,"companyName":null,"accountId":null,"role":null}}}
If it returns a dict, why not just access its contents as usual?
token = r['accessTokenDetails']['accessToken']
#michael-queue the response from the request to a JSON endpoint is a JSON encoded string. To load it into a dictionary and access inner properties it's needed to json.loads(json_string) into Python. For the opposite operation, to dump a dictionary into a JSON string is json.dumps(dictionary) instead.

Categories

Resources