How can I send this request using python requests library - python

How to send the below request using python requests library?
Request :
I have tried
with requests.Session() as session:
// Some login action
url = f'http://somewebsite.com/lib/ajax/service.php?key={key}&info=get_enrolled'
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
r = session.post(url, json=json_data)
But it doesn't give the output I want.

1.Define a POST request method
import urllib3
import urllib.parse
def request_with_url(url_str, parameters=None):
"""
https://urllib3.readthedocs.io/en/latest/user-guide.html
"""
http = urllib3.PoolManager()
response = http.request("POST",
url_str,
headers={
'Content-Type' : 'application/json'
},
body=parameters)
resp_data = str(response.data, encoding="utf-8")
return resp_data
2.Call the function with your specific url and parameters
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
key = "123456"
url = "http://somewebsite.com/lib/ajax/service.php?key={0}&info=get_enrolled".format(key)
request_with_url(url, json_data)

With no more info what you want and from what url it is hard to help but.
But try adding headers with the user-agent to the post. More headers may be needed, but User-Agent is a header that is often required.
with requests.Session() as session:
// Some login action
url = f'http://somewebsite.com/lib/ajax/service.php?key={key}&info=get_enrolled'
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
headers = {'User-Agent': 'Mozilla/5.0'}
r = session.post(url, json=json_data, headers=headers)

Related

Using Python, how do I make a request to the shopee API to get a list of products on offer with my affiliate link

