My program is given a JSON class and I need to access certain items within it.
I don't exactly understand what type of data structure it is, which may be part of my problem.
I've tried json.dumps() and json.load(), both of which return errors. I've even tried ._dict_.
I've received below error:
"the JSON object must be str, bytes or bytearray, not 'LambdaContext'," "'LambdaContext' object has no attribute '_dict_'," and "Object of type 'LambdaContext' is not JSON serializable." I don't know what else to do with this JSON data.
I need to access the "apiAccessToken."
The JSON data:
{
"context": {
"System": {
"apiAccessToken": "AxThk...",
"apiEndpoint": "https://api.amazonalexa.com",
"device": {
"deviceId": "string-identifying-the-device",
"supportedInterfaces": {}
},
"application": {
"applicationId": "string"
},
"user": {}
}
}
}
My Code:
def postalCodeRetriever(intent, session, context):
deviceId = session['user']['userId']
jsoninfo = json.dumps(context)
json_dict = json.loads(jsoninfo)
print(str(json_dict))
TOKEN = context["System"]
print(TOKEN)
URL = "https://api.amazonalexa.com/v1/devices/" + deviceId + "/settings/address/countryAndPostalCode"
HEADER = {'Accept': 'application/json', 'Authorization': 'Bearer ' + TOKEN}
response = urllib2.urlopen(URL, headers=HEADER)
data = json.load(response)
postalCode = data['postalCode']
return build_response({}, build_speechlet_response(
"hello", postalCode, None, True))
Below code should do it:
import json
data = json.dumps({
"context": {
"System": {
"apiAccessToken": "AxThk...",
"apiEndpoint": "https://api.amazonalexa.com",
"device": {
"deviceId": "string-identifying-the-device",
"supportedInterfaces": {}
},
"application": {
"applicationId": "string"
},
"user": {}
}
}
})
data_dict = json.loads(data)
print(data_dict['context']['System']['apiAccessToken'])
Output:
AxThk...
Related
I am a very beginner and struggling with a POST Request.
I would like to have a conditional variable in payload which skips project services if they are not active in the project. To have a list of active services I called GET Projects and exported the list of projects to csv where projects names are rows and services are columns. Whenever service is active it has value 1 in its column. Is it possible to tailor services to payload if value in the csv is !=0?
start = "https://developer.api.autodesk.com/bim360/admin/v1/projects/"
end = "/users"
for i in range (len(projects_df)):
payload = json.dumps({
"email": "dummy#lalaland.com",
"companyId": "0000",
"roleIds": [
"0000"
],
"services": [
{
"serviceName": "documentManagement",
"access": "administrator"
},
{
"serviceName": "projectAdministration",
"access": "administrator"
},
{
"serviceName": "projectManagement",
"access": "administrator"
},
{
"serviceName": "costManagement",
"access": "administrator"
},
{
"serviceName": "fieldManagement",
"access": "administrator"
},
{
"serviceName": "modelCoordination",
"access": "administrator"
},
{
"serviceName": "insight",
"access": "administrator"
}
]
})
headers = {
'Authorization': 'Bearer ' + access_token_beta,
'Content-Type': 'application/json',
'User-Id': 'XXXXX'
}
project_id = projects_df.iloc[i,0]
url = start+project_id+end
response = requests.request("POST", url, headers=headers, data=payload)
jsonAsPythonValue = json.loads(response.text)
if (i == 0):
post_user = pd.DataFrame.from_dict(pd.json_normalize(jsonAsPythonValue))
else:
post_user = post_user.append(pd.DataFrame.from_dict(pd.json_normalize(jsonAsPythonValue)),ignore_index=True)
i=i+1
Thank you in advance!
What I usually do is create payload with a minimal set of data, and then have a series of if conditions that add to it as necessary.
payload = {
'key1': 'value1',
'key2': 'value2'
}
if condition1:
payload['key3'] = 'value3'
if condition2:
payload['key4'] = 'value4'
I'm trying to validade an address in FedEX API using Python 3.8 and it returns an error of invalid field value
First I connect to the Auth API
payload={"grant_type": "client_credentials",'client_id':Client_id,'client_secret':Client_secret}
url = "https://apis-sandbox.fedex.com/oauth/token"
headers = {'Content-Type': "application/x-www-form-urlencoded"}
response=requests.post(url, data=(payload), headers=headers)
And it returns a message with the Auth token correctly
{"access_token":"eyJhbGciOiJSUzI1NiIsInRM5U0F2eUs1ZVFBVTFzS5k","token_type":"bearer","expires_in":3599,"scope":"CXS SECURE"}
Then I just get the token to use it in next transactions
token = json.loads(response.text)['access_token']
Then I prepare the next payload for address validation API
payload_valid_address = {
"addressesToValidate": [
{
"address":
{
"streetLines": ["7372 PARKRIDGE BLVD"],
"city": "Irving",
"stateOrProvinceCode": "TX",
"postalCode": "75063-8659",
"countryCode": "US"
}
}
]
}
And send the request to the new endpoint with the given token
url = "https://apis-sandbox.fedex.com/address/v1/addresses/resolve"
headers = {
'Content-Type': "application/json",
'X-locale': "en_US",
'Authorization': 'Bearer '+ token
}
response = requests.post(url, data=payload_valid_address, headers=headers)
print(response.text)
and get the error
<Response [422]>
{"transactionId":"50eae03e-0fec-4ec7-b068-d5c456b64fe5","errors":[{"code":"INVALID.INPUT.EXCEPTION","message":"Invalid field value in the input"}]}
I have made inumerous tests and I don't get the invalid field.
Anyone know what is happening and can help?
payload = json.dumps({input payload}) this works to prevent the response error 422
<Response [422]>
I have fixed it
For any reason, convert the string payload_valid_address to Json in 2 steps doesn't work
payload_valid_address = {....}
payload = json.dumps(payload_valid_address)
But if made in just one step it pass the API request
payload_valid_address = json.dumps({....})
I also had this error and additionally had to use json.loads(json_string) when the json data contained key words like false, true or null.
import json
json_string = r'''{
"accountNumber": {
"value": "802255209"
},
"requestedShipment": {
"shipper": {
"address": {
"postalCode": 75063,
"countryCode": "US"
}
},
"recipient": {
"address": {
"postalCode": "m1m1m1",
"countryCode": "CA"
}
},
"shipDateStamp": "2020-07-03",
"pickupType": "DROPOFF_AT_FEDEX_LOCATION",
"serviceType": "INTERNATIONAL_PRIORITY",
"rateRequestType": [
"LIST",
"ACCOUNT"
],
"customsClearanceDetail": {
"dutiesPayment": {
"paymentType": "SENDER",
"payor": {
"responsibleParty": null
}
},
"commodities": [
{
"description": "Camera",
"quantity": 1,
"quantityUnits": "PCS",
"weight": {
"units": "KG",
"value": 20
},
"customsValue": {
"amount": 100,
"currency": "USD"
}
}
]
},
"requestedPackageLineItems": [
{
"weight": {
"units": "KG",
"value": 20
}
}
]
}
}'''
data = json.loads(json_string)
data
response = requests.request("POST", url, data=json.dumps(data), headers=headers)
I have managed to get Fedex to accept my ayload, however i get this message:
"code":"INVALID.INPUT.EXCEPTION","message":"Validation failed for object='shipShipmentInputVO'. Error count: 1","parameterList":[{"key":"NotNull.shipShipmentInputVO.labelResponseOptions","value":"labelResponseOptions cannot be null"
and when I add the required parameter
'labelResponseOptions': "URL_ONLY"
I get this:
"code":"SYSTEM.UNEXPECTED.ERROR","message":"The system has experienced an unexpected problem and is unable to complete your request. Please try again later. We regret any inconvenience."
Is this really some Fedex internal error?
Already looked at here, here and here but still having issues.
I have a POST data that looks like this:
{
"config":{
"param1": "param1 value",
"param2": "param2 value",
"param3": "param3 value"
},
"name": "Testing API",
"url": "https://testingapi.my.own.com",
"enabled": true
}
I have the following headers:
{
"Content-Type": "application/json",
"referer": "https://testingapi.my.own.com",
"X-CSRFToken": "my token value here"
}
How do format this for the session.post?
I am keep getting the response code of 400 and logs are stating that I am not sending the required params in the post request.
Here is the code:
headers = {"Content-Type": "application/json",
"referer": "https://testingapi.my.own.com",
"X-CSRFToken": "my token"
}
request_data = {
"config":{
"param1": "param1 value",
"param2": "param2 value",
"param3": "param3 value"
},
"name": "Testing API",
"url": "https://testingapi.my.own.com",
"enabled": "true"
}
#tried the following:
r = session.post(url, data = request_data, headers=headers)
r = session.post(url, json = json.dumps(request_data), headers=headers)
When you do data = request_data your nested dictionary is not packaged into the request body as you expect. Try inspecting the body attribute of the request object:
import requests
s = requests.Session()
request_data = {
"config":{
"param1": "param1 value",
"param2": "param2 value",
"param3": "param3 value"
},
"name": "Testing API",
"url": "https://testingapi.my.own.com",
"enabled": True
}
r = s.post('https://httpbin.org/post/404', data=request_data )
r.request.body
returns
'url=https%3A%2F%2Ftestingapi.my.own.com&enabled=True&config=param3&config=param2&config=param1&name=Testing+API'
And when you json = json.dumps(request_data) you json-dump your data twice, so so the server (after unserializing the data one time) only sees a json string rather than an unserialized dict (see requests docs).
So you need to either serialize your data before passing it to data
r = s.post('https://httpbin.org/post/404', data=json.dumps(request_data), )
or as Paul has suggested, use the json parameter and pass your data dict to it:
r = s.post('https://httpbin.org/post/404', json=request_data)
after making post call of API I want to extract specific key/value and than save it onto a text file.
What have been done so far:-
(1)Rest api call and return list
import requests
import json
#API details
url = "http://192.168.1.100:9792/api/scan"
body = json.dumps({"service":"scan", "user_id":"1", "action":"read_all", "code":"0"})
headers = {'Content-Type': 'application/json'}
#Making http post request
response = requests.post(url, headers=headers, data=body, verify=False)
#Decode response.json() method to a python dictionary for data process utilization
dictData = response.json()
#Json string
json_str = json.dumps(dictData)
print(json_str)
print(json_str) output as below
{
"node": [
{
"id": "123",
"ip": "10.101.10.1",
"model": "md1",
"type": "basic",
"name": "aaa"
},
{
"id": "456",
"ip": "10.101.10.2",
"model": "sp3",
"type": "extra",
"name": "bbb"
},
{
"id": "789",
"ip": "1.1.1.1",
"model": "md1",
"type": "basic",
"name": "ccc"
},
{
"id": "101",
"ip": "2.2.2.2",
"model": "advance",
"type": "sw1",
"name": "ddd"
}
],
"status": "success"
}
(2)Extract specific key/value, This is where I'm getting error to get the key/value from the list
for i in json_str["node"]:
if i["type"]=="basic" or i["type"]=="sw1" :
print(i["name"],i["ip"], i["type"])
I'm getting error
for i in json_str["node"]:
TypeError: string indices must be integers, not str
I tried change to json_str[0] but it still doesn't return the key/value that i want.
Please assist further. thanks
Just use back dictData as it already in dictionary
for i in dictData["node"]
You dumped the json into str
Again to work with dict first load the json and then try
json_str = json.dumps(dictData)
json_dict = json.loads(json_str)
print(json_dict)
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "random_uuid",
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
}
}'''
headers = {
'content-type': "application/x-www-form-urlencoded",
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
In the above script, I created a UUID and assigned it to the variable random_uuid. I want the UUID that was created to be substituted inside json for the value random_uuid for the key id. But, the above script is not substituting the value of random_uuid and just using the variable random_uuid itself.
Can anyone please tell me what I'm doing wrong here?
Thanks in advance.
You'll can use string formatting for that.
In your JSON string, replace random_uuid with %s, than do:
payload = payload % random_uuid
Another option is to use json.dumps to create the json:
payload_dict = {
'id': random_uuid,
...
}
payload = json.dumps(payload_dict)
Use str.format instead:
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "{0}",
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
}
}'''.format(random_uuid)
You could use direct JSON entry into a dict:
payload = {
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": random_uuid,
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
}
}
This code may help.
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "%s",
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
}
}''' % random_uuid
headers = {
'content-type': "application/x-www-form-urlencoded",
}
print payload
print(response.text)