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)
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?
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/
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...
I am very new to Python. I run into this problem and hope you can help. Let me explain what I try to do and let me know if I am confusing you.
I have this Python script and it works fine with creating an event.
# Set the request parameters
url = 'https://outlook.office365.com/api/v1.0/me/events?$Select=Start,End'
user = 'user1#domain.com'
pwd = getpass.getpass('Please enter your AD password: ')
# Create JSON payload
data = {
"Subject": "Testing Outlock Event",
"Body": {
"ContentType": "HTML",
"Content": "Test Content"
},
"Start": "2016-05-23T15:00:00.000Z",
"End": "2016-05-23T16:00:00.000Z",
"Attendees": [
{
"EmailAddress": {
"Address": "user1#domain.com",
"Name": "User1"
},
"Type": "Required" },
{
"EmailAddress": {
"Address": "user2#domain.com",
"Name": "User2"
},
"Type": "Optional" }
]
}
json_payload = json.dumps(data)
# Build the HTTP request
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_payload)
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')
request.get_method = lambda: 'POST'
# Perform the request
result = opener.open(request)
Since other posts suggest to set properties for Json separately (here) for the attachment, so I include the data_attachment code below in addition to the request (see "data_attachment" and "json_payloadAttachment"). However, I am not sure how to add that in the request and make one POST.
# Set the request parameters
url = 'https://outlook.office365.com/api/v1.0/me/events?$Select=Start,End'
user = 'user1#domain.com'
pwd = getpass.getpass('Please enter your AD password: ')
# Create JSON payload
data = {
"Subject": "Testing Outlock Event",
"Body": {
"ContentType": "HTML",
"Content": "Test Content"
},
"Start": "2016-05-23T15:00:00.000Z",
"End": "2016-05-23T16:00:00.000Z",
"Attendees": [
{
"EmailAddress": {
"Address": "user1#domain.com",
"Name": "User1"
},
"Type": "Required" },
{
"EmailAddress": {
"Address": "user2#domain.com",
"Name": "User2"
},
"Type": "Optional" }
]
}
data_attachment = {
"#odata.type": "#Microsoft.OutlookServices.FileAttachment",
"Name": "test123.txt",
"ContentBytes": "VGVzdDEyMw=="
}
json_payload = json.dumps(data)
json_payloadAttachment = json.dumps(data_attachment)
# Build the HTTP request
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_payload) # NOT Sure where to put the attachment payload here
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')
request.get_method = lambda: 'POST'
# Perform the request
result = opener.open(request)
Please help. Thanks in advance.
It appears that you need to merge the data; for example you can add another key to your data dictionary called Attachments which contains an array of dictionaries and merge them that way; then serialize your data to JSON.
You don't need json_payloadAttachment.
...
data["Attachments"] = [data_attachment]
json_payload = json.dumps(data)
You're also missing the HasAttachments key according to the link you posted.
data["HasAttachments"] = True