How to request GET method in specific url using Postman? - python

I want to get some results using Postman.
expected result :
{
"status": "200",
"message": "success",
"results": {
"count": "6816",
"data": [
{
"timestamp": "2022-07-17T10:47:03Z",
"sender": "0x2F664960a7FBdaDA8e133DbAF1Bfc27DCCBADBfb",
"receiver": "0xA68A135Ccd37E720000fC30CFcc453b15F8040df",
"value": "0",
"status": "1",
"message": "",
"transaction_hash": "0x1a03528eecf165678d7fbcb9ceeee45a98b02f10a5ce30236ef29ee5b3747c84",
"block_number": "2472",
"contract_address": null,
"trace_address": [
"0",
"1",
"1"
],
"trace_type": "staticcall",
"sub_traces": null,
"transaction_index": "0",
"gas_used": "2715",
"gas_limit": "29039032",
"external_receiver": "0",
"input": "0x0d2020dd476f7665726e616e6365436f6e74726163740000000000000000000000000000"
},
...
]
}
}
When I request GET Method for example,
API Docs : https://docs.wemix.com/v/en/dapp-developer/api-reference/account-apis#get-internal-transactions-by-address-and-get-internal-transactions-by-transaction-hash
GET https://explorerapi.test.wemix.com/v1/accounts/0xA68A135Ccd37E720000fC30CFcc453b15F8040df/internal-transactions
api-key: 1ba5e446edf1997f67b51bf9e60b3fbba6fa1bf84301115292805d7e24f43539RESPONSE DATA
I requests GET method using 'api-key' using Postman
but, my response is,
{
"status": "401",
"message": "Unauthorized"
}
How to fix it to get proper response?
Or, is there a good way to call API with Python?

In addition to Khalil's answer - to do the same in python you could do the following:
import requests
headers = {'api-key': '1ba5e446edf1997f67b51bf9e60b3fbba6fa1bf84301115292805d7e24f43539'}
response = requests.get('https://explorerapi.test.wemix.com/v1/accounts/0xA68A135Ccd37E720000fC30CFcc453b15F8040df/internal-transactions', headers=headers)
print(response)
<Response [200]> which will get you the data that you desire.
The API Key that was provided had RESPONSE DATA at the end which was invalid as the API key.

On the Headers tab, you need to add a key api-key with the api key 1ba5e446edf1997f67b51bf9e60b3fbba6fa1bf84301115292805d7e24f43539 in the value.

Related

API FedEX "INVALID.INPUT.EXCEPTION","message":"Invalid field value in the input"

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?

Extract data from API call and save file

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)

Python: Parse json data from a list with the same name

So I have the next json and I want to get just the github link and the twitter one without taking the foursquare and gravatar one.
Also this in not all, sometimes the json data can change and if doesn't find a foursquare url, github will become first and twitter the second one. With the other ones (github or twitter) will be the same.
How can I get the github and twitter url if they are not in the same position as in this json?
{ "socialProfiles": [
{
"type": "foursquare",
"typeId": "foursquare",
"typeName": "Foursquare",
"url": "https://foursquare.com/user/somerandomuser",
"id": "554225246246"
},
{
"type": "github",
"typeId": "github",
"typeName": "Github",
"url": "https://github.com/somerandomuser",
"username": "somerandomuser"
},
{
"type": "gravatar",
"typeId": "gravatar",
"typeName": "Gravatar",
"url": "https://gravatar.com/somerandomuser",
"username": "somerandomuser",
"id": "132341667"
},
{
"bio": " This is a bio of a random user",
"followers": 543,
"following": 222,
"type": "twitter",
"typeId": "twitter",
"typeName": "Twitter",
"url": "https://twitter.com/somerandomuser",
"username": "somerandomuser",
"id": "41414515335"
}
]
}
you can use dict comprehension to create another dict only with the urls that you need, in this case twitter and github
search = ['github', 'twitter']
urls = {dct['type']: dct['url'] for dct in data.get('socialProfiles', []) if dct['type'] in search}
print(urls)
Output
{
'github': 'https://github.com/somerandomuser',
'twitter': 'https://twitter.com/somerandomuser'
}
And after that you can get the url that you need.
print(urls['github'])
# Output
# https://github.com/somerandomuser
Using a simple iteration.
Ex:
checkList = ["twitter", "github"]
for i in data["socialProfiles"]:
if i["typeId"] in checkList: #Check if typeid is in your check-list
print(i["url"])
Output:
https://github.com/somerandomuser
https://twitter.com/somerandomuser
data is your dictionary.
for social_profile in data["socialProfiles"]:
for link in social_profile:
if link['typeId'] == "twitter" or link['typeId'] == "github":
print (link["url"])

