Extracting data from http response in python - json

I am trying to extract the expiry date returned in the body of my http post response body. the r.json() returned is type 'dict' but when i use the get() function there is no recognised 'key'.
I would like to extract the date from the response and compare it with the current datetime to see if the date has expired.
#Extract date string from http response
print("status: ", r.status_code)
Expiry_Data = r.json()
print(type(Expiry_Data))
print(Expiry_Data)
print(Expiry_Data.get('Expiry_Date'))
Output:
status: 200
<class 'dict'>
{'ResultSets': {'Table1': [{'Expiry_Date': '2022-11-12T00:00:00'}]}, 'OutputParameters': {}}
None

Related

Passing an integer field in header for requests library in python

I have to pass an integer field in headers for a request but it is giving me an error:
requests.exceptions.InvalidHeader: Value for header {orgId: 721067787} must be of type str or bytes, not <class 'int'>
This is my code please help, regarding the exception:
authenticationHeaders = {'Authorization':tmpAuthToken,'orgId':organizationId}
response = requests.get("https://desk.zoho.com/api/v1/tickets",headers = authenticationHeaders)
return response.json()
You have to send a string value inside the dictionary.
This would work:
authenticationHeaders = {'Authorization':str(tmpAuthToken),'orgId':str(organizationId)}
response = requests.get("https://desk.zoho.com/api/v1/tickets",headers = authenticationHeaders)
return response.json()

How to fix 'AttributeError: 'dict' object has no attribute ... ' error in python assert

I'm setting up a request assertion with request module and python assert keyword but getting
AttributeError: 'dict' object has no attribute 'documentation_url'
when I try to assert a string in json response. How do I assert something within the json response and when the condition is true, it should print out something?
import requests
import pprint
URL = 'https://github.com/timeline.json'
def get_github_json(URL):
response = requests.get(URL).json()
return response
assert get_github_json(URL).documentation_url == 'https://developer.github.com/v3/activity/events/#list-public-events'
The json response looks like this:
{'documentation_url': 'https://developer.github.com/v3/activity/events/#list-public-events',
'message': 'Hello there, wayfaring stranger. If you’re reading this then you '
'probably didn’t see our blog post a couple of years back '
'announcing that this API would go away: http://git.io/17AROg Fear '
'not, you should be able to get what you need from the shiny new '
'Events API instead.'
}
Hi because it's a dictionary then you would have to get the value with a key.
We know response is a dictionary, so in this case when you want the value from the documentation_url, we would need to do it like this:
def get_github_json(url):
response = requests.get(url).json()
return response
assert get_github_json(url)['documentation_url'] # <---- your are getting the value by giving the key
If you try and print out response['documentation_url'] then you would get this result:
https://developer.github.com/v3/activity/events/#list-public-events

groovy script SOAP UI json response parse

How to parse json response using groovy script.
I am using SOAP UI and have json response as below-
{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}
Can anyone please share sample code to parse json object and post that some basic assertions check.
Thanks
Add a Script Assertion for the rest request test step with below script.
Define your expected data as shown in the snippet below as needed
It compares each key value with expected data.
JsonSlurper can be used to parse the response.
//Check if the response is not empty
assert context.response, 'Response is empty or null'
//Define expected data
def expectedData = [name: 'aaaaaaaaaaa', emailid: 'bbbbbbbbb']
def json = new groovy.json.JsonSlurper().parseText(context.response)
//Checks all elements of resource one by one and compare with expectedData
json.resource.each {k, v -> assert v == expectedData."$k" }

How to post values from RestAssured to JSon and get a value from it?

{"service_request": {"service_type":"Registration","partner":"1010101","validity":1,"validity_unit":"Year","quantity":1,"center":"1020301","template":"2020301"}}
I have JSON values as above obtained from Request Payload, when I post data from the web page. I want to post this data from RESTAssured in java and want to get the returned value? How can I do that?
I would recommend to check https://github.com/jayway/rest-assured/wiki/Usage#specifying-request-data
I imagine you are trying to do a POST using Rest-Assured.For that simplest and easy way is.. Save your payload as String. If you have payload as JSONObject, use toJSONString() to convert it to String
String payload = "yourpayload";
String responseBody = given().contentType(ContentType.JSON).body(payload).
when().post(url).then().assertThat().statusCode(200).and()
extract().response().asString();
Above code, post your payload to given Url, verify response code and convert response body to a String. You can do assertion without converting to String as well like
given().contentType(ContentType.JSON).body(payload).
when().post(url).then().assertThat().statusCode(200).
and().assertThat().body("service_request.partner", equalTo("1010101"));

HTTPResponse object -- JSON object must be str, not 'bytes'

I've been trying to update a small Python library called libpynexmo to work with Python 3.
I've been stuck on this function:
def send_request_json(self, request):
url = request
req = urllib.request.Request(url=url)
req.add_header('Accept', 'application/json')
try:
return json.load(urllib.request.urlopen(req))
except ValueError:
return False
When it gets to this, json responds with:
TypeError: the JSON object must be str, not 'bytes'
I read in a few places that for json.load you should pass objects (In this case an HTTPResponse object) with a .read() attached, but it doesn't work on HTTPResponse objects.
I'm at a loss as to where to go with this next, but being that my entire 1500 line script is freshly converted to Python 3, I don't feel like going back to 2.7.
Facing the same problem I solve it using decode()
...
rawreply = connection.getresponse().read()
reply = json.loads(rawreply.decode())
I recently wrote a small function to send Nexmo messages. Unless you need the full functionality of the libpynexmo code, this should do the job for you. And if you want to continue overhauling libpynexmo, just copy this code. The key is utf8 encoding.
If you want to send any other fields with your message, the full documentation for what you can include with a nexmo outbound message is here
Python 3.4 tested Nexmo outbound (JSON):
def nexmo_sendsms(api_key, api_secret, sender, receiver, body):
"""
Sends a message using Nexmo.
:param api_key: Nexmo provided api key
:param api_secret: Nexmo provided secrety key
:param sender: The number used to send the message
:param receiver: The number the message is addressed to
:param body: The message body
:return: Returns the msgid received back from Nexmo after message has been sent.
"""
msg = {
'api_key': api_key,
'api_secret': api_secret,
'from': sender,
'to': receiver,
'text': body
}
nexmo_url = 'https://rest.nexmo.com/sms/json'
data = urllib.parse.urlencode(msg)
binary_data = data.encode('utf8')
req = urllib.request.Request(nexmo_url, binary_data)
response = urllib.request.urlopen(req)
result = json.loads(response.readall().decode('utf-8'))
return result['messages'][0]['message-id']
I met the problem as well and now it pass
import json
import urllib.request as ur
import urllib.parse as par
html = ur.urlopen(url).read()
print(type(html))
data = json.loads(html.decode('utf-8'))
Since you are getting a HTTPResponse, you can use Tornado.escape and its json_decode() to convert the JSON string into a dictionary:
from tornado import escape
body = escape.json_decode(body)
From the manual:
tornado.escape.json_decode(value)
Returns Python objects for the given JSON string.