Format of google app engine API url - javascript

I created a google App engine project locally. Added a simple "Place" API and started the engine. I noticed that the server is waiting on http://localhost:8888/_ah/api base URL.
Now, I want to use the google javascript client API to call my API (I am assuming that is possible). So I created a simple local website and created a simple HTML/javascript page. Then I loaded the google javascript client library and executed.
Here is my page
<html>
<head>
<script>
function load() {
console.log("API client loaded");
var ROOT = 'http://localhost:8888/_ah/api';
gapi.client.load('getPlace', 'v1', function() {
console.log("API called");
}, ROOT);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
</head>
<body>
<div> Hello </div>
</body>
</html>
Now, when I run it, I get a 404 error. Then I checked the URL that the browser places. It looks like this:
http://<local>:8888/_ah/api/discovery/v1/apis/getPlace/v1/rpc?fields=methods%2F*%2Fid&pp=0
A few questions:
What I am doing should work correct ? (local app engine + javascript
library)
What is the expected URL for app engine generated API ? (what is the "discovery" in the URL?)
What is the "rpc" at the end ? I am hoping to create REST API

Related

Cannot log values using Logger in google app script

Here is my HTML code, from where I call the function loadClient when load button is clicked,
//LOAD CLIENT BUTTON`
document.getElementById("load_button").addEventListener('click',function(){
google.script.run.loadClient();
});
here is the respective function in the code.gs file
//function02-loadClient
function loadClient() {
eval(UrlFetchApp.fetch('https://apis.google.com/js/api.js').getContentText());
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/webmasters/v3/rest")
.then(function() { Logger.log("GAPI client loaded for API"); },
function() { Logger.log("Error loading GAPI client for API" ); });
}
When you call google.script.run in the client-side environment, you're requesting execution of a server side Apps Script function.
Your implementation of loadClient() doesn't make sense in the context of server-side Apps Script execution.
Here's a full, simple example of successfully triggering a Logger.log() call on the server-side by way of a client side button click:
client.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<script>
function registerListener() {
document.getElementById('callServerFunction').addEventListener('click', function() {
google.script.run
.withSuccessHandler(function() {
alert("Successfully called server function.");
})
.withFailureHandler(function() {
alert("Failed to call server function.");
})
.serverFunction();
});
}
</script>
<body onload="registerListener()">
<button id="callServerFunction">Call Server Side Function</button>
</body>
</html>
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('client');
}
function serverFunction() {
Logger.log("Server function called.");
}
Server side logging results after the button is clicked
[18-06-10 13:48:20:359 PDT] Server function called.
Regarding the Javascript Google API Client Libraries (i.e. https://apis.google.com/js/api.js), that's not meant to be used in the Apps Script server side context. The whole point of Apps Script is that there is a laundry list of services ready to use immediately without any setup. In addition to not being compatible, trying to load the client-side JS libraries in the server side Apps Script context is simply redundant.
Similarly, trying to use the client-side JS libraries in client-side Apps Script code doesn't make too much sense either, as you have the full set of server-side functionality available via google.script.run.
"trying to load the client-side JS libraries in the server side Apps Script context is simply redundant."
...is not redundant when G. fails to provide/implement/disclose a client-side method unimplemented on the server side; e.g.:
Drive.files.emptyTrash()
https://developers.google.com/drive/api/v2/reference/files/delete?hl=en#javascript
empty trash is simply nowhere to be found among GA Apps Script server-side js calls references urls
https://developers.google.com/apps-script/reference/drive
https://developers.google.com/apps-script/reference/drive#methods
https://developers.google.com/apps-script/advanced/drive
The sought-after capability is NOT THE SAME as file.setTrashed(true) read the necessity as: empty the trash, not 'put a file in the trash', 'mark a file as trashed'; nor is any 'interactive' option viable for e.g. for deleting thousands of files directly or via the trash.
it's impossible with Drive's GAS to permanently delete a file directly
semantics of 'delete' Google admits existence of in Google's Drive client side APIs:
https://developers.google.com/drive/api/v2/reference/files/delete?hl=en
which can't be called from, and for which there is no equivalent, on the server side !
no english phrase I can conceive of adequately captures the implications, otherwise, and economic, of this glaring omission
But perhaps someone can provide the (?undocumented) GAS Apps Script call counterexample

How do I get access to a Javascript client SDK generated by swagger in a web page?

I am working on a REST API for a web-service. We have chosen to create a formal specification of the API using SwaggerHub. Now I've come to the next step, using the generated Javascript client SDK to talk to the web-service in a web page...
The documentation provided by SwaggerHub is focused on using the generated client SDK in node.js, which seems to behave slightly different from a browser.
I've collected the full SDK in a single bundle using "browserify":
browserify index.js > bundle.js
Then I've added a reference to the bundle to the HTML:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="bundle.js"></script>
This seems to work, although I'm unsure exactly how I can test it at this stage.
Then I try to interact with the API declared in the bundle, as soon as the document is ready (this is - except for the encapsulation and the alert() calls - taken from the documentation provided in the generated client SDK):
<script type="text/javascript">
$(document).ready(function() {
alert('Document ready');
var WebApiForStandard = require('web_api_for_standard');
alert('API ready');
var defaultClient = WebApiForStandard.ApiClient.instance;
[...]
I get the "Document ready" message, and I don't get the "API ready" message. When I check the browser console (in Firefox), it shows:
ReferenceError: require is not defined
I assume that this is because require() is something from node.js.
... but I've already asked the browser to load the API bundle, so maybe that isn't a problem. Next try is to omit the require() call:
<script type="text/javascript">
$(document).ready(function() {
alert('Document ready');
var defaultClient = WebApiForStandard.ApiClient.instance;
alert('Client ready');
[...]
But no. Now the browser console reports:
ReferenceError: WebApiForStandard not defined
What do I do then?

Having trouble with requiring AWS in Javascript

I'm trying to implement DynamoDB in a Javascript file. I tried out multiple tutorials in succession to no avail. All I'm trying to do is make a query from within my Javascript code (which is being run in an HTML page). Unfortunately, my code doesn't even get up to that. It throws me errors when I try to require AWS-SDK. I installed aws-sdk with Node.js. After being confused by multiple tutorials, I ended up with the following code:
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://requirejs.org/docs/release/2.2.0/r.js"></script>
<script src="boom.js"></script>
</head>
<body></body>
</html>
JavaScript (boom.js):
require(['aws-sdk'], function (foo) {
var CONF = require("./super_secure_conf.json");
var AWS = require("aws-sdk");
function init(){
AWS.config = new AWS.Config({
access_key_id: CONF.AWS_ACCESS_KEY_ID,
secretAccessKey: CONF.AWS_SECRET_ACCESS_KEY,
region: "us-east-1"
});
DynamoDB = new AWS.DynamoDB();
}
});
The file "super_secret_conf.json" is a JSON file containing my AWS Credentials. I tried storing the credentials at ~/.aws/credentials previously, but that wasn't working. (Should credentials be a folder or file? I had tried saving my credentials in a blank file – without any extension. Just thought I'd mention.) So I followed another tutorial, which said to use the JSON method (and I am aware that it is very insecure) which is what you see here. I still get an error though:
Error: Module name "super_secure_conf.json" has not been loaded yet for context: _. Use require([])
All and any help is greatly appreciated.
You are requiring AWS twice, calling it foo the first time. And you aren't waiting for the callback from your config.json require call (or even passing it a callback function). I believe your code needs to change to look like this:
require(['aws-sdk', "./super_secure_conf.json"], function (AWS, CONF) {
function init(){
AWS.config = new AWS.Config({
access_key_id: CONF.AWS_ACCESS_KEY_ID,
secretAccessKey: CONF.AWS_SECRET_ACCESS_KEY,
region: "us-east-1"
});
DynamoDB = new AWS.DynamoDB();
}
});
However I'm not sure if the path "./super_secure_conf.json" is actually going to work. That looks like a path you would use for loading a file in a server-side NodeJS application, not a browser-side JavaScript application.
Note that the reason you have to load your config this way is because the ~/.aws/credentials method of loading an AWS config is not going to work for a JavaScript app running in a browser. I think you've been reading NodeJS tutorials which aren't going to translate perfectly to JavaScript in the browser. I would highly recommend you start by looking through the documentation for AWS SDK for JavaScript in the Browser, and in particular read the page on Configuring the SDK in the Browser.

How to solve Facebook Error 191 without having a website?

Me an my team are currently working on a software project at university and my present task is to bind our desktop javafx application with Facebook.
Basically I have an fxml method in a controller that is called when the user hits a "Share" button in my GUI. In the method I'd like to simply open up my .html file using a WebView:
#FXML
public void shareFacebookClicked() throws Exception{
// Setting up the webview
WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
webEngine.setJavaScriptEnabled(true);
// Read the html file and let the web engine load it.
File file = new File(getClass().getClassLoader().getResource("facebook.html").toURI().getPath());
webEngine.load(file.toURI().toURL().toString());
Stage stage = new Stage();
stage.initOwner(this.stage);
stage.setScene(new Scene(webView, 1000, 800));
stage.show();
}
There is no problem with it, my "facebook.html" file is loaded and displayed correctly (well, almost correctly) in a web view.
The actual problem is that I'm constantly getting the 191 Facebook error saying that the link is not owned by the application. Since there are tons of posts and questions on this around the Internet (and yes I checked and read all of them) here are the things that I'm already aware of:
I registered my application on the Facebook Developer site. I know about the AppID and Secret
I know that this error mainly comes from the fact that people forget to set their website URL and domain in the Settings. The problem is that I don't have a website. I just have a simple .html file which I'd like to use in a web view inside of javafx. However, I tried all possible combinations advised on stackoverflow, facebook help centre and other forums which include: Setting website URL to http://localhost/, domain to localhost, enabling Embedded browser OAuth Login, setting the redirect URI to localhost too, etc.
I assume that my goal could be achieved by using RESTfb, Facebook4j or Graph API. When I tried those I had to stop because I faced problems with the user authentication plus I thought this current option would be the easiest way (considering this feature has LOW-priority in our software).
None of this solved my problem therefore I've given up researching the answer and decided to post my very own personal question.
In my opinion there must be some error in the .html file and/or I completely misunderstand something in the way this works. The .html file:
<html>
<head>
<title> Share on Facebook </title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js"></script>
<script src="https://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#shareonfacebook').click(function (e) {
FB.ui({
appId: 'MY_APP_ID',
display: "popup",
method: "feed",
name: "Test",
link:"",
caption:"Test",
description: "Test",
});
});
});
</script>
</head>
<body>
<div id="fb-root"></div>
<button id="shareonfacebook" >Share</button>
<script>
FB.init({
appId : 'MY_APP_ID'
});
</script>
</body>
</html>
Partially I have this code from a tutorial site. Theoretically it should work. All I want is a dialog to come up where the user can publish the results of the workout he/she completed using our software. Currently when the .html file is opened up there is a simple button to click. This and all the "Test" strings inside of the javascript are only for testing. I just want to achieve that I can post something on my wall. The next step would be of course to somehow set the posting text dynamically etc.
Please tell me what I'm doing wrong or how I should approach the whole thing. Like I said, the task is minimal therefore it shouldn't be that difficult but I've been sitting in front of my laptop for 2 days without any success. I'm ready to post more code or give more information if it's needed.
Thank you for the help in advance!

