Import CSV from API output to google - api

I have absolutly no idea of what I'm doing but I'm trying to import CSV data from API output into a google sheets.
The data I want to import are bookings data, aleady generated as a csv file and I simply need to import all the data the first time and then update it (no need to re-import all the datas from last year)
The API URL is:
https://www.beds24.com/api/csv/getbookingscsv
I need however to enter my username and my password and if necessary a date range.
So in my head it would be:
One script for the year booking import
username XXXXX
password •••••
datefrom
dateto
One script for the day booking import using the date range
username XXXXX
password •••••
datefrom 2019-09-29
dateto 2019-09-29
The first look I took using googlescript I found out that I would probably need something like this:
function importCSV() {
var var bookings = beds24api.beds24GetBookings(prop_key, data_option);
var res = UrlFetchApp.fetch("https://www.beds24.com/api/csv/getbookingscsv");
var content = res.getContentText();
var authentication = {
'authentication' : {
'username' : XXXXX,
'password' : •••••
};
};
}
function beds24GetBookingsCSV(username, password, data_option){
return beds24JsonApi('https://www.beds24.com/api/csv/getbookingscsv',username, password, data_option);
};
return {
beds24GetBookings: beds24GetBookingsCSV,
};
}
Lot of you gonna get bleding eyes from this code but if I could get some help acheiving this that would be awesome!

I have no experience with beds24 nor do I wish to. But if you look here you will find an example of UrlFetchApp.fetch(url, options);. I believe that you'll need to include your authentication data into the options object or include them as elements of the querystring portion of the url. Look to see in beds 24 has a Google Apps Script example or possibly a Javascript example.

String url = "https://www.beds24.com/api/csv/getbookingscsv";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
String params = "username=XXX&password=YYY";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println(response.toString());
# Function to get data from Beds24 API
getBeds24Data <-function(username = property_mgmt$username,
password = property_mgmt$password,
datefrom = "2019-01-01",
dateto = "2019-12-30"){
url <- "https://www.beds24.com/api/csv/getbookingscsv"
response <- httr::POST(url=url, body = list("username" = username,
"password"=password,
datefrom = datefrom,
dateto = dateto))
beds24Data <- httr::content(response,type='text/csv',col_names=T,col_types=NULL)
return(beds24Data)
}

Related

Not able to upload json data to Bigquery tables using c#

