400 Bad Request POST request - python

I'm programing in Python some API application, using POSTMAN, and a Bearer token. I already receive the token, and to some GET with success response.
But when doing a insert of a record I got 400 Bad request error, this is the code I'm using for adding the record
def add_identity(token, accountid, newIdentity):
end_point = f"https://identityservice-demo.clearid.io/api/v2/accounts/{accountid}/identities/"
headers = CaseInsensitiveDict()
headers["Content-type"] = "application/json; charset=utf-8"
headers["Authorization"] = f"Bearer {token}"
response = requests.request("POST", end_point, data=newIdentity, headers=headers)
print(f"{response.reason} - {response.status_code}")
the variable newIdentity has the following data
nID = {
"privateData": {
"birthday": "1985-30-11T18:23:27.955Z",
"employeeNumber": "99999999",
"secondaryEmail": "",
"cityOfResidence": "Wakanda",
"stateOfResidence": "Florida",
"zipCode": "102837",
"phoneNumberPrimary": "(999)-999-999)",
"phoneNumberSecondary": "+5-(999)-999-9999"
},
"companyData": {
"approvers": [
{
"approverId": ""
}
],
"supervisorName": "Roger Rabbit",
"departmentName": "Presidency",
"jobTitle": "President",
"siteId": "string",
"companyName": "ACME Inc",
"workerTypeDescription": "",
"workerTypeCode": ""
},
"systemData": {
"hasExtendedTime": "true",
"activationDateUtc": "2022-03-16T18:23:27.955Z",
"expirationDateUtc": "2022-03-16T18:23:27.955Z",
"externalId": "999999",
"externalSyncTimeUtc": "2022-03-16T18:23:27.955Z",
"provisioningAttributes": [
{
"name": ""
}
],
"customFields": [
{
"customFieldType": "string",
"customFieldName": "SSNO",
"customFieldValue": "9999999"
}
]
},
"nationalIdentities": [
{
"nationalIdentityNumber": "0914356777",
"name": "Passport",
"issuer": "Wakanda"
}
],
"description": "1st Record ever",
"status": "Active",
"firstName": "Bruce",
"lastName": "Wayne",
"middleName": "Covid",
"displayName": "Bruce Wayne",
"countryCode": "WK",
"email": "bruce.wayne#wakanda.com",
"creationOnBehalf": "ACME"
}
what could solve the problem?
the swagger for the API is
https://identityservice-demo.clearid.io/swagger/index.html#/Identities/get_api_v2_accounts__accountId__identities
Thanks for your help in advance

data have to be a dict ,, you can try import json and data=json.dumps(newIdentity) ,
and if it keeps returning 400 , check well that all the parameters are accepted by the api by recreating the request with Postman or any request editor, and if the api uses any web interface check what is the reason for that 400 . This was translated by Google so I don't know if I said something nonsense :)

Related

create Xero invoice using python request raise "No data has been processed for this endpoint. This endpoint is expecting Invoice data to be specifed"

I am trying to create an Invoice in Xero accounting using one of the Xero provided rest api, i used a Python requests library to access the certain Invoice rest api but unable to create an invoice. It raise following error
{'ErrorNumber': 17, 'Type': 'NoDataProcessedException', 'Message': 'No data has been processed for this endpoint. This endpoint is expecting Invoice data to be specifed in the request body.'}
Here is my my python code,
def XeroRequests():
new_tokens = XeroRefreshToken('*****************************')
xero_tenant_id = XeroTenants(new_tokens[0])
get_url = 'https://api.xero.com/api.xro/2.0/Invoices'
response = requests.post(get_url,
headers = {
'Authorization': 'Bearer ' + new_tokens[0],
'Xero-tenant-id': xero_tenant_id,
'Accept': 'application/json'
},
data = {
"Type": "ACCREC",
"Contact": {
"ContactID": "eaa28f49-6028-4b6e-bb12-d8f6278073fc"
},
"Date": "\/Date(1518685950940+0000)\/",
"DueDate": "\/Date(1518685950940+0000)\/",
"DateString": "2009-05-27T00:00:00",
"DueDateString": "2009-06-06T00:00:00",
"LineAmountTypes": "Exclusive",
"LineItems": [
{
"Description": "Consulting services as agreed (20% off standard rate)",
"Quantity": "10",
"UnitAmount": "100.00",
"AccountCode": "200",
"DiscountRate": "20"
}
]
})
json_response = response.json()
print("POST response ", json_response)
Whats wrong i did here?
You need to give data like this as per the API documentation
data = {
"Invoices": [{
"Type": "ACCREC",
"Contact": {
"ContactID": "eaa28f49-6028-4b6e-bb12-d8f6278073fc"
},
"Date": "\/Date(1518685950940+0000)\/",
"DueDate": "\/Date(1518685950940+0000)\/",
"DateString": "2009-05-27T00:00:00",
"DueDateString": "2009-06-06T00:00:00",
"LineAmountTypes": "Exclusive",
"LineItems": [
{
"Description": "Consulting services as agreed (20% off standard rate)",
"Quantity": "10",
"UnitAmount": "100.00",
"AccountCode": "200",
"DiscountRate": "20"
}
]
}
]
}