How can I format this JSON String into a JSON object?

I have the following JSON document being sent from an SNS HTTPs subscription to an API Gateway endpoint (backed by a Python2.7 Lambda function). In this case, I have a Cloudwatch Alarm that's configured to send to SNS, which then sends to this Gateway endpoint. SNS packages that alarm (which is JSON) into the "body" field of the message it sends to Gateway.
I need to extract the JSON document out of the "body" field, but by this point it's been properly mangled with escape characters and new lines and json.loads() is not liking it at all.
How can I read the value of "body" back into a JSON document using Python2.7 within a Lambda function? I've tried cleaning it by removing '\n' and '\', but I'm just striking out!
Here is the JSON as received by Lambda:
{
"body": "{\n \"Type\" : \"Notification\",\n \"MessageId\" : \"944c9xxx3-c98d636ff2c7\",\n \"TopicArn\" : \"arn:aws:sns:us-west-2:xxx6xx:sxxxr-sns-topic\",\n \"Subject\" : \"ALARM: \\\"hhh\\\" in US West (Oregon)\",\n \"Message\" : \"{\\\"AlarmName\\\":\\\"hhh\\\",\\\"AlarmDescription\\\":null,\\\"AWSAccountId\\\":\\\"8xxx\\\",\\\"NewStateValue\\\":\\\"ALARM\\\",\\\"NewStateReason\\\":\\\"Threshold Crossed: 1 out of the last 1 datapoints [0.333370380661336 (13/06/18 18:06:00)] was greater than or equal to the threshold (0.1) (minimum 1 datapoint for OK -> ALARM transition).\\\",\\\"StateChangeTime\\\":\\\"2018-06-13T18:16:56.457+0000\\\",\\\"Region\\\":\\\"US West (Oregon)\\\",\\\"OldStateValue\\\":\\\"INSUFFICIENT_DATA\\\",\\\"Trigger\\\":{\\\"MetricName\\\":\\\"CPUUtilization\\\",\\\"Namespace\\\":\\\"AWS/EC2\\\",\\\"StatisticType\\\":\\\"Statistic\\\",\\\"Statistic\\\":\\\"AVERAGE\\\",\\\"Unit\\\":null,\\\"Dimensions\\\":[{\\\"name\\\":\\\"InstanceId\\\",\\\"value\\\":\\\"i-07bxxx26\\\"}],\\\"Period\\\":300,\\\"EvaluationPeriods\\\":1,\\\"ComparisonOperator\\\":\\\"GreaterThanOrEqualToThreshold\\\",\\\"Threshold\\\":0.1,\\\"TreatMissingData\\\":\\\"\\\",\\\"EvaluateLowSampleCountPercentile\\\":\\\"\\\"}}\",\n \"Timestamp\" : \"2018-06-13T18:16:56.486Z\",\n \"SignatureVersion\" : \"1\",\n \"Signature\" : \"fFunXkjjxxxvF7Kmxxx\",\n \"SigningCertURL\" : \"https://sns.us-west-2.amazonaws.com/SimpleNotificationService-xxx.pem\",\n \"UnsubscribeURL\" : \"https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=axxxd\"\n}",
"resource": "/message",
"requestContext": {
"requestTime": "13/Jun/2018:18:16:56 +0000",
"protocol": "HTTP/1.1",
"resourceId": "m4sxxxq",
"apiId": "2v2cthhh",
"resourcePath": "/message",
"httpMethod": "POST",
"requestId": "f41e8-8cbd-57ad9e625d12",
"extendedRequestId": "xxx",
"path": "/stage/message",
"stage": "stage",
"requestTimeEpoch": 1528913816627,
"identity": {
"userArn": null,
"cognitoAuthenticationType": null,
"accessKey": null,
"caller": null,
"userAgent": "Amazon Simple Notification Service Agent",
"user": null,
"cognitoIdentityPoolId": null,
"cognitoIdentityId": null,
"cognitoAuthenticationProvider": null,
"sourceIp": "xxx",
"accountId": null
},
"accountId": "xxx"
},
"queryStringParameters": {
"id": "CBxxx69"
},
"httpMethod": "POST",
"pathParameters": null,
"headers": {
"Content-Type": "text/plain; charset=UTF-8",
"Via": "1.1 xxx.cloudfront.net (CloudFront)",
"Accept-Encoding": "gzip,deflate",
"CloudFront-Is-SmartTV-Viewer": "false",
"x-amz-sns-subscription-arn": "arn:aws:sns:us-west-2:xxx:sxxx-nxxx-sns-topic:xxx",
"CloudFront-Forwarded-Proto": "https",
"X-Forwarded-For": "54.240.xxx, 54.182.xxx",
"CloudFront-Viewer-Country": "US",
"User-Agent": "Amazon Simple Notification Service Agent",
"X-Amzn-Trace-Id": "Root=1-5b21xxx53acea6642317ed4",
"x-amz-sns-topic-arn": "arn:aws:sns:us-west-2:xxxx:sxxxier-sns-topic",
"Host": "2vxxx.execute-api.us-west-2.amazonaws.com",
"X-Forwarded-Proto": "https",
"X-Amz-Cf-Id": "xxx",
"CloudFront-Is-Tablet-Viewer": "false",
"X-Forwarded-Port": "443",
"x-amz-sns-message-type": "Notification",
"CloudFront-Is-Mobile-Viewer": "false",
"x-amz-sns-message-id": "xxx",
"CloudFront-Is-Desktop-Viewer": "true"
},
"stageVariables": null,
"path": "/message",
"isBase64Encoded": false
}
if i use your pasted sample as a raw string, it works well:
>>> j = r'''...your sample pasted here...'''
>>> data = json.loads(j)
>>> bodydata = json.loads(data['body'])
>>> bodydata['Type']
u'Notification'
seems, that what you pasted above is the repr form, printed out with Python

