problems with requests in python list - python

I am going to post phone in the app but I am getting error again and again. Because the structure of the post looks like that
data = {
'login': 'login',
'password': 'password',
'data': '[{"user_id": "user_id","text": "key"}]'
}
response = requests.post('url', data=data)
the problem with this code is that user_id and key because they are not default values they can be different. if I remove apostrophe from the list. Error occurs Array is not Json. If I put this like that
data = [
{
'login': 'login',
'password': 'password',
'data': {"user_id": user_id, "text": key}
}
]
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
response = requests.post('url', json=data, headers=headers)
It throws another error Login or Password is null. How can I solve this problems any help plz? thank you in advance!

If I understand the question correctly, you want to replace the hard-coded user id and key with values from a pair of variables. This shouldn't require any change in the structure of the payload. Just try
import json
user_id = "..."
key = "..."
request_data = [{"user_id": user_id, "text": key}]
data = {
'login': 'login',
'password': 'password',
'data': json.dump(request_data)
}
response = requests.post('url', data=data)

Related

Use my dataframe in a loop so It can be use in a Json process

I have the next code
payload = json.dumps({
"phones": [
{
"phone": "593 999999999"
},
{
"phone": "593 000000000"
}
]
})
headers = {
'Authorization': 'Bearer ********',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
The responde message I´ts:
`{"summary":{"total":2,"valid":1,"invalid":1},"numbers":[{"valid":true,"error":null,"input":"+593 997178570","phone":"+59399999999","wid":"593997178570#c.us","kind":"mobile","country":"EC","countryPrefix":593,"formats":{"local":"997178570","nationaal":"099 999 9999","international":"+593 99 999 9999"}},{"valid":false,"error":"The phone number is not WhatsApp compatible","input":"+593 000000000","phone":"+593 000000000","wid":null,"kind":"unknown","country":"EC","countryPrefix":593,"formats":{"nationaal":"+593 000000000","international":"+593 000000000"}}]}`
And then I do this.
data = response.json()
aux=pd.DataFrame(data['numbers'])
resultado=aux[['phone','valid']]
So I already know how to put that responde into a dataframe that It´s the purpose of this.
So my question is this, how can I use that process with a dataframe simple as this
Number
593987654321
593987654322
593987654323
593987654324
It´s there a way to put that dataframe into a loop so I can use my Json process.
Or to convert my dataframe into a dictionary?. I have no experience working with Json.
IUUC, you can export Number column to list of dictionaries with .to_dict('records').
payload = {"phones": df[['Number']].rename(columns={'Number':'phone'}).to_dict('records')}
print(payload)
{'phones': [{'phone': 593987654321}, {'phone': 593987654322}, {'phone': 593987654323}, {'phone': 593987654324}]}

Microsoft Graph API send email using Access Token of Enterprise Application

I'm working on python code to send an email from Outlook using Microsoft Graph API. For this, I have created an Enterprise Application in my Azure Active Directory Tenant. I have granted admin consent for the tenant to the application on Mail.Send permission. I'm able to get the access token for Graph API with the help of this application, but I'm not able to send the mail. Can anyone please help me to understand, what is the issue with my code?
Python Code:
from requests import post
CLIENT_SECRET_VALUE = 'CLIENT_SECRET_VALUE'
TENANT_ID = 'TENANT_ID'
CLIENT_ID = 'CLIENT_ID'
LOGIN_URI = f'https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token'
headers = {
'Host': 'login.microsoftonline.com',
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'client_id': CLIENT_ID,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': CLIENT_SECRET_VALUE,
'grant_type': 'client_credentials',
'tenant': TENANT_ID
}
response = post(url=LOGIN_URI, headers=headers, data=body)
response.raise_for_status()
response_body = response.json()
authorization_token = f"{response_body['token_type']} {response_body['access_token']}"
print(authorization_token)
email_header = {
'Authorization': authorization_token,
'Content-Type': 'application/json'
}
message = {
'body': {
'content': 'Outlook Mail Testing Demo',
'contentType': 'Text'
},
'sender': {
'emailAddress': {
'address': 'email.address.of.shared.mailbox#active-directory-tenant.tld',
'name': 'Name of Shared Mailbox'
}
},
'subject': 'Testing email',
'toRecipients': [
{
'emailAddress': {
'address': 'temprorary.email.address#another-domain.tld',
'name': 'Name of person to whom email belongs'
}
}
]
}
email_body = {
'message': message
}
email_send_response = post(url='https://graph.microsoft.com/v1.0/users/me/sendMail', headers=email_header, data=email_body)
email_send_response.raise_for_status()
[N.B.: CLIENT_SECRET_VALUE is getting generated by the enterprise application. TENANT_ID & CLIENT_ID are the tenant and client ids assigned to the application]
On running the code, I'm getting an error:
400 Client Error: Bad Request for url: https://graph.microsoft.com/v1.0/users/me/sendMail
There are two problems in your code. As I specified the first issue in comments that the URL should be as below as you are using client credential flow.
https://graph.microsoft.com/v1.0/users/{userid/UPN}/sendMail
The second problem I have identified after a long research in python is that the body which you are sening with the API call is not in the format of json. So I have used import json and method json.dumps and tested it. Then it worked.
Code:
from requests import post
import json
CLIENT_SECRET_VALUE = 'aX27Q~insds3EvI4z8otRNGHRcCgdjeFOTSpCLPZ'
TENANT_ID = '363147dc-b3be-41a7-af56-f67894ef5a7'
CLIENT_ID = 'e61195e5-7955-4558-9126-37f6cf372d45'
LOGIN_URI = f'https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token'
headers = {
'Host': 'login.microsoftonline.com',
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'client_id': CLIENT_ID,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': CLIENT_SECRET_VALUE,
'grant_type': 'client_credentials',
'tenant': TENANT_ID
}
response = post(url=LOGIN_URI, headers=headers, data=body)
response.raise_for_status()
response_body = response.json()
authorization_token = f"{response_body['token_type']} {response_body['access_token']}"
print(authorization_token)
email_header = {
'Authorization': authorization_token,
'Content-Type': 'application/json'
}
message = {
'body': {
'content': 'Outlook Mail Testing Demo',
'contentType': 'Text'
},
'sender': {
'emailAddress': {
'address': 'email.address.of.shared.mailbox#active-directory-tenant.tld',
'name': 'Name of Shared Mailbox'
}
},
'subject': 'Testing email',
'toRecipients': [
{
'emailAddress': {
'address': 'temprorary.email.address#another-domain.tld',
'name': 'Name of person to whom email belongs'
}
}
]
}
email_body = {
'message': message
}
email_send_response = post(url='https://graph.microsoft.com/v1.0/users/1ab4e76f-5f52-44b8-8a72-7d03c05e6ff4/sendMail', headers=email_header, data=json.dumps(email_body))
print(email_send_response)
OUTPUT:

Unable to verify webhooks from PayPal in Python

I am trying to verify webhooks for subscriptions in paypal using django python. I am receiving the webhooks but when i send them to get verified i get this error: {'name': 'VALIDATION_ERROR', 'message': 'Invalid request - see details', 'debug_id': 'ccc873865982', 'details': [{'field': '/', 'location': 'body', 'issue': 'MALFORMED_REQUEST_JSON'}], 'links': []}. I have checked what the status code is for the response which gives a 400 response. By looking at the API Docs i see that invalid request + 400 response is either a validation error (which is to do with the Json format, so most likely a syntax error) or an authorization error (which says i need to change the scope). I think it is the validation error because the error points to the body.
Here is the relevant code:
header_params = {
"Accept": "application/json",
"Accept-Language": "en_US",
}
param = {
"grant_type": "client_credentials",
}
cid = settings.PAYPAL_CLIENT_ID
secret = settings.PAYPAL_CLIENT_SECRET
token_i = requests.post('https://api-m.sandbox.paypal.com/v1/oauth2/token', auth=(cid, secret), headers=header_params, data=param).json()
token = token_i["access_token"]
bearer_token = "Bearer x".replace('x', token)
headers = {
"Content-Type": "application/json",
"Authorization": bearer_token,
}
print(request.body)
webhook_event = request.body.decode("utf-8")
data = {
"transmission_id": request.headers["PAYPAL-TRANSMISSION-ID"],
"transmission_time": request.headers["PAYPAL-TRANSMISSION-TIME"],
"cert_url": request.headers["PAYPAL-CERT-URL"],
"auth_algo": request.headers["PAYPAL-AUTH-ALGO"],
"transmission_sig": request.headers["PAYPAL-TRANSMISSION-SIG"],
"webhook_id": "3AJ143072C221060T",
"webhook_event": webhook_event,
}
print(json.dumps(data))
response = requests.post('https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature', headers=headers, json=json.dumps(data)).json()
print('worked')
print(response)
if response["verification_status"] == "SUCCESS":
print('success')
Here is the print of the print(json.dumps(data)) (i removed some ids):
{
"transmission_id": "id_is_here",
"transmission_time": "2021-07-04T23:37:29Z",
"cert_url": "https://api.sandbox.paypal.com/v1/notifications/certs/CERT-360caa42-fca2a594-7a8abba8",
"auth_algo": "auth_algo",
"transmission_sig": "EODOx5y8kIDycYiBYcIgByiBzHyEfu1/NS2nsumOIksVuw/2vJwHj2FcuHYxIa4n/s+s25xkeqk0CXPiSuqtNUGv4pvFtpwbCVAOCU+Msn304+wBgyb7G24rwUPwrof/5jHYQxqKKX5RzxTrff4oPnisKBDUUXV4s2+KO3h2RYAhrXtwTSPt7cK5ZbGZ6SmfpYJ8qDnYFh4PIesLeflSPQ4vHQrFbgr3NiW63sZruGFJc0hTWWc8L3BhzDuUfiSrxBJLAtrqReC8R0HSV8D+Ywmdeipep54yZeJZXfbmUUGvSYbmVMsVggyzZnltyl1hP5xUd3iIi2jdNWYpLESZzA==",
"webhook_id": "Webhook_id_is_here",
"webhook_event": "{\"id\":\"id_here\",\"event_version\":\"1.0\",\"create_time\":\"2021-07-04T23:37:26.733Z\",\"resource_type\":\"subscription\",\"resource_version\":\"2.0\",\"event_type\":\"BILLING.SUBSCRIPTION.CREATED\",\"summary\":\"Subscription created\",\"resource\":{\"start_time\":\"2021-07-04T23:37:26Z\",\"quantity\":\"1\",\"create_time\":\"2021-07-04T23:37:26Z\",\"custom_id\":\"custom_id_here\",\"links\":[{\"href\":\"https://www.sandbox.paypal.com/webapps/billing/subscriptions?ba_token=BA-2UF06918UT180770Y\",\"rel\":\"approve\",\"method\":\"GET\"},{\"href\":\"https://api.sandbox.paypal.com/v1/billing/subscriptions/I-4S15814RUE18\",\"rel\":\"edit\",\"method\":\"PATCH\"},{\"href\":\"https://api.sandbox.paypal.com/v1/billing/subscriptions/I-4S15814RUE18\",\"rel\":\"self\",\"method\":\"GET\"}],\"id\":\"sub_id_here_\",\"plan_overridden\":false,\"plan_id\":\"P-0DA33732CG980003EMDQJ6BA\",\"status\":\"APPROVAL_PENDING\"},\"links\":[{\"href\":\"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-91E32247D9338170B-4RF07261WK370823W\",\"rel\":\"self\",\"method\":\"GET\"},{\"href\":\"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/id_here/resend\",\"rel\":\"resend\",\"method\":\"POST\"}]}"
}
Your data for the key webhook_event is double encoded as JSON.
You have to decode it with
webhook_event = json.loads(webhook_event)
or not encode it in the first place.

Extracting splukn data from Python script

I am trying to retrieve the data from splunk through python but i get syntax error where as curl command gives me output
import requests
baseurl = 'https://*****/services/search/jobs/export'
headers = {
"Content-Type": "application/json",
}
data = {
'username': '****',
'password': '*******',
"search": "search index=sso-fed-prod source="/app/pingfederate-9.3.2/pingfederate/log/splunk-audit.log" event=SSO OR AUTHN_ATTEMPT OR OAuth connectionid status=success",
}
r = requests.get(baseurl, data=json.dumps(data), headers=headers)
print(r.json())
output
edwops#ip-10-94-202-253:/app/edwops/scripts/python > python splunk_extract.py
File "splunk_extract.py", line 12
"search": "search index=sso-fed-prod source="/app/pingfederate-9.3.2/pingfederate/log/splunk-audit.log" event=SSO OR AUTHN_ATTEMPT OR OAuth connectionid status=success",
^
SyntaxError: invalid syntax
The problem is in the generation of data dict, try:
data = {
'username': '****',
'password': '*******',
"search": 'search index=sso-fed-prod source="/app/pingfederate-9.3.2/pingfederate/log/splunk-audit.log" event=SSO OR AUTHN_ATTEMPT OR OAuth connectionid status=success',
}
Explanation: when you set up value for search key, you close quotation marks " here:
search index=sso-fed-prod source="
so all what goes after is assumed to be a variable by an interpreatator and not the string as intended. So you just need to use single quotation marks ' for the whole search value.

Apple Sign In Python

I want to make an apple sign in with social auth python. Now I have a piece of code below. When I do a request, I get an invalid grant error. I think that 'id_token' is not valid. But I don't know how to get that id_token, because I get the id_token after the request. Can anybody help me. Big Thanks!
headers = {
'alg': 'ES256',
'kid': settings.SOCIAL_AUTH_APPLE_ID_KEY
}
payload = {
'iss': settings.SOCIAL_AUTH_APPLE_ID_TEAM,
'iat': now,
'exp': now + TOKEN_TTL_SEC,
'aud': 'https://appleid.apple.com',
'sub': settings.SOCIAL_AUTH_APPLE_ID_CLIENT,
}
client_secret = jwt.encode(
payload,
settings.SOCIAL_AUTH_APPLE_ID_SECRET,
algorithm='ES256',
headers=headers
).decode("utf-8")
headers = {'content-type': "application/x-www-form-urlencoded"}
data = {
'client_id': 'com.scread.app',
'client_secret': client_secret,
'code': 'id_token',
'grant_type': 'authorization_code'
}
res = requests.post('https://appleid.apple.com/auth/token', data=data, headers=headers)
It seems that the service id must end like .app. Thus for example com.company.app. That was the solution for me.

Categories