How do I get data from the Bitfinex web API using javascript

Here is a link to their API documentation
I would like to practice web programming by creating a bitcoin price ticker from scratch. My plan is to serve a script that makes api calls to exchanges to display the data. This will mean I only have to serve the script, not handle the data server-side.
I know that part of programming is learning from documentation, but the docs from bitfinex are very sparse and I couldn't find a tutorial.
I created an index.html to test my javascript. It returns a console error:
XMLHttpRequest cannot load https://api.bitfinex.com/v1/pubticker/:last_price.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
Here is the full index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>
<script>
$.getJSON("https://api.bitfinex.com/v1/pubticker/:last_price",
function(data, status){
alert("price: "+data +" status: " + status);
}
)
</script>
Thank you stack exchange
</body>
You can't — at least, not with Javascript. That API is not configured to allow calls from Javascript running on other web sites. You will need to call this API from a script running on your web server.
(Also, for what it's worth, the :symbol token in the URL is supposed to be replaced with the symbol of the ticker you're trying to look up, e.g. /v1/pubticker/BTCUSD for BTC/USD exchange prices.)
If you run a webserver with SSL on it (as Duskwuff said, "You will need to call this API from a script running on your web server.") then you can deploy the following file to it:
<?php
$func = $_GET['fn'];
if(in_array($func,array('getBfx')))
{
$func();
}
function getBfx()
{
$a = $_GET['api'];
echo "objData = ".file_get_contents($a);
}
?>
Then you can include the script from the URL to which you deployed it, with ?func=getBfx&api=https://api.bitfinex.com/v1{Whatever} tacked onto the end of it. I didn't have to escape that URL, but you might.

Categories

Resources