Hubspot client library file upload returning 400 Bad Request - hubspot-crm

I'm using hubspot client library in nodejs. https://github.com/HubSpot/hubspot-api-nodejs
Below is my code
import FormData from "form-data";
import fs from "fs";
import os from "os";
import uniqueFilename from "unique-filename";
const requestBody = req.body; //Binary data from postman post request
const path = uniqueFilename(os.tmpdir(), 'test.png');
fs.writeFileSync(path, requestBody);
const formData = new FormData();
const options = {
access: "PUBLIC_NOT_INDEXABLE",
overwrite: false,
duplicateValidationStrategy: "NONE",
duplicateValidationScope: "EXACT_FOLDER"
};
formData.append("folderId", 'folder id');
formData.append("options", JSON.stringify(options));
formData.append("file", fs.createReadStream(path));
const fileUploadReq = await hubspotClient.client.apiRequest({
method: 'POST',
path: '/filemanager/api/v3/files/upload',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
});
Seems all api working file except file upload. it is returning 400 Bad request error.
same formData i've tried with axios post request it is working.
Am i missing something or it something wrong with hubspot client library?

Related

how can i convert this Rapid API's HTTP Url to Dart Http request

i have this URL
https://zozor54-whois-lookup-v1.p.rapidapi.com/?rapidapi-key=MYAPIKEYb&domain=DOMAINTOCHECK&format=FORMATTYPE
rapid API gives two header's and other things
I Tried This Code By Exploring HTTP package But Not Working:
import 'package:http/http.dart' as http;
void main() async {
var url = 'https://zozor54-whois-lookup-v1.p.rapidapi.com/?domain=sendrank.com&format=json';
var headers = {
'X-Rapidapi-Key': APIKEyY
'X-Rapidapi-Host': 'zozor54-whois-lookup-v1.p.rapidapi.com',
'Host': 'zozor54-whois-lookup-v1.p.rapidapi.com'
};
var response = await http.get(url, headers: headers);
print(response.body);
}
You need to encode the url with the parameters
final queryParameters = {
'domain': 'sendrank.com',
'format': 'json',
};
final uri = Uri.https('zozor54-whois-lookup-v1.p.rapidapi.com', '/', queryParameters);
final response = await http.get(uri, headers: {
'X-Rapidapi-Key': APIKEyY
'X-Rapidapi-Host': 'zozor54-whois-lookup-v1.p.rapidapi.com',
'Host': 'zozor54-whois-lookup-v1.p.rapidapi.com'
});
See How do you add query parameters to a Dart http request?

Getting Error: XMLHttpRequest error when using dart

I have tried POST request from dart code to django rest api on local machine.
the API works when I do POST from Postman but fails when using dart.
Can someone please explain why !
my dart code :
void post_call() async {
var headers = {
'Content-Type': 'application/json',
};
var data = {"_selectedValue":"yes","_DescriptionValue":"yes","_namefieldValue":"yes","_contactValue":"yes","_emailValue" : "yes"};
var url = Uri.parse('http://127.0.0.1:8000/first_app/forms/');
var res = await http.post(url, headers: headers, body: json.encode(data));
if (res.statusCode != 200) throw Exception('http.post error: statusCode= ${res.statusCode}');
print(res);
}
the API works when I do POST from Postman but fails when using dart.

Trying to upload media to the Meta Whatsapp API but running into errors

