Here's the code of my test:
#pytest.mark.run(order=18)
def test_post(client):
"""
Test whether the test client has been added or not.
"""
print(f"\n\n {'>>>'*6} TESTING CLIENT POST {'<<<'*6} \n\n")
access_token = cognito_auth.get_access_token({
"username": os.environ["TEST_USER_EMAIL"],
"password": os.environ["TEST_USER_PASSWORD"]
})
data = {
"client_code": "999999.9.9",
"name": "AUTOMATED TEST CLIENT",
"short_name": "AUTOMATED TEST CLIENT",
"br_cnpj": "123809128312",
"br_im": "213798238974324",
"br_ie": "7893248932794324",
"address_id": 7665,
"is_inserted": False,
"skin_id": 1,
"plan_id": 1,
"organization": "CFR-100000",
"is_api_connected": False
}
response = client.post('http://localhost:5000/dev/api/client', json=data, headers={
"Authorization": f"Bearer {access_token}"
})
print("THE RESPONSE")
print(response.json)
According to this doc, everything should be fine, but instead, I get the following postgres error:
{'error': {'code': 500, 'type': '/errors/internal-server-error', 'message': '(psycopg2.errors.InvalidTextRepresentation) invalid input syntax for type integer: ""\nLINE 1: ... plan_id, organization, is_api_connected) VALUES (\'\', \'99999...\n ^\n\n[SQL: INSERT INTO tb_client (client_id, client_code, name, short_name, br_cnpj, br_im, br_ie, address_id, is_inserted, skin_id, plan_id, organization, is_api_connected) VALUES (%(client_id)s, %(client_code)s, %(name)s, %(short_name)s, %(br_cnpj)s, %(br_im)s, %(br_ie)s, %(address_id)s, %(is_inserted)s, %(skin_id)s, %(plan_id)s, %(organization)s, %(is_api_connected)s) ON CONFLICT ON CONSTRAINT tb_client_client_code_key DO NOTHING]\n[parameters: {\'client_id\': \'\', \'client_code\': \'999999.9.9\', \'name\': \'AUTOMATED TEST CLIENT\', \'short_name\': \'AUTOMATED TEST CLIENT\', \'br_cnpj\': \'123809128312\', \'br_im\': \'213798238974324\', \'br_ie\': \'7893248932794324\', \'address_id\': 7665, \'is_inserted\': False, \'skin_id\': 1, \'plan_id\': 1, \'organization\': \'CFR-100000\', \'is_api_connected\': False}]\n(Background on this error at: http://sqlalche.me/e/13/9h9h)'}}
Is the client post function seriously only expecting strings for json? It seems that the problem goes away when I use only strings, but I'm not expecting that on the API.
Even if I include "'Content-Type': 'application/json'" on the headers, I get the same error. What could be happening?
Related
I am trying to create a work-item using Python and requests library.
def test_create_work_item(work_items):
payload = {
'op': 'add',
'path': '/fields/System.Title',
'value': 'Sample bug'
}
pl = json.dumps(payload)
work_item = work_items.create(body=pl, type='bug')
assert work_item.status_code == 200
I am getting the below error for this :
{"$id":"1","innerException":null,"message":"You must pass a valid patch document in the body of the request.","typeName":"Microsoft.VisualStudio.Services.Common.VssPropertyValidationException,Microsoft.VisualStudio.Services.Common","typeKey":"VssPropertyValidationException","errorCode":0,"eventId":3000}
The same body works okay with Postman. So not sure what more is needed here to get it working.
I`m not familiar with Python.... Check this example: Create work item
The API uses an array of new fields:
[
{
"op": "add",
"path": "/fields/System.Title",
"from": null,
"value": "Sample task"
}
]
In your case, you use just one field in the request:
{
'op': 'add',
'path': '/fields/System.Title',
'value': 'Sample bug'
}
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.
I am trying to submit a POST request with data in json format to create a user using the Crowd API.
Here is the code snippet:
url = 'http://crowdserver/crowd/rest/usermanagement/1/user'
payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample#user.cool"}'
req = urllib2.Request(url, payload)
req.add_header('Content-type','application/json')
req.add_header("Accept", "application/json")
res = urllib2.urlopen(req)
output = resp.read()
print output
print resp.code
I get the following output:
Bad Request
Error code returned is 400
I thought this might perhaps be an encoding issue so replaced payload with:
payload = json.dumps({"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample#user.cool"})
Which returns:
NameError: name 'true' is not defined
So it looks like "active": true is not in an acceptable format.
If I add double quotes such as "active":"true" I get a TypeError; TypeError: not a valid non-string sequence or mapping object
Update
So the type error was indeed solved by setting the active attribute value to True but it turns out the 400 error was returned due to invalid user data, for example missing password or the user already exists read as the user already exists - I find it odd that the error for invalid input and an existing user share the same error code.
In this line:
payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample#user.cool"}'
Change ..., "active": true, ... to ..., "active": True, ...
Python's True/False are case-sensitive.
I try to do a payment with api yandex money.
I use
instance_id = ExternalPayment.get_instance_id(client_id)['instance_id']
api = ExternalPayment(instance_id)
def wallet_payments(access_token, ym_account, total, api):
wallet = Wallet(access_token)
request_options = {
"pattern_id": "p2p",
"to": ym_account,
"amount_due": total,
"comment": "test payment comment from yandex-money-python",
"message": "test payment message from yandex-money-python",
"label": "testPayment",
"test_payment": True,
"test_result": "success"
}
request_result = api.request(request_options)
process_payment = api.process({
"request_id": request_result['request_id'],
})
return process_payment['status']
request_result['status'] returns success, but after
`process_payment = api.process({
"request_id": request_result['request_id'],
})`
I get {'status': 'refused', 'error': 'illegal_param_ext_auth_success_uri'}.
How can I solve that?
From the yandex documentation:
illegal_param_ext_auth_success_uri:
The ext_auth_success_uri parameter has a missing or invalid value.
So you probably need to define a ext_auth_success_uri parameter which will be a listener url that receive yandex api response in case of success.
And you probably will need this one too which is the same but in case of error:
illegal_param_ext_auth_fail_uri:
The ext_auth_fail_uri parameter has a missing or invalid value.
source: https://tech.yandex.com/money/doc/dg/reference/process-payment-docpage/
I am using Batching requests in Google Analytics API(Python). Link to Batching : https://developers.google.com/api-client-library/python/guide/batch
Batching works fine when all the records via .add() are correct(valid). When one or more values are invalid, then the batching fails for all the records.
I added a call back function to handle the error and I saw that BAtching request is failing for all the records in the batch ( as opposed to only the invalid record). Is there a way to handle the error and skip the row/record which is invalid and continue with the rest of the records in the batch?
Below is the sample code I used and the error message :
def add_user_callback(request_id, response, exception):
if exception:
print "error :",exception
else:
print "successful"
def main():
## code to set the account, property and other variables
batch.add(service.management().webpropertyUserLinks().insert(
accountId=account_id,
webPropertyId=property_at,
body={
'permissions': {
'local': [
'READ_AND_ANALYZE'
]
},
'userRef': {
'email': 'valid_address#domain.com'
}
}))
batch.add(service.management().webpropertyUserLinks().insert(
accountId=account_id,
webPropertyId=property_at,
body={
'permissions': {
'local': [
'READ_AND_ANALYZE'
]
},
'userRef': {
'email': 'invalid_address#ddomain.com' ## i used a dummy id : pppp#domain.com
}
}))
batch.execute()
#Error :
#error : <HttpError 400 when requesting https://www.googleapis.com/analytics/v3/management/accounts/62974313/webproperties/UA-62974313-35/entityUserLinks?alt=json returned "Value for field user.email = ppppp#domain.com is not valid.">
#error : <HttpError 400 when requesting https://www.googleapis.com/analytics/v3/management/accounts/62974313/webproperties/UA-62974313-11/entityUserLinks?alt=json returned "Value for field user.email = ppppp#domain.com is not valid.">
Please let me know if you need more info.
Let's assume you have a list of users you want to add to profiles stored in a list users.
You can remove the bad emails with the following callback function:
def call_back(request_id, response, exception):
if exception is not None:
if isinstance(exception, HttpError):
message = json.loads(exception.content)['error']['message']
bad = 'Value for field user.email = (\S*) is not valid.'
match = re.match(bad, message)
if match:
bad_user = match.group(1)
if bad_user in users:
users.remove(bad_user)
else:
print response
After all the failed calls return you can re-attempt the batch call again by looping through the users and constructing a new batch request:
batch = BatchHttpRequest(callback=call_back)
for user in users:
request = analytics.management().profileUserLinks().insert(
accountId=ACCOUNT_ID,
webPropertyId=PROFILE_ID,
profileId=profile,
body={
'permissions': {'local': ['READ_AND_ANALYZE']},
'userRef': {'email': user}
}
)
batch.add(request, request_id=PROFILE_ID + user)
batch.execute()