How to send POST request in python 3? - python

This is how my code looks like. I need to find out how can make call since I am new to Python.
HEADER = {
'Content-Type': 'application/x'
}
BODY = {
'scope': 'b2b',
'grant_type': 'client_credentials',
'client_id': var_clientid,
'client_secret': var_clientsecret
}

This is how I was able to connect!
import requests
url = 'someurlexample'
BODY = {
'scope': 'b2b',
'grant_type': 'client_credentials',
'client_id': var_clientid,
'client_secret': var_clientsecret
}
S = requests.session()
post = S.post(url, data=BODY, json=False)

Related

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:

Call API with Python using Token

I am trying to call an API using an access token.
Currently I am getting the token like so:
import requests
auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"
data = {
"grant_type": grant_type,
"client_id": client_id,
"client_secret": client_secret,
"scope": scope
}
auth_response = requests.post(auth_url, data=data)
print(auth_response.content)
This produces something like the following:
{"access_token":"eyJhbGdiOihSUzh1NhIsImtpZCI6IjlVUHVwYnBkTXN2RDZ0Ry1ZcDVRUlEiLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE2MzM4OTcxNDIsImV4cCI6hTYzMhkwMDc0MiwiaXNzIjoiaHR0cHM6Ly9vYXV0aC56YW1iaW9uLmNvbSIsImF1ZCI6ImFwaTEiLCJjbGllbnRfaWQiOiIwN0I3RkZEOC1GMDJCLTRERDAtODY2OS0zRURBNzUyRTMyNkQiLCJzY29wZSI6WyJhcGkxIl19.GU6lynvQYAAmycEPKbLgHE-Ck189x-a-rVz6QojkBIVpSLu_sSAX2I19-GlTjVWeLKoMVxqEfVq_qIaaQYa5KFmMLHRxP6J-RUgGK8f_APKjX2VNoMyGyAbZ0qXAJCvUTh4CPaRbZ6pexEishzr4-w3JN-hJLiv3-QH2y_JZ_V_KoAyu8ANupIog-Hdg8coI3wyh86OeOSAWJA1AdkK5kcuwC890n60YVOWqmUiAwPRQrTGh2mnflho2O3EZGkHiRPsiJgjowheD9_Wi6AZO0kplHiJHvbuq1PV6lwDddoSdAIKkDscB0AF53sYlgJlugVbtU0gdbXjdyBZvUjWBgw","expires_in":3600,"token_type":"Bearer","scope":"api1"}
Now I would like to call the API and pass the token in a header, but I am unsure how to do this and I have had a couple of goes at online resources
One of my attempts were:
url = "https://anotherurl.com/api/SecuredApi/StaffDetails"
head = {'Authorization': 'token {}'.format(auth_response)}
response = requests.get(url, headers=head)
print(response)
but this gives me a 403 error
Please assist me with pointing out my error
EDIT:
Thanks to #RaniSharim I have made some changes. I now have
import requests
import json
auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"
data = {
"grant_type": grant_type,
"client_id": client_id,
"client_secret": client_secret,
"scope": scope
}
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
"EndDateTime" : "2021-10-11 23:59:00"
}
auth_response = requests.post(auth_url, data=data)
# print(auth_response.content)
authjson = auth_response.content
authdata = json.loads(authjson)
token = (authdata['access_token'])
# print(token)
head = {"Authorization": "Bearer " + token}
response = requests.get(url, headers=head, params=dateparams)
print(response.content)
This looks better but I am now getting a 400 error:
"message":"The date range you have specified is in an invalid format. The required format is yyyy-MM-dd HH:mm:ss","status":400}
As best I can see my date ranges are already in the requested format, as set here:
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
"EndDateTime" : "2021-10-11 23:59:00"
}
Normally, 400 means front-end error, but when you do GET request
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
}
r = requests.get(url, params=dateparams)
print(r.url)
GET url will turn into sth like this:
https://oauth.thegivenurl.com/connect/token?StartDateTime=2021-01-01+00%3A00%3A00
see the str
2021-01-01+00%3A00%3A00
So if back-end can't handle this right, you'll get this error too
but you can use GET in another way:
requests.get(url, json=dateparams)
This will send your json params perfectly

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.

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.

Getting eBay Access Token (Exchanging auth token) with python requests

I'm trying to use this guide to get access token.
Here is my main file:
import requests
from utils import make_basic_auth_header, conf
code = '<Auth code here>'
url = "%s/identity/v1/oauth2/token" % conf('EBAY_API_PREFIX')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': make_basic_auth_header()
}
data = {
'grant_type': 'authorization_code',
# 'grant_type': 'refresh_token',
'state': None,
'code': code,
'redirect_uri': conf('EBAY_RUNAME')
}
r = requests.post(
url,
data=data,
headers=headers,
)
Here's the make_basic_auth_header() function:
def make_basic_auth_header():
auth_header_payload = '%s:%s' % (conf('EBAY_APP_ID'), conf('EBAY_CERT_ID'))
auth_header_base64 = base64.b64encode(auth_header_payload)
auth_header = 'Basic %s' % auth_header_base64
return auth_header
But all I get in r.json() is:
{u'error_description': u'request is missing a required parameter or malformed.', u'error': u'invalid_request'}
I'm frustrated - what am I doing wrong?
sorry, I was stupid enough and I didn't see the tickbox on ebay.

Categories