Unable to POST request correctly

I wanted to shorten the link through the wklej API, they have documentation on the site but only for php, I can’t understand what the problem is. Here is an example request from their website:
https://wklej.to/api/url/add
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://wklej.to/api/url/add",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 2,
CURLOPT_TIMEOUT => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer HERE IS MY API KEY",
"Content-Type: application/json",
),
CURLOPT_POSTFIELDS => '{
"url": "https:\/\/google.com",
"custom": "google",
"password": "mypass",
"expiry": "2020-11-11 12:00:00",
"type": "splash",
"metatitle": "Not Google",
"metadescription": "Not Google description",
"metaimage": "https:\/\/www.mozilla.org\/media\/protocol\/img\/logos\/firefox\/browser\/og.4ad05d4125a5.png",
"geotarget": [
{
"location": "Canada",
"link": "https:\/\/google.ca"
},
{
"location": "United States",
"link": "https:\/\/google.us"
}
],
"devicetarget": [
{
"device": "iPhone",
"link": "https:\/\/google.com"
},
{
"device": "Android",
"link": "https:\/\/google.com"
}
],
"languagetarget": [
{
"language": "en",
"link": "https:\/\/google.com"
},
{
"language": "fr",
"link": "https:\/\/google.ca"
}
],
"parameters": [
{
"name": "aff",
"value": "3"
},
{
"device": "gtm_source",
"link": "api"
}
]
}',
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
I tried making a request like this:
r = requests.post("https://wklej.to/api/url/add", data = {"api": "HERE IS MY API KEY", "url": "https://amazon.com"})
but in response i get this:
{"error":1,"message":"A valid API key is required to use this service."}
I recently started learning python and would like to know what I did wrong, if I understand correctly then I need to send a request in JSON format. By the way, their documentation states that in the request you only need to specify a link for the shortener and an api key, everything else is optional.
update
now i do this:
headers = {
'Authorization': 'Bearer MY_API_KEY',
'Content-Type': 'application/json',
}
data = {"url": "https://amazon.com"}
r = requests.post("https://wklej.to/api/url/add", headers=headers, data=data)
and response is :
{"error":1,"message":"Missing required parameter: url"}
Why is it missing ? I have set this in "data"
Try this instead:
r = requests.post("https://wklej.to/api/url/add", headers=headers, json=data)
The data argument will be form-encoded, while the json argument serializes the passed value to json. See documentation here.

Can't get discord webhook to send with json

I've been trying to make a discord webhook, and for some reason I can't get it to send to save my life. I have all the embeds in a json file, and am trying to run it with python. Any help would be greatly appreciated.
json file:
{
"embeds": [
{
"title": "Title",
"color": 11393254,
"fields": [
{
"name": "Name1",
"value": "value1"
},
{
"name": "Name2",
"value": "value2",
"inline": true
},
],
"footer": {
"text": "Footer",
"icon_url": "random image url"
},
"timestamp": "now",
"thumbnail": {
"url": "random image url"
}
}
],
"username": "Username"
}
python code:
import requests, json
with open('webhook.json') as json_file:
data = json.load(json_file)
url = 'https://discord.com/api/webhooks/xxxxx'
headers={"Content-Type": "application/json"}
requests.post(url, data=json.dumps(data), headers=headers)
What's the status code you get back from the POST? That could be a clue where it's going awry.

Python post request, problem with posting