Paypal Rest API keeps returning malformed json error

I am trying to create payment using paypal Rest API, but I keep getting this error response:
{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"262cbdc417df7"}
here with my code:
payment_url = 'https://api.sandbox.paypal.com/v1/payments/payment'
headers = {"Content-Type": "application/json", "Authorization": "Bearer %s" % access_token}
data = {
"intent": "sale",
"redirect_urls": {
"return_url": "http://localhost:8080/index.html",
"cancel_url": "http://localhost:8080/index.html"
},
"payer": {
"payment_method": "paypal"
},
"transactions": [
{
"amount": {
"total": "7.47",
"currency": "USD"
},
"details": {
"subtotal": "7.41",
"tax": "0.03",
"shipping": "0.03"
},
"description": "This is the payment transaction description.",
"item_list": {
"items": [
{
"quantity": "1",
"name": "item",
"price": "7.41",
"currency": "USD",
"sku": "item"
}]
}
}
]
}
print headers
print data
r = requests.post(payment_url, headers=headers, data=data)
print 'payment res', r.text
And I only get the response like this:
{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"262cbdc417df7"}
I have seen quite a few questions regarding this kind of error, but none of them have solution yet. :(
The json formated post data is obviously valid. Otherwise, requests post method would raise exceptions. And the response is returned from paypal server, but I can't find any information from the link it gave. I have checked Rest API documentation, and I think I made the request exactly as the samples. What did I miss?
Any kind advice or solution would be appreciated.
Your return_url and cancel_url values need to have quotes around them. As the message says, your JSON is malformed.
Try this - http://jsonlint.com/ to see your errors.

Categories