Context: I need to send media templates in which I need to send local files. Thus I need to upload the files to the WhatsApp API to get the Media Id, which I can then use to send the message templates.
The issue: I am running into errors while sending the post request to the server through DART. However the same call is working when sent through postman. I have tried sending the data both as a JSON and as form-data, but both are returning errors. I am attaching the code below, as well as the errors I am facing. Any help is really appreciated.
Getting the file path
upload() async{
if(await Permission.storage.isGranted){
FilePickerResult? choice = await FilePicker.platform.pickFiles(allowMultiple: false);
String? path = choice?.files.single.path;
if(path != null){
uploadJson(path);
// uploadFormData(path);
}
}else{
Permission.storage.request();
}
}
Uploading JSON
uploadJson(String path) async{
File imgfile = File(path);
Uint8List imgbytes = await imgfile.readAsBytes();
String bs4str = base64.encode(imgbytes);
print(bs4str);
var headers = {
'Authorization': variables.authorizationToken,
"Content-Type": 'application/json',
};
var body = jsonEncode({
'file': '$bs4str;type=image/jpeg',
'messaging_product':'whatsapp'
});
Response response = await post(Uri.parse('${variables.baseURL}${variables.phoneNumberId}/media'), headers: headers, body: body);
print(response.body);
}
Uploading as Form-data
uploadFormData(String path) async {
var headers = {
'Authorization': 'Bearer EAAGtvNhUHUIBANf5KvyxnZCUKcRn3jTJgPZBR2AbbVhZBZBO7GjoDCnS26FQT6Nr6qdRV993ZCJEbGwiqZCdQ7TZBJX8S6KXQdOTgmSf9ue7GCEN1IL3yqfAUEIN1bw0nyvptHeZBFCsdfwpxZAcS1ZCbCdmqArZC81orVbYRkzJy1h7ChOAygmrchfFtJAapykZAadruFqOWwcVvtudMezse94zENBNVZA0k7pAZD',
};
var request = MultipartRequest('POST', Uri.parse('https://graph.facebook.com/v14.0/106822672107550/media'));
request.fields.addAll({
'messaging_product': 'whatsapp'
});
request.files.add(await MultipartFile.fromPath('file', path));
request.headers.addAll(headers);
Response response = await Response.fromStream(await request.send());
print(response.body);
}
Error for JSON:
flutter: {"error":{"message":"An unknown error has occurred.","type":"OAuthException","code":1,"fbtrace_id":"AE72st2KT8wJFQ_wYvrcJY6"}}
Error for Form-Data:
flutter: {"error":{"message":"(#100) Param file must be a file with one of the following types: audio\/aac, audio\/mp4, audio\/mpeg, audio\/amr, audio\/ogg, audio\/opus, application\/vnd.ms-powerpoint, application\/msword, application\/vnd.openxmlformats-officedocument.wordprocessingml.document, application\/vnd.openxmlformats-officedocument.presentationml.presentation, application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application\/pdf, text\/plain, application\/vnd.ms-excel, image\/jpeg, image\/png, image\/webp, video\/mp4, video\/3gpp. Received file of type 'application\/octet-stream'.","type":"OAuthException","code":100,"fbtrace_id":"AfsxKl38CW7hUF_ixMzNha9"}}
The problem was with the Mime-type of the file. The Multi-Part file class needed the mime-type of the file to be declared while uploading the file, or the file was automatically being uploaded as an octlet-stream. The code to the working request is posted below.
var request = http.MultipartRequest('POST', Uri.parse('https://graph.facebook.com/v14.0/${variables.phoneNumberId}/media'));
request.headers.addAll({
'Authorization': variables.authorizationToken,
'Content-Type': 'multipart/form-data'
});
request.fields.addAll({
'messaging_product': 'whatsapp',
'type': 'application/pdf'
});
// The MIME type of the image or file
const mimeType = 'application/pdf';
// Open the image file
var file = File(path);
// Create a MultipartFile from the File object
final multipartFile = await http.MultipartFile.fromPath(
'file',
file.path,
contentType: MediaType.parse(mimeType),
);
// Create a request body containing the multipart file
request.files.add(multipartFile);
// Send the request
final response = await request.send();
// Check the response status code
if (response.statusCode == 200) {
String body = await response.stream.bytesToString();
var json = jsonDecode(body);
print(json['id']);
} else {
print(response.reasonPhrase);
}

Get json respons from http get respons?

Please tell me how to get json response?
I get base4 by example:
// Using Node.js 14.x +
// use "lib" package from npm
const lib = require('lib')({token: null /* link an account to create an auth token */});
// make API request
let result = await lib.http.request['#1.1.6'].get({
url: null // required
});
https://autocode.com/lib/http/request/#get
Using axios package will be easier. It's default response type is json.
const axios = require('axios');
let result = await axios.get('your_url')
});

How to Http Post with Json Body on Flutter

I am trying to get data from API. I need to pass value from the body, in postman without a header: application/JSON data is not displayed.
final response = await http.post(
"http://192.168.10.25:8080/Login/validateusername",
body: {"username": "user#PYA"},
headers: {'Content-Type': 'application/json'},
);
Error Message:
E/flutter (28851): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (28851): Bad state: Cannot set the body fields of a Request with content-type "application/json".
Add the content type application/json
Future<String> apiRequest(String url, Map jsonMap) async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
// todo - you should check the response.statusCode
String reply = await response.transform(utf8.decoder).join();
httpClient.close();
return reply;
}
Simply encode body to json object when using content-type "application/json"
http.Response response = await http.post( uri , headers: headers, body: JsonEncoder().convert(body));
Another simple way is as bellow
import 'package:http/http.dart' as http;
String body = json.encode({
'foo': 'bar',
'complex_foo' : {
'name' : 'test'
}
});
http.Response response = await http.post(
url: 'https://example.com',
headers: {"Content-Type": "application/json"},
body: body,
);
use the http dart package
var data = {username:"username",password:"password"};
http.Response response = await http.post(
"yourApiroute",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: {"username": data.phone, "password": data.password});
var json = jsonCodec.encode(data);
print("json=$json");
var url = "http:yourAPIrouter.com/etc";
var response = await http.post(
url,
headers:{ "Accept": "application/json" } ,
body: { "json": '$json'},
encoding: Encoding.getByName("utf-8")
);
and dont forget add the key "json" in postman
I am doing almost the same. However, I tried to avoid doing back-end, like in your case. I just did a minimal php request so that I would not waste or patience learning what is needed to develop a user management controller.
However, I faced several limitations and problems that Flutter alone can't solve. After some denial, I gave a try. Lumen, a light version of the Laravel Framework, some tutorials and some past experience, I eventually realized that the API should carry most of the authentication, and not the application itself. I digressed.
In my case, the code of the fuction to a http post is:
Future<Post> createPost() async {
final url = "http://localhost:8000/api/login";
Map<String, String> body = {
'user': user.text,
'pass': pass.text,
};
await http.post(url, body: body);
print(body);
return http.;
}
I first convert it into a map. I prefer this method over parsing json, because down the line, if I need to add more variables, I just make the map bigger.
I just have a question: What does your http://192.168.10.25:8080/Login/validateusername look like? I think that there is no need to specify the type of information that your body parses.

Resources