I am trying to upload json data to one of the table created under the dataset in Bigquery but fails with "Google.GoogleApiException: 'Google.Apis.Requests.RequestError
Not found: Table currency-342912:sampleDataset.currencyTable [404]"
Service account is created with roles BigQuery.Admin/DataEditor/DataOwner/DataViewer.
The roles are also applied to the table also.
Below is the snippet
public static void LoadTableGcsJson(string projectId = "currency-342912", string datasetId = "sampleDataset", string tableId= "currencyTable ")
{
//Read the Serviceaccount key json file
string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName + "\\" + "currency-342912-ae9b22f23a36.json";
GoogleCredential credential = GoogleCredential.FromFile(dir);
string toFileName = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName + "\\" + "sample.json";
BigQueryClient client = BigQueryClient.Create(projectId,credential);
var dataset = client.GetDataset(datasetId);
using (FileStream stream = File.Open(toFileName, FileMode.Open))
{
// Create and run job
BigQueryJob loadJob = client.UploadJson(datasetId, tableId, null, stream); //This throws error
loadJob.PollUntilCompleted();
}
}
Permissions for the table, using the service account "sampleservicenew" from the screenshot
Any leads on this , much appreciated
Your issue might reside in your user credentials. Please follow this steps to check your code:
Please check if the user you are using to execute your application have access to the table you want to insert data.
If your json tags matchs your table columns.
If you json inputs are correct ( table name, dataset name ).
Use a dummy table to perform a quick test of your credentials and data integrity.
These steps will help you identifying what could be missing on your side. I perform the following operations to reproduce your case:
I created a table on BigQuery based on the values of your json data:
create or replace table `projectid.datasetid.tableid` (
IsFee BOOL,
BlockDateTime timestamp,
Address STRING,
BlockHeight INT64,
Type STRING,
Value INT64
);
Created a .json file with your test data
{"IsFee":false,"BlockDateTime":"2018-09-11T00:12:14Z","Address":"tz3UoffC7FG7zfpmvmjUmUeAaHvzdcUvAj6r","BlockHeight":98304,"Type":"OUT","Value":1}
{"IsFee":false,"BlockDateTime":"2018-09-11T00:12:14Z","Address":"tz2KuCcKSyMzs8wRJXzjqoHgojPkSUem8ZBS","BlockHeight":98304,"Type":"IN","Value":18}
Build & Run below code.
using System;
using Google.Cloud.BigQuery.V2;
using Google.Apis.Auth.OAuth2;
using System.IO;
namespace stackoverflow
{
class Program
{
static void Main(string[] args)
{
String projectid = "projectid";
String datasetid = "datasetid";
String tableid = "tableid";
String safilepath ="credentials.json";
var credentials = GoogleCredential.FromFile(safilepath);
BigQueryClient client = BigQueryClient.Create(projectid,credentials);
using (FileStream stream = File.Open("data.json", FileMode.Open))
{
BigQueryJob loadJob = client.UploadJson(datasetid, tableid, null, stream);
loadJob.PollUntilCompleted();
}
}
}
}
output
Row
IsFee
BlockDateTime
Address
BlockHeight
Type
value
1
false
2018-09-11 00:12:14 UTC
tz3UoffC7FG7zfpmvmjUmUeAaHvzdcUvAj6r
98304
OUT
1
2
false
2018-09-11 00:12:14 UTC
tz2KuCcKSyMzs8wRJXzjqoHgojPkSUem8ZBS
98304
IN
18
Note: You can use above code to perform your quick tests of your credentials and the integrity of the data to insert.
I also make use of the following documentation:
Load Credentials from a file
Google.Cloud.BigQuery.V2
Load Json data into a new table

Sending sms to multiple phonenumbers using mysms API

I'm trying to send sms using mysms API. I am able to send to single number using following example:
Example: https://api.mysms.com/json/message/send?api_key=xxxxx&msisdn=xxx&password=xxx&recipient=436761234567&message=Hi
How can I send to multiple number using above example?
I came up with this code:
function sendSMS() {
var apikey = "your api_key";
var mno = 40123123456; // msisdn = your number without +sign in from
var pwd = "yourpassword";
// var no = 40123123456; // single number & replace this with a real one
var grp = [40123123456,40123123456,40123123456]; // multiple numbers / let's call it a group & just replace those with your actual testing numbers
var msg = "Hi!%0aThis is a test message!%0aThis is another row.%0a:D"; // Use %0a to insert a new row in your message
for ( var i in grp ) {
var smsurl = "https://api.mysms.com/json/message/send?api_key="+apikey+"&msisdn="+mno+"&password="+pwd+"&recipient="+grp[i]+"&message="+msg+"";
var xhttp = new XMLHttpRequest();
xhttp.open("GET", smsurl, true);
xhttp.send();
console.log(smsurl);
}
}
Now just make the call:
sendSMS();
This code is javascript and I hope will answer your question well. Also it was tested and proven that is working. There is always room for improvements.

sending string parameter in action=track leanplum Rest Api not working

