Baselinker Api Call from Google App Script - api

I struggle to connect to third party api (Baselinker Api) from my App Script.
function makeHttpPostRequestWithAppsScript() {
const url = "https://api.baselinker.com/connector.php?method=getOrders";
const response = UrlFetchApp.fetch(url, {
"method": "POST",
"headers": {
"X-BLToken": "xxxx",
"Content-Type": "application/json"
},
"muteHttpExceptions": true,
"followRedirects": true,
"validateHttpsCertificates": true,
"contentType": "application/json",
"payload": JSON.stringify({"order_id":"5131"})
});
Logger.log("Response code is %s", response.getResponseCode());
Logger.log(response.getContentText());
}
Any idea where am I going wrong? Of Course token is ok.
I am getting error like that :
Informacje {"status":"ERROR","error_code":"ERROR_UNKNOWN_METHOD","error_message":"An empty or unknown method has been used"}
That is what it should look like in PHP
<?php
$methodParams = '{
"date_confirmed_from": 1407341754,
"get_unconfirmed_orders": false
}';
$apiParams = [
"method" => "getOrders",
"parameters" => $methodParams
];
$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: xxx"]);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$response = curl_exec($curl);
Thanks

I believe your goal is as follows.
You want to convert the following PHP script to Google Apps Script.
<?php
$methodParams = '{
"date_confirmed_from": 1407341754,
"get_unconfirmed_orders": false
}';
$apiParams = [
"method" => "getOrders",
"parameters" => $methodParams
];
$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: xxx"]);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$response = curl_exec($curl);
When I saw your PHP script, it seems that the data of $methodParams is sent as the form data. So, in this case, how about the following modification?
Modified script:
function makeHttpPostRequestWithAppsScript() {
const url = "https://api.baselinker.com/connector.php";
const response = UrlFetchApp.fetch(url, {
"method": "POST",
"headers": { "X-BLToken": "xxxx" },
"muteHttpExceptions": true,
"payload": {
"method": "getOrders",
"parameters": JSON.stringify({ "order_id": "5131" }),
}
});
Logger.log("Response code is %s", response.getResponseCode());
Logger.log(response.getContentText());
}
Note:
When I saw your sample PHP script and your Google Apps Script, in your PHP script, {"date_confirmed_from": 1407341754,"get_unconfirmed_orders": false} is used as the value of parameters. But, in your Google Apps Script, {"order_id":"5131"} is used. If your sample PHP script works fine and when the above modified Google Apps Script didn't work, please test for replacing {"order_id":"5131"} with {"date_confirmed_from": 1407341754,"get_unconfirmed_orders": false} and test it again.
I thought that if {"date_confirmed_from": 1407341754,"get_unconfirmed_orders": false} is used to the above Google Apps Script, it seems that the request is the same with your PHP script. So, if an error occurs, please check each value and your token, again.
This modified script supposes that your sample PHP script works. Please be careful about this.
Reference:
fetch(url, params)

Related

How to send POST requests to the VK API

I have a VK bot that needs to send long messages. They do not fit in URI, if I try to send a GET request, API returns URI too long error. Sending requests with Content-Type: application/json and passing json as body doesn't work, neither is it possible to send a Content-Type: multipart/form-data request. Is it possible to send a POST request to VK API?
It is possible to send a POST request using Content-Type: application/x-www-form-urlencoded;charset=UTF-8. Also it's recommended to send access_token and v parameters in url and the rest in the body.
Example in JavaScript:
const TOKEN = '...'
const VERSION = '5.126'
fetch(`https://api.vk.com/method/messages.send?access_token=${TOKEN}&v=${VERSION}`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
random_id: Math.round(Math.random()*100000),
peer_id: 185014513,
message: 'Hello world'
}).toString()
})
.then((res) => res.json())
.then(console.log)
In PHP:
const TOKEN = '...';
const VERSION = '5.126';
$query = http_build_query([
'access_token' => TOKEN,
'v' => VERSION,
]);
$body = http_build_query([
'random_id' => mt_rand(0, 100000),
'message' => 'Hello world',
'peer_id' => 185014513,
]);
$url = "https://api.vk.com/method/messages.send?$query";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER , [
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
]);
$response = curl_exec($curl);
curl_close($curl);
$json = json_decode($response, true);
Note that you cannot send messages over 4096 characters long

405 error with JIRA REST API using node js