Using Python, how do I make a request to the shopee API to get a list of products on offer with my affiliate link?
I've made several scripts, but they all have a signature issue or unsupported authentication attempt. Does anyone have a working example of how to do this?
Below are two code examples I made, but they don't work.
Query: productOfferV2 and shopeeOfferV2
code1:
import requests
import time
import hashlib
appID = '18341090114'
secret = 'XMAEHHWQD3OEGQX5P33AFRREJEDSQX76'
# Set the API endpoint URL
url = "https://open-api.affiliate.shopee.com.my/graphql"
payload = """
{
"query": "query Fetch($page:2){
productOfferV2(
listType: 0,
sortType: 2,
page: $page,
limit: 50
) {
nodes {
commissionRate
commission
price
productLink
offerLink
}
}
}",
"operationName": null,
"variables":{
"page":0
}
}
"""
payload = payload.replace('\n', '').replace(':0', f':{2}')
timestamp = int(time.time())
factor = appID+str(timestamp)+payload+secret
signature = hashlib.sha256(factor.encode()).hexdigest()
# Set the request headers
headers = {
'Content-type': 'application/json',
'Authorization': f'SHA256 Credential={appID},Timestamp={timestamp},Signature={factor}'
}
# Send the POST request
response = requests.post(url, payload, headers=headers)
data = response.json()
print(data)
return = error-invalid-signature-python
code2:
import requests
import json
import hmac
import hashlib
appID = '18341090114'
secret = 'XMAEHHWQD3OEGQX5P33AFRREJEDSQX76'
query = '''query { productOfferV2(item_id: ALL) {
offers {
shop_id
item_price
discount_price
offer_id
shop_location
shop_name
}
}
}'''
def generate_signature(query, secret):
signature = hmac.new(secret.encode(), query.encode(), hashlib.sha256).hexdigest()
return signature
signature = generate_signature(query, secret)
url = 'https://open-api.affiliate.shopee.com.my/graphql'
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + appID + ':' + signature
}
payload = {
'query': query
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
data = response.json()
print(data)

How to pass the customer id dynamically in the tap payment method to save the card value

I am sending the post request to the TAP PAYMENT GATEWAY in order to save the card, the url is expecting two parameters like one is the source (the recently generated token) and inside the url the {customer_id}, I am trying the string concatenation, but it is showing the error like Invalid JSON request.
views.py:
ifCustomerExits = CustomerIds.objects.filter(email=email)
totalData = ifCustomerExits.count()
if totalData > 1:
for data in ifCustomerExits:
customerId = data.customer_id
print("CUSTOMER_ID CREATED ONE:", customerId)
tokenId = request.session.get('generatedTokenId')
payload = {
"source": tokenId
}
headers = {
'authorization': "Bearer sk_test_**********************",
'content-type': "application/json"
}
# HERE DOWN IS THE url of TAP COMPANY'S API:
url = "https://api.tap.company/v2/card/%7B"+customerId+"%7D"
response = requests.request("POST", url, data=payload, headers=headers)
json_data3 = json.loads(response.text)
card_id = json_data3["id"]
return sponsorParticularPerson(request, sponsorProjectId)
Their expected url = https://api.tap.company/v2/card/{customer_id}
Their documentation link: https://tappayments.api-docs.io/2.0/cards/create-a-card
Try this..
First convert dict. into JSON and send post request with request.post:
import json
...
customerId = str(data.customer_id)
print("CUSTOMER_ID CREATED ONE:", customerId)
tokenId = request.session.get('generatedTokenId')
payload = {
'source': tokenId
}
headers = {
'authorization': "Bearer sk_test_**************************",
'content-type': "application/json"
}
pd = json.dumps(payload)
# HERE DOWN IS THE url of TAP COMPANY'S API:
url = "https://api.tap.company/v2/card/%7B"+customerId+"%7D"
response = requests.post(url, data=pd, headers=headers)
json_data3 = json.loads(response.text)
card_id = json_data3["id"]
return sponsorParticularPerson(request, card_id)
Please tell me this works or not...

Python - Request check?

POSTURL = 'https://partner.spreadshirt.de/login'
REQURL = 'https://partner.spreadshirt.de/dashboard'
payload = {
"username": 'test#gmail.com',
"password": 'somepassword'
}
import requests
with requests.Session() as session:
post = session.post(POSTURL, data=payload)
r = session.get(REQURL)
print("String" in r.text)
I know that this String is in present on the Website so this is not the problem. But my code returns False, so maybe I cant get to the REQURL? How could I determine if I got there?

Send request to azure inkrecognizer

I have registered at the https://azure.microsoft.com/ru-ru/try/cognitive-services
From there I got an API-key and an endpoint https://api.cognitive.microsoft.com/inkrecognizer
Here is my code:
import requests, json
subs_key = API_KEY
uri_base = 'https://api.cognitive.microsoft.com/inkrecognizer'
headers = {'Content-type': 'application/json',
"Ocp-Apim-Subscription-Key": subs_key}
body = {}
response =requests.request('POST', uri_base, json=body, data=None, headers=headers)
print('Response:')
parsed =json.loads(response.text)
print(json.dumps(parsed, sort_keys=True, indent=2))
However it gives me
Response:
{
"error": {
"code": "404",
"message": "Resource not found"
}
}
What am I doing wrong?
Here how the code should look like:
import requests, json
subs_key = API_KEY
uri_base = 'https://api.cognitive.microsoft.com/inkrecognizer/v1.0-preview/recognize'
headers = {'Content-type': 'application/json',
"Ocp-Apim-Subscription-Key": subs_key}
body = {}
response =requests.request('PUT', uri_base, json=body, data=None, headers=headers)
print('Response:')
parsed =json.loads(response.text)
print(json.dumps(parsed, sort_keys=True, indent=2))
And you will need to add into body 'language' and 'strokes'
GIST

Unexpected token END OF FILE at position 0 on Python POST request to Firebase

I am trying to send a message via Firebase to a certain client. This is my current (test) code:
import json
import requests
import urllib
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Content-Type': 'application/json', 'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
payload = json.dumps(payload)
res = requests.post(server, headers=headers, json=payload)
return res
which produces the following error, returned by Firebase:
JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.
The following JSON sent to Firebase seems correct to me:
{
"data": {
"type":"dataUpdate"
},
"to":"xxx"
}
which is in the format described by the Firebase documentation. Any idea why Firebase doesn't accept the given data?
When you use json=payload as a parameter to requests.post() you don't need to specify 'Content-Type': 'application/json' in the header. In addition, you are passing a string when the parameter should be payload as a dict (ie. no need for json.dumps())
Try this:
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
res = requests.post(server, headers=headers, json=payload)
return res

Categories