I want to send string parameters in Leanplum api using action script
Eg param:{"Element":"Hi"}
var request:URLRequest = new URLRequest("https://www.leanplum.com/api");
request.method = URLRequestMethod.GET;
var variables:URLVariables = urlVariables;
variables.userId = userId;
variables.event = eventName;
var params:Object = new Object();
params.Element = "Hi";
var paramStr:String = JSON.stringify(params);
variables.params = paramStr;
variables.appId = appId;
variables.clientKey = clientKeyProduction;
variables.apiVersion = apiVersion;
variables.action = "track";
variables.versionName = AppInfo.getInstance().appVersion;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, function(e:Event):void {
trace(e.target.data);
});
loader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void {
trace(e.target.data);
});
loader.load(request);
This is actual Request (App ID and ClientKey are dummy):
https://www.leanplum.com/api?clientKey=V42fKaJaBuE&userId=1010&params={"Element":"Ur"}&appId=HEVdDlXiBVLwk&event=Element_Opened&action=track&versionName=2.3.0&apiVersion=1.0.6&info=Lu
Encoded Request:
https://www.leanplum.com%2Fapi%3FclientKey%3DV42fKaJaBuE%26userId%3D1010%26params%3D%7B%22Element%22%3A%22Ur%22
%7D%26appId%3DHEVdDlXiBVLwk%26event%3DElement_Opened%26action%3Dtrack%26versionName%3D2.3.0%26apiVersion%3D1.0.6%26info%3DLu
if I run above request in any rest client I get the same status success : true .
I am getting the response {"response": [{"success": true}]} but I can't find the parameters with value string in Leanplum dashboard, its listing parameter name but not the String Value for parameter.
If you apply some combination of filters then you can see values of parameter you sent to leanplum. like First select the occurrence of some event then apply Group by parameter then select parameter you want to see the data for.
Its a little different from flurry, Google analytics etc.

how to update a column in force.com explorer

SELECT Name, ProfileId, Id, Username FROM User this is the select query to retrive data in Force.com explorer
Now I wan't to update a column how can I do this? update key word it self not working here please give the solution for this.
thanks in advance
In Salesforce you not write to update query same as in SQL.
Please use update method to update column of an object.
More information and sample please read following documents.
https://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_update.htm
I found Solution it's working fine now, If any one haveing doubts ask me for Create,Update,Get functionalities
private void UpdateProfileId(string Id)
{
SforceService sfs = new SforceService();
var login = sfs.login(ConfigurationManager.AppSettings["username"],ConfigurationManager.AppSettings["password"]);
sfs.Url = login.serverUrl;
sfs.SessionHeaderValue = new SessionHeader();
sfs.SessionHeaderValue.sessionId = login.sessionId;
var userinfo = login.userInfo;
QueryResult qr = null;
sfs.QueryOptionsValue = new salesforce.QueryOptions();
User[] UpdateUser = new User[1];
User objuser = new User();
objuser.Id = Id;
objuser.ProfileId = "00e90000001CcTnAAK";
UpdateUser[0] = objuser;
try
{
SaveResult[] saveResults = sfs.update(UpdateUser);
foreach (SaveResult saveResult in saveResults)
{
if (saveResult.success)
{
Console.WriteLine("Successfully updated Account ID: " +saveResult.id);
}
}
}
}

Post values in URL are not set because of special characters in Web API

I'm trying to pass a string with special characters to your web api but is giving error.
Below the line where I pass the values ​​pro web api:
string listaParcelaSeparadoVirgula = null;
foreach (var item in listaParcelas)
{
listaParcelaSeparadoVirgula = listaParcelaSeparadoVirgula + ";;" + item;
}
var result = HttpUtility.UrlEncode(listaParcelaSeparadoVirgula);
var response = client.PostAsJsonAsync("api/LancamentoReceitaDespesa/AddLancamentoParcelar/" + result, lancamentoReceitaDespesa).Result;
the result is a string variable with values ​​separated by ";;". Below the contents of the string:
";;aaaaa 1/2||10/01/2014|100,00||;;aaaaa 2/2||10/02/2014|100,00||"
with UrlEncode:
"%3b%3baaaaa+1%2f2%7c%7c10%2f01%2f2014%7c100%2c00%7c%7c%3b%3baaaaa+2%2f2%7c%7c10%2f02%2f2014%7c100%2c00%7c%7c"
Error:
{"Error while copying content to a stream."}
How can I pass these values ​​pro web api?
Well you could try encode value with base64 since in url you could have special symbols
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(result);
var response = client.PostAsJsonAsync("api/LancamentoReceitaDespesa/AddLancamentoParcelar/" + System.Convert.ToBase64String(plainTextBytes), lancamentoReceitaDespesa).Result;
then in web
public void AddLancamentoParcelar(string base64EncodedData) {
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
var result = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
I am not sure if its the best solution but as you could have any symbol in url then its could be an solution.