I am trying to create an automated JIRA ticket using the REST API but I keep getting a 405 error.
I am using the examples here: https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/
Also, when I visit the post URL directly I do not get any errors so I doubt it is a server issue. Any ideas?
var Client = require('node-rest-client').Client;
client = new Client();
// Provide user credentials, which will be used to log in to Jira.
var loginArgs = {
data: {
"username": "user",
"password": "pass"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("https://jira.mydomain.com/rest/auth/1/session", loginArgs, function(data, response) {
if (response.statusCode == 200) {
//console.log('succesfully logged in, session:', data.session);
var session = data.session;
// Get the session information and store it in a cookie in the header
var args = {
headers: {
// Set the cookie from the session information
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
// I copied this from the tutorial
"fields": {
"project": {
"key": "REQ"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Request"
}
}
}
};
// Make the request return the search results, passing the header information including the cookie.
client.post("https://jira.mydomain.com/rest/api/2/issue/createmeta", args, function(searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
I am expecting the Jira ticket of type REQ to be created with the details I added in the fields section.
I believe you are using the incorrect REST API; what you're currently doing is doing a POST to Get create issue meta which requires a GET method, hence, you're getting a 405. If you want to create an issue, kindly use Create issue (POST /rest/api/2/issue) instead.

Receiving a BAD REQUEST (400) response with Basecamp API 3 from a Node Express application

The same request including the access token is working with CURL and Postman.
The code from Postman (masked credentials and ids) is included.
var http = require("https");
var options = {
"method": "GET",
"hostname": [
"3",
"basecampapi",
"com"
],
"path": [
"<MASKED ACCOUNT ID>",
"my",
"profile.json"
],
"headers": {
"Authorization": "Bearer <MASKED AUTH TOKEN>",
"Cache-Control": "no-cache",
"Postman-Token": "92fc7993-57aa-47f7-aaae-44925dd37f3e"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();
Use NodeJS Request instead of NodeJS Native when creating code from a Postman request.

Laravel - Send api_token within the header

I'm building an API for Laravel and I want to send the api_token within the header instead of the form post. Is this something that is already built in or would I have to go the route of figuring out how to create my own auth driver?
After struggling a little with this myself I got it working.
You need to first follow this little tutorial on how to use the api_token for your laravel API:
https://gistlog.co/JacobBennett/090369fbab0b31130b51
Then once you have the api_token in the users table etc you can now pass this in the header of each request.
My laravel is using the Vueify templates, ie I have under /components/Comment.vue etc files.
First step is to pass the users api_token to the Vue Template by passing a property through the component definition in your blade template:
<comments id_token="{{ access()->user()->api_token }}"></comments>
Then ensure in your .vue file that you accept the property by adding it to the "props":
export default {
data: function() {
return {
edit: false,
list: [],
comment: {
id: '',
name: '',
body: ''
}
};
},
props: ['id_token'],
created: function() {
Vue.http.headers.common['Authorization'] = 'Bearer ' + this.id_token;
this.fetchCommentList();
},
Notice above that I also added the token to the common headers in order to have it go through each request used in all the methods further down.
Vue.http.headers.common['Authorization'] = 'Bearer ' + this.id_token;
If you are consuming your API, you don't need to create an auth driver, you need to make requests to your API endpoints. Choose the method you prefer, and make requests, don't think as the same way when you use the auth driver at a webpage.
This is an example how send the $token through the headers. With cURL and Guzzle
$data = [
'value1' => 'value1',
'value2' => 'value2'
];
With CURL
$headers = [
'Authorization: Bearer '.$token
];
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'http://api.domain.com/endpoint');
curl_setopt($ch2, CURLOPT_POST, 1);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch2);
curl_close ($ch2);
With Guzzle
$headers = [
'Authorization' => 'Bearer '.$token
];
$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'http://api.domain.com/endpoint',[
'form_params' => $data,
'headers' => $headers,
]);
I hope this helps!

How to get the response after a POST request in CasperJS

I have this very simple code to read the response from a server endpoint after a post request. Actually I'm saving a data to a database and wait for a response before going to next step
casper.open('http://example.com/ajax.php, {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
});
on ajax.php file I'm trying to echo the POST request in a simple way.
this will let me know easily if I'm getting the right response from the server.
echo json_encode($_POST);
I tried these snippets but I'm unable to get the response.
casper.on('page.resource.received', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('http.status.200', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('resource.received', function(resp) {
this.echo(JSON.stringify(resp, null, 4));
});
I've been facing the same problem POSTing a query to ElasticSearch and I could not retrieve the results.
As far as I can understand if you want to retrieve the data echoed by your script the solution could be this:
this.echo(this.page.content);
or
this.echo(this.page.plainText);
in your function.
For example (my case with ElasticSearch):
/*
* SOME VAR DEFINITIONS HERE
*/
casper.start();
casper.then( function() {
// the next var is very specific to ElasticSearch
var elasticQuery = JSON.stringify (
{
'size' : 20,
'query' : {
'filtered' : {
'filter' : { 'term' : { 'locked' : false } }
}
},
'sort': { 'lastScrapeTime': { 'order': 'asc' } }
}
);
var elasticRequest = {
method: 'POST',
data: elasticQuery
}
this.thenOpen( <<YOUR URL>>, elasticRequest, function (response) {
// dump response header
require('utils').dump(response);
// echo response body
this.echo(this.page.content);
// echo response body with no tags added (useful for JSON)
this.echo(this.page.plainText);
});
}
);
casper.run();
As Roberto points out. You can use this.page.content to show the response. But you need to add the function(response) in your script. For example:
casper.open('http://example.com/ajax.php', {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
}, function(response){
if(response.status == 200){
require('utils').dump(this.page.content);
}
});
If you want to unit test a REST API, CasperJS is not necessarily the right tool.
CasperJS allows to observe a web browser which is running a web page.
So a more typical approach would be to use CasperJS to load a page that would call your REST API and you would assert the page behavior is correct (assuming the page would make something observable according the AJAX call response).