Conditional variable in payload - python

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'

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?

Error in SQL syntax after sending post request to web page form in python

I need to post some json data here: https://online.superpoistenie.sk/pzp/kalkulacka/
the webpage will proceed data and show results
Basicly you insert some info and the webpage will generate all possible prices from different brands for your insurance specificly car.
Basicly i want to
post json data to page
get back answer from page in json
best result will be if i will get name of company name of the offer and price
I am only interested in cars.
I tried to do this in node.js with axios didnt got far and i was new to node.js now i am using python and request lib and i am having some nice answer i just cant finish it.
Here is my code:
import requests, json, urllib3, bs4, pprint
url = "https://online.superpoistenie.sk/pzp/kalkulacka/"
json_head = "/predvolba.json"
json_file = "C:/Users/GC/Desktop/web crawler poistovne/Json_Storage"
payload = json_file + json_head
with open(payload, 'r') as f:
data = f.read()
json_data = json.loads(data)
pprint.pprint(json_data)
try:
r = requests.post(url, data=json_data, headers="")
pprint.pprint(r.status_code)
except EnvironmentError as er:
print('Decoding json failed')
print(er)
r = requests.get(url)
print(r) #will output code 200
r = requests.post(url, json_data)
print(r) #will output code 200
print(r.content)
the output is html file with error codes in it meaning i screwed up something in json but i dont know what. i want it to be html code with the redirected page after i send form and i want to filter the html code to parts where the name of company are and prices.
Thanks so much for any answer!
this is the json i am seding to the site
[
{
"comp838":0
},
{
"comp839":null
},
{
"typ_vozidla":"1"
},
{
"len_pzp_check":true
},
{
"comp773":5
},
{
"comp771":1
},
{
"comp770":"motorka"
},
{
"comp769":"do+3%2C5+t"
},
{
"comp143":"BMW"
},
{
"comp144":"rad%2F%F8ada+2+Cabriolet"
},
{
"comp763": "BMW"
},
{
"comp772":"-vyberte-zo-zoznamu-"
},
{
"comp167":"Benz%EDn"
},
{
"comp678":"%28F23%29+%282014-%29+Benz%EDn&prevedenie=2-dv.%2C+4-m.%2C+kabriolet%2C+osob."
},
{
"comp600":"2-dv.%2C+4-m.%2C+kabrilet%2C+osob."
},
{
"comp677":"3.0+%282998+ccm%2C+250+kW%2C+turbo+29"
},
{
"comp147":"250"
},
{
"comp148":"2998"
},
{
"comp149":"2000"
},
{
"comp157":"1"
},
{
"comp779":"Adam"
},
{
"comp780":"Tilingerov"
},
{
"comp781":"Adam"
},
{
"comp782":"Tilingerov"
},
{
"comp158":"1982"
},
{
"comp150":"90028"
},
{
"comp151":"90028--Z%E1lesie%ESC%%EBA"
},
{
"comp212":"0947588699"
},
{
"comp211":"learningpotential2%40gmail.com"
},
{
"comp205":"1"
},
{
"comp286":"1"
},
{
"comp287":"1"
},
{
"comp810":"1"
},
{
"comp288":"0"
},
{
"comp591":"0"
},
{
"comp401":"Nie"
},
{
"comp806": "1"
},
{
"typ_vozidla":1
},
{
"len_pzp_check":true
},
{
"tel_pov":22
},
{
"odoslany_kasko":3
},
{
"scenar":1
},
{
"zmena":false
}
]

skype interview api automatic scheduling not working

I am trying to integrate Skype interview API using python and JWT.
for this 1st I am creating a token using python and jwt, and after that, I am sending API request call to skype interview with generated above token.
the request is processed and I am getting a proper response. the scheduling is set to automatic and date proposing is set to the candidate.
my issue is instead of the candidate to get the date proposing email the interviewer is getting the date selecting email without even proposing the date by the candidate.
You can see/check below my code:
input_data = {
"iemail": "interviewer#email.com",
"iduration": 90,
"cname": "Candidate",
"location": "LOCAL"
"position": "Full Stack Developer",
"cemail": "candidate#email.com",
"iname": "Interviewer"
}
def payloadGenertor(content):
jti = uuid.uuid1()
iss = "ISSUER"
iat = int(datetime.now().timestamp())
sub = hash256(content)
exp = iat + 10
payload = {
"jti": f '{jti}',
"iss": f '{iss}',
"iat": iat,
"sub": f '{sub}',
"exp": exp
}
payloadStr = json.dumps(payload)
return payloadStr
url = "https://interviews.skype.com/api/interviews"
content = {
"position": {
"code": input_data['location'] + " " + str(uuid.uuid1()).split('-')[0],
"title": input_data['position'],
"Description": f "Interviews for {input_data['position']} {input_data['location']}."
},
"participants": [
{
"name": input_data['iname'],
"email": input_data['iemail'],
"role": "interviewer",
"timezone": "Asia/Kolkata"
},
{
"name": input_data['cname'],
"email": input_data['cemail'],
"role": "candidate",
"timezone": "Asia/Kolkata"
}
],
"scheduling": {
"duration": int(input_data['iduration']),
"mode": "automatic",
"dateproposing": "candidate"
}
}
secret = "API_SECRET"
payloadHeader = {
"alg": "HS256",
"typ": "JWT"
}
payload = payloadGenertor(content)
jwt = generate_JWT(payloadHeader, payload, secret)
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + jwt
}
response = requests.post(url, data = content, headers = headers)
print(response.text)

Print status code from the post in a json-rpc call

I have a working script that does the job just fine but I can't seem to figure out how to print the status code after the script runs.
Can someone please review and provide some guidance and help?
import requests
import json
url = 'http://10.3.198.100/ins'
switchuser = 'user'
switchpassword = 'password'
myheaders = {'content-type' : 'application/json-rpc'}
payload = [
{
"jsonrpc": "2.0",
"method": "cli",
"params": {
"cmd": "vrf context management",
"version": 1
},
"id": 1
},
{
"jsonrpc": "2.0",
"method": "cli",
"params": {
"cmd": "ip route 192.168.255.0/24 10.3.198.130",
"version": 1
},
"id": 2
},
{
"jsonrpc": "2.0",
"method": "cli",
"params": {
"cmd": "copy run start",
"version": 1
},
"id": 3
}
]
response = requests.post(url, data = json.dumps(payload), headers = myheaders, auth = (switchuser, switchpassword)).json()
You are immediately calling .json() after your .post() returns. This means that you are throwing away the rest of the info from the response.
Try this instead:
response = requests.post(
url,data=json.dumps(payload),
headers=myheaders,
auth=(switchuser,switchpassword))
json_response = response.json()
print(response.status_code)
Reference: http://docs.python-requests.org/

Accessing Nested JSON data in Python

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...

Categories