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)
Related
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)
I try to "translate" this curl command
curl --request POST --header "Content-Type: application/json" --url http://some-url --user userName:apiKey --data '{ "some": "JSON data as string" }'
into Meteor's HTTP call. I tried this:
const options = {
{ "some": "JSON data as object" },
headers: {
'Content-Type': 'application/json',
},
params: {
user: 'userName:apiKey',
},
// Or alternatively
//
// user: 'userName:apiKey',
};
HTTP.call('POST', 'http://some-url', options, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
With curl command it works fine, with HTTP.call I get a 403, Forbidden. Authorization with userName:apiKey seems to fail. How do I specify the userName:apiKey in the HTTP.call example? Or maybe their is another problem?
If you need authentication, you need to add the auth parameter. The params parameter will actually set all the containing properties to be part of the POST request body.
const options = {
data: { "some": "JSON data as object" },
headers: {
'Content-Type': 'application/json',
},
auth: 'userName:apiKey'
}
Read: https://docs.meteor.com/api/http.html#HTTP-call
CURL Code run fine to send an Email using sendGrid,
I want to convert this code for Flutter Dart Application (as sendGrid does not have any API)
curl --request POST --url https://api.sendgrid.com/v3/mail/send --header 'Authorization: Bearer
API_KEY' --header 'Content-Type: application/json'
--data '{"personalizations": [{"to": [{"email": "test#gmail.com"}]}],
"from": {"email": "test#hotmail.com"},"subject": "Hello, World!",
"content": [{"type": "text/plain", "value": "Hello World App"}]}'
Please provide a full function
I tried something like this ...but it is not working
Future<Map<String, dynamic>> postRequest() async {
var url = 'https://api.sendgrid.com/v3/mail/send';
var body = json.encode({
"personalizations": [
{
"to": [
{"email": "test#gmail.com"}
]
}
],
"from": {"email": "test#hotmail.com"},
"subject": "Hello, World!",
"content": [
{"type": "text/plain", "value": "sent from flutter "}
]
});
var response = await http.post(
url,
headers: {
'Authorization':
'Bearer API_KEY',
'Content-Type': 'application/json',
},
body: body,
);
// todo - handle non-200 status code, etc
print(json.decode(response.body))
return json.decode(response.body);
}
Could you try this ?
import 'package:http/http.dart' as http;
void main() async {
var headers = {
'Authorization': 'Bearer API_KEY',
'Content-Type': 'application/json',
};
var data = '{"personalizations": [{"to": [{"email": "test#gmail.com"}]}], "from": {"email": "test#hotmail.com"},"subject": "Hello, World!", "content": [{"type": "text/plain", "value": "Hello World App"}]}';
var response = await http.post('https://api.sendgrid.com/v3/mail/send', headers: headers, body: data);
print(response.body);
if (response.statusCode != 200) throw Exception('http.post error: statusCode= ${response.statusCode}');
}
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.)
Trying to upload a file using requests module, but encountered Internal Server Error Its the same using poster module too:
import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
files={'file': open(r'Users/.../test.zip', 'rb')}
headers_info = {
'content-type': "multipart/form-data; boundary=---12345",
'x-api-service-version': "1.0",
'connection': "Keep-Alive",
'authorization': "Basic XXXXXXX",
'x-file-format': "decrypted",
'cache-control': "no-cache",
}
response = requests.post(url, data = payload , headers=headers_info , params=querystring , files=files)
print response.status_code
print response.text
I tested the api with POSTMAN (chrome extension to test rest API) and it seems to work fine with postman i get a success response and the file is uploaded.
The postman code for python shows :
import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
headers = {
'content-type': "multipart/form-data; boundary=---12345",
'accept-encoding': "gzip, deflate",
'x-api-service-version': "1.0",
'connection': "Keep-Alive",
'authorization': "Basic XXXXXXX",
'x-file-format': "decrypted",
'cache-control': "no-cache",
'postman-token': "XXXXXXX"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
Any suggestions for the same ? Am I missing something obvious? Thanks for any pointers you can share!
You don't have to specify 'content-type': "multipart/form-data; boundary=---12345", as well as empty data. Try to send request without headers
response = requests.post(url, params=querystring , files=files)
If you fail you might try to add 'authorization': "Basic XXXXXXX", 'postman-token': "XXXXXXX" headers