The request body contains invalid JSON - python-requests

I'm trying to POST to a discord webhook URL using Python Requests but whenever the embeds field is present, it returns {'code': 50109, 'message': 'The request body contains invalid JSON.'}. If I remove embeds and just leave content it will send without any errors.
My code is:
url = "https://discord.com/api/webhooks/[redacted]/[redacted]"
headers = {
"Content-Type": "application/json"
}
data = {
"username": "Webhook",
"content": "Hello, World!",
"embeds": [{
"title": "Hello, Embed!",
"description": "This is an embedded message."
}]
}
res = requests.post(url, headers=headers, data=data)
I've tried various version of the Discord API but the result is always the same.

I got it working by replacing
requests.post(url, headers=headers, data=data)
with
requests.post(url, json=data)

Try this. I think the requests library may be adding a header called content-type which conflicts with your header Content-Type, which makes the Discord API return an error:
url = "https://discord.com/api/webhooks/[redacted]/[redacted]"
headers = {
"content-type": "application/json"
}
data = {
"username": "Webhook",
"content": "Hello, World!",
"embeds": [{
"title": "Hello, Embed!",
"description": "This is an embedded message."
}]
}
res = requests.post(url, headers=headers, json=data)

Related

Curl call to python translation in postman

I have a success Post call to an api via postman, but when I generate the code snippet for the curl call , payload section throwing an error
The working curl call
curl --location --request POST 'url_to_be_used' \
--header 'Authorization: Token [QWS-T]eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' \
--form 'payload={
"data": {
"Service_Type": "Tele-Consultation",
"CSR_Partner_Logo": [["", "", "", ""], []],
"Service_Count": "500+",
"Name": "name_to_be_given"
}
}'
Code snippet generated as below
import requests
url = "url_to_be_used"
payload = {'payload': '{
"data": {
"Service_Type": "Tele-Consultation",
"CSR_Partner_Logo": [["", "", "", ""], []],
"Service_Count": "500+",
"Name": "name_to_be_given"
}
}'}
files = [
]
headers = {
'Authorization': 'Token [QWS-T]eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
}
response = requests.request("POST", url, headers=headers, data = payload, files = files)
print(response.text.encode('utf8'))
python throws error as SyntaxError: EOL while scanning string literal for the payload which is because of the single quotes i am guessing. When i remove the single code to make it syntax error free , the final post call throws "invalid payload" error. Please guide how to fix it.
As per documentation payload expects dictionary:
https://requests.readthedocs.io/en/master/user/quickstart/
so try:
import requests
url = "url_to_be_used"
payload={
"data": {
"Service_Type": "Tele-Consultation",
"CSR_Partner_Logo": [["", "", "", ""], []],
"Service_Count": "500+",
"Name": "name_to_be_given"
}
}
files=[
]
headers = {
'Authorization': 'Token [QWS-T]eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
Can you also try with three single quotes
import requests
url = "url_to_be_used"
payload={'payload': '''{
"data": {
"Service_Type": "Tele-Consultation",
"CSR_Partner_Logo": [["", "", "", ""], []],
"Service_Count": "500+",
"Name": "name_to_be_given"
}
}'''}
files=[
]
headers = {
'Authorization': 'Token [QWS-T]eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)

Axios post request returning 403 when sending firebase notification

Hi I am trying to send notification to my app using firebase post method its working fine in postman but when I try to do post method in my app its returning 403. I tried implementing another get request its working fine so no problem with axios setup.
export const postData = function (url, payload) {
return AXIOS.post(url, payload, config);
};
let config = {
headers: {
'Content-Type': 'application/json',
"Authorization" : "key= *****myKey****"
}
};
Here is my post mehtod
let body = {
"to": "******myTokeb*******",
"notification": {
"title": "Title here",
"body": "R(body)",
"mutable_content": true,
"sound": "Tri-tone"
}
};
postData("http://fcm.googleapis.com/fcm/send",body).then((d)=>{
console.log("d",d)
}).catch((e)=>{
console.log("e",e);
});
Error
Error: Request failed with status code 403
at createError (D:\projects\fiver\Roeyat\node_modules\axios\lib\core\createError.js:16)
at settle (D:\projects\fiver\Roeyat\node_modules\axios\lib\core\settle.js:17)
at EventTarget.handleLoad (D:\projects\fiver\Roeyat\node_modules\axios\lib\adapters\xhr.js:61)
at EventTarget.dispatchEvent (D:\projects\fiver\Roeyat\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:567)
at EventTarget.__didCompleteResponse (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
Use HTTPS in postData
That will work!

Posting Image to Personal Profile Invalid Request Parameters

Unable to share image content through share endpoint, image asset is uploaded through assets API but my request to share API which is copied directly from the example here https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/share-api?context=linkedin/compliance/context#share-content returns an error, invalid parameters in the request body [/Headers] see below details.
Request Headers:
{Authorization: Bearer ***
X-Restli-Protocol-Version: 2.0.0
}
Request Body
{"content":{"contentEntities":[{"entity":"urn:li:digitalmediaAsset:C5622AQEEn3mmqzCb5w"}],"title":"Great Result","landingPageUrl":"https://google.com.au","shareMediaCategory":"IMAGE"},"distribution":{"linkedInDistributionTarget":{}},"owner":"urn:li:person:zzR_UbXjsG","subject":"Great Result","text":{"text":"Great result, couldn't have gone better #realestate"}}
Scopes:
scope=r_emailaddress w_member_social w_organization_social r_basicprofile rw_company_admin rw_organization_admin
Error:
{"serviceErrorCode":100,"message":"Unpermitted fields present in REQUEST_BODY: Data Processing Exception while processing fields [/Headers]","status":403}
It looks like the error message has to do with the headers. Your request body is JSON, but you don't have a Content-Type header set, so this could be the problem:
Content-Type: application/json
Generally, you need a Content-Length header to be sent along with that, but most of the time the client you are using to send the request handles setting that one.
I'm not sure how you're making the request, but here is a fetch() example in JavaScript (make sure you put the correct auth token in the Authorization header):
const url = 'https://api.linkedin.com/v2/shares';
const requestBody = {
"content": {
"contentEntities": [
{
"entity": "urn:li:digitalmediaAsset:C5622AQEEn3mmqzCb5w"
}
],
"title": "Great Result",
"landingPageUrl": "https://google.com.au",
"shareMediaCategory": "IMAGE"
},
"distribution": {
"linkedInDistributionTarget": {}
},
"owner": "urn:li:person:zzR_UbXjsG",
"subject": "Great Result",
"text": {
"text": "Great result, couldn't have gone better #realestate"
}
};
async function makeRequest(url, requestBody) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ***',
'X-Restli-Protocol-Version': '2.0.0'
},
body: JSON.stringify(requestBody) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
// make the actual request
makeRequest(url, requestBody);

API always error 408 - Invalid Data Type Sent

I really don't know what happen with this error (I mean by, is this related to the Flutter or Dart or the package that I used or the API that I used). In a nutshell, it always giving me back error code 408 - Invalid data type sent from my flutter App, while I COMPLETELY could done it in Postman and been tried it with PHP.
I just wanna call a normal POST request to my payment gateway API (I use Midtrans).
Here is my result:
From Postman
From my app in Flutter within VS Code
What am I doing wrong? I am completely has no clue about this.
I will give the detail below for anyone who want to try a simple call to this API so you can reproduce this.
Endpoint
https://api.sandbox.midtrans.com/v2/charge
Body
"payment_type": "bank_transfer",
"bank_transfer": {
"bank": "permata",
"va_number": "1234567890"
},
"transaction_details": {
"order_id": "order-101b-{{2020-11-0222rrd324dzz}}",
"gross_amount": 44000
},
"customer_details": {
"email": "richie.permana#gmail.com",
"first_name": "Richie",
"last_name": "Permana",
"phone": "+6281 1234 1234"
},
"item_details": [
{
"id": "item01",
"price": 21000,
"quantity": 1,
"name": "Schema Programmer"
},
{
"id": "item02",
"price": 23000,
"quantity": 1,
"name": "Ayam Xoxoxo"
}
]
}
This is the header
{
'content-type': 'application/json',
'accept': 'application/json',
'authorization':
'Basic U0ItTWlkLXNlcnZlci1kNnJNbGp5ZDBKSDgyOEhBT28tSWkxM0E=',
'cache-control': 'no-cache'
}
My Dart Function Snippet
Future _makePayment() async {
String url = "https://api.sandbox.midtrans.com/v2/charge";
final Map<String, String> header = {
'content-type': 'application/json',
'accept': 'application/json',
'authorization':
'Basic U0ItTWlkLXNlcnZlci1kNnJNbGp5ZDBKSDgyOEhBT28tSWkxM0E=',
'cache-control': 'no-cache'
};
var json = jsonEncode({
"payment_type": "bank_transfer",
"bank_transfer": {"bank": "permata", "va_number": "1234567890"},
"transaction_details": {
"order_id": "order-101b-{{2020-11-0222rrddzz557}}",
"gross_amount": 44000
},
"customer_details": {
"email": "richie#example.com",
"first_name": "Richie",
"last_name": "Permana",
"phone": "+6281 1234 1234"
},
"item_details": [
{
"id": "item01",
"price": 21000,
"quantity": 1,
"name": "Schema Programmer"
},
{"id": "item02", "price": 23000, "quantity": 1, "name": "Ayam Xoxoxo"}
]
});
Response response = await post(
url,
headers: header,
body: json,
);
var res = jsonDecode(response.body);
print(
"payloadddded =>> ${json.runtimeType}\n");
if (res['status_code'] == 201) {
print("ngeheeeee berhasil MIDTRAANSS =>> ${res['status_code']}");
} else {
print("res full =>> ${response.body}");
print("ape kaden => ${res['status_code']} || terosz => $res");
}
}
Note:
For the body, you may be need put more attention on the order_id because it will return some error if you not change the order_id (yes, think it like any other primary key id).
API Docs: https://api-docs.midtrans.com/
I really appreciate any helps or workaround given.
Thank you very much.
Dart's package:http manipulates the content-type header under the hood. If it does the encoding from string to bytes for you (i.e. if body is a string) then it adds a charset=xxx suffix to the content type - it becomes, for example application/json; charset=utf-8.
Apparently your server is allergic to this. (It shouldn't be, but whatever...). You can prove this using the dart:io http client.
var client = HttpClient();
var request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json; charset=utf-8');
request.headers.add(
'authorization',
'Basic U0ItTWlkLXNlcnZlci1kNnJNbGp5ZDBKSDgyOEhBT28tSWkxM0E=',
);
request.add(utf8.encode(json));
var response2 = await request.close();
var reply = await response2.transform(utf8.decoder).join();
print(reply);
client.close();
This gives the same 408 error but does not if the charset suffix is removed.
There's a simple solution. Don't allow http to do the encoding for you - do it yourself.
var response = await http.post(
url,
headers: headers,
body: utf8.encode(json),
);
(Your json apparently needs work, because this now complains that the json is invalid, but that's easy to compare with your working postman.)

Parse.com push api - randomly returns 404

I have a problem with parse api. I'm sending this data:
{
"where": {
"deviceType": "android"
},
"data": {
"action": "somestring",
"aps": {
"alert": "some title",
"id": 4353453,
"s": "some_short_string"
}
}
}
to https://api.parse.com/1/push using POST method with headers:
Content-Type: "application/json",
X-Parse-Application-Id: "myid",
X-Parse-REST-API-Key: "mykey",
User-Agent: "PHPWebapiClient"
Api returns mostly status 200, but sometimes it returns 404. Of course in this case notifications wont work, and even don't appear in parse admin. It seems totally random, i can't determine the cause. Interestingly api always return this header:
http_code: "HTTP/1.0 200 Connection established"
no matter what response code is returned.
I tried resending request, but this didn't help.
Is there anyone experiencing similar problems? Please help me sort this out.

Resources