I'm trying to write a typeform bot but I am a totally beginner so I have problems with request.post
I am trying to fill this typeform: https://typeformtutorial.typeform.com/to/aA7Vx9
by this code
import requests
token = requests.get("https://typeformtutorial.typeform.com/app/form/result/token/aA7Vx9/default")
data = {"42758279": "true",
"42758410": "text",
"token": token}
r = requests.post("https://typeformtutorial.typeform.com/app/form/submit/aA7Vx9", data)
print(r)
I think that something is wrong with "data" and I am not sure if I use token in a good way. Could you help me?
So, first of all, you need to get another field with the token. To do that, you should pass the header 'accept': 'application/json' in your first request. In the response, you'll get the json object with the token and landed_at parameters. You should use them in the next step.
Then, the post data shoud be different from what you're passing. See the network tab in the browser's developer tools to find out the actual template. It has a structure like that:
{
"signature": <YOUR_SIGNATURE>,
"form_id": "aA7Vx9",
"landed_at": <YOUR_LANDED_AT_TIME>,
"answers": [
{
"field": {
"id": "42758279",
"type": "yes_no"
},
"type": "boolean",
"boolean": True
},
{
"field": {
"id": "42758410",
"type": "short_text"
},
"type": "text",
"text": "1"
}
]
}
And finally, you should convert that json to text so the server would successfully parse it.
Working example:
import requests
import json
token = json.loads(requests.post(
"https://typeformtutorial.typeform.com/app/form/result/token/aA7Vx9/default",
headers={'accept': 'application/json'}
).text)
signature = token['token']
landed_at = int(token['landed_at'])
data = {
"signature": signature,
"form_id": "aA7Vx9",
"landed_at": landed_at,
"answers": [
{
"field": {
"id": "42758279",
"type": "yes_no"
},
"type": "boolean",
"boolean": True
},
{
"field": {
"id": "42758410",
"type": "short_text"
},
"type": "text",
"text": "1"
}
]
}
json_data = json.dumps(data)
r = requests.post("https://typeformtutorial.typeform.com/app/form/submit/aA7Vx9", data=json_data)
print(r.text)
Output:
{"message":"success"}

Failed Authentication Error while calling Australia Post Shipments API

While following the example of create-shipments ,i am getting this error response
{
"errors": [
{
"message": "The request failed authentication",
"error_code": "API_001",
"error_name": "Unauthenticated request"
}
]
}
here is my example code:
import json,requests
headers = {"account-number":"1234567890",'auth-key':'aaaaaaaa-1111-2222-927d-c793f4fb1461','Content-Type': 'application/json'}
print requests.post('https://digitalapi.auspost.com.au/shipping/v1/shipments', data=json.dumps(data), headers=headers).content
and data is something like:
data={
"shipments":[
{
"shipment_reference":"XYZ-s001-01",
"customer_reference_1":"Order S00o1",
"customer_reference_2":"SKU-1",
"email_tracking_enabled":True,
"from":{
"name":"prakash sharma",
"lines": [
"1 Main Street"
],
"suburb": "MELBOURNE",
"state": "VIC",
"postcode": "3000",
"phone": "0401234567",
"email":"prakashsharmacs24#gmail.com"
},
"to":{
"name":"Jane Smith",
"business_name":"Smith Pty Ltd",
"lines":[
"123 Centre Road"
],
"suburb":"Sydney",
"state":"NSW",
"postcode":"2000",
"phone":"0412345678",
"email":"jane.smith#smith.com"
},
"items":[
{
"item_reference":"SKU-1",
"product_id":"T28S",
"length":"10",
"height":"10",
"width":"10",
"weight":"1",
"authority_to_leave":False,
"allow_partial_delivery":True,
"features":{
"TRANSIT_COVER":{
"attributes":{
"cover_amount":1000
}
}
}
}
]
}
]
}
My auth key and account-number are valid as it work in case of GET request over /postage/parcel/international/service.json and /postage/parcel/domestic/service.json
Problem is solved, as shipping/v1/shipments required Basic Authorization so we need to set the header as
:
headers={'Content-Type':'application/json',
'Authorization':'Basic '+base64.b64encode(API_Key+":"+Password_Secret),
'Account-Number':AccountNumber}
OR
we can use HTTPBasicAuth as auth=HTTPBasicAuth(API_Key, Password_Secret) in the requests.post.

Categories

Resources