How to convert CURL [Send Grid] to http post in Flutter? - http

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}');
}

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)

Translating curl command to Meteor's HTTP call

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

How to upload the image using LinkedIn API without using curl request?

I've used the curl request to upload an image which successfully worked for me.
curl -i --upload-file ~/Desktop/Myimage.jpg -H 'Authorization: Bearer Redacted' "https://api.linkedin.com/mediaUpload/C5522AQHn46pwH96hxQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQLKRJOn_yNw6wAAAW2T0DWnRStny4dzsNVJjlF3aN4-H3ZR9Div77kKoQ&app=1983914&sync=0&v=beta&ut=1Dnjy796bpjEY1"
I've tried using the same request with "request" package which got failed and redirected me to the "404 page not found" LinkedIn page.
Here is the code:
const options = {
headers: {
'Authorization': `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'multipart/form-data'
},
method: 'put',
url: mediaUploadUrl
}
fs.createReadStream(filePath).pipe(request(options, function(err, httpsResponse, body){
if ( err ) {
console.log('err', err);
response(callback, 400, err);
} else {
console.log(body);
response(callback, 200, { mediaUrn });
}
}));
Documentation page that I've followed: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/rich-media-shares
#linkedin
The request method is supposed to be POST but you are sending PUT instead, below code should work.
const options = {
headers: {
'Authorization': `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'multipart/form-data'
},
method: 'post',
url: mediaUploadUrl
}
fs.createReadStream(filePath).pipe(request(options, function(err, httpsResponse, body) {
if ( err ) {
console.log('err', err);
response(callback, 400, err);
} else {
console.log(body);
response(callback, 200, { mediaUrn });
}
}));

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.)

HTTP.post to FCM Server not working

I am using Ionic 2 with HTTP native module to make a post request to FCM server for push notifications. The code I am using is:
HTTP.post(
"https://fcm.googleapis.com/fcm/send",
{
"notification": {
"title": "Notification title",
"body": "Notification body",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
},
"to": "device token",
},
{
Authorization: {
key: "AUTHORIZATION KEY HERE"
}
})
Its giving me an error:
Unimplemented console API: Unhandled Promise rejection:
Unimplemented console API: Error: Uncaught (in promise): [object Object]
I tried the post request with Postman, it works perfectly fine delivering push notifications.
The code with Postman is:
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=Authorisation Key
Cache-Control: no-cache
Postman-Token: 446e253b-179a-d19b-21ea-82d9bb5d4e1c
{
"to": "Device Token",
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
}
"notification":{
"title":"Notification title",
"body":"Notification body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
}
Questions:
I am unable to add content-type to the header in the HTTP post request, but it works with postman.
If I try to add a function(response) { to get the response from the server, it gives me an error. The documentation for the same is at https://github.com/wymsee/cordova-HTTP
why are you using HTTP native module? Angular has a built in Http.
Using this one (importing HttpModule from #angular/http in your NgModule) you can just call
import { Http, Headers } from '#angular/http';
......
constructor(public http: Http) { }
sendPushNotification(deviceId: string) {
let url = 'https://fcm.googleapis.com/fcm/send';
let body =
{
"notification": {
"title": "Notification title",
"body": "Notification body",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
},
"to": "device token"
};
let headers: Headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'key='+this.someKey
});
let options = new RequestOptions({ headers: headers });
console.log(JSON.stringify(headers));
this.http.post(url, body, headers).map(response => {
return response;
}).subscribe(data => {
//post doesn't fire if it doesn't get subscribed to
console.log(data);
});
}
push.on('notification', (data) => {
if (data.additionalData.foreground) {
// if application open, show popup
let confirmAlert = this.alertCtrl.create({
title: data.title,
message: data.message,
buttons: [{
text: 'Ignore',
role: 'cancel'
}, {
text: 'Go to',
handler: () => {
//TODO: Your logic here
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
}]
});
confirmAlert.present();
} else {
//if user NOT using app and push notification comes
//TODO: Your logic on click of push notification directly
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
});
push.on('error', (e) => {
alert(e);
});
});

Resources