<html>
<head>
<script>
function appendResults(text) {
var results = document.getElementById('results');
results.appendChild(document.createElement('P'));
results.appendChild(document.createTextNode(text));
}
function makeRequest() {
var request = gapi.client.urlshortener.url.get({
'shortUrl': 'http://goo.gl/fbsS'
});
request.then(function(response) {
appendResults(response.result.longUrl);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
}
function init() {
gapi.client.setApiKey('*My API key*');
gapi.client.load('urlshortener', 'v1').then(makeRequest);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
</head>
<body>
<div id="results"></div>
</body>
</html>
This is the sample code from getting started page to use Google Translate API here. I used it exactly as instructed, and I already changed the "API key" part with my API key. Can anyone tell me why this code doesn't work? Is there any other library that I need to import to this .html ?
How to get access to the Google Translate API? How to get an API Key?
1. Sign Up for Free RapidAPI Account:
To begin using the Google Translate API, you’ll first need to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.
RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.
2. Subscribe to Google Translate API:
Once signed in, log in to your RapidAPI account and access the API console. Click on the “Pricing” tab and opt-in for the basic subscription that gives you 50 free API calls to Google Translate API per day.
3. Test Your API Subscription:
Let’s test your Google Translate API subscription. Select the “POST Translate” endpoint within the API console. The default values of parameters indicate that we are going to translate the text “Hello, world!” to Spanish (with language code ‘es’). Trigger the API, and you should see the translated text in the API response (JSON format).
So, “Hello, world!” in Spanish translates to “Hola Mundo!”.
You can also check language translator javascript code for website
The referenced page provides an example of a Translation API call, whose core lines are:
// Executes an API request, and returns a Promise.
// The method name language.translations.list comes from the API discovery.
return gapi.client.language.translations.list({
q: 'hello world',
source: 'en',
target: 'de',
});
Your sample code does not seem to include an API call.
Related
i'm using the open weather map api in order to get information on the current weather and then integrate it with watson assistant (i used this as a reference for the watson assistant code) before deploying on the terminal. here's my code:
var city = "Seattle";
weather.setCity(city);
function processResponse(err, response){
if(err){
console.log(err);
return;
}
var endConversation = false;
if(response.intents[0]){
if(response.intents[0].intent=="CurrentWeather"){
weather.getDescription(function(err, desc){
weather.getTemperature(function(err, temp){
console.log("It is " + desc + " today with a temperature of " + temp + " degrees Celsius.");
)};
)};
}
else if(response.intents[0].intent=="end_conversation"){
console.log(response.output.text);
endConversation = true;
}
}
if(!endConversation){
var newMessageFromUser = prompt(">> ");
service.message({
workspace_id: workspace_id,
input: {
text: newMessageFromUser
},
context: response.context
},processResponse);
}
}
it works, but then the response looks like this:
>> what is the weather today in seattle
>>
It is few clouds today with a temperature of 29 degrees Celsius.
>> bye
['See ya!']
whenever i use any third party apis, instead of responding right after i enter the trigger keywords, the terminal asks me to input another entry (in the scenario above, i entered nothing) before responding. however, when i try to enter keywords related to intents whose responses are just retrieved right away from the watson assistant (as is with end_conversation), the terminal responds right away.
Is there a way for me to force the terminal to only ask once?
There are different ways to get around entering something before the actual response.
Take a look at client-based dialog actions. The key is to use the skip_user_input flag and check it within your application. Basically, it would indicate to your application that you need to process some data. The app would it send back to Watson Assistant to respond. There is also the server-based dialog action. In that case Watson Assistant is invoking an IBM Cloud Functions action. A tutorial using that approach is here, interfacing with a Db2 database.
Another technique is what I call replaced markers. You would have Watson Assistant returns an answer with placeholders. Your app would replace those markers.
Third, you are using JavaScript with asynchronous processing. It seems that your empty prompt is processed while you fetch the weather data. The IF for the weather is independent of the empty prompt. Try fixing that.
following Michal Bida's advice, I tried implementing the third party API in cloud function and it worked. simply created a php function using the php implementation of the openweather map api and followed the steps on how to create an action in php through this tutorial. for the implementation, i followed this tutorial on how to implement actions in watson assistant. it now works even when directly invoked from the chat bot at the side of the watson assistant.
an example of a response it returns will be:
{"weather":"It is raining today in Seattle with a temperature of 15 degrees Celsius"}
From what I understand, deploying a Google Script as a Google Execution API allows me to call each function from my script separately as and when I need it.
I have a webpage with some buttons and forms that I want to run the functions within my script on.
I have a Google Script with some (example) functionality:
function addPlayer(name,email,group) {
//name email group
var ss = SpreadsheetApp.openById(SHEET_ID); //Sheet belonging to me, script author.
var sheet = ss.getSheetByName("Players");
sheet.appendRow(new Date(),name,email,group);
}
function updatePlayer() {
//update player row with new data
//name email group
}
function anotherFunction() {
//store some data in another sheet within spreadsheet.
}
function listPlayers()
{
//return data from sheet
}
And a sample webpage which wants to run functions from that script:
function OnLoadCallback() { //on gapi load
gapi.client.setApiKey(API_KEY); //developer dashboard generated browser API key
// Create execution request.
var request = {
'function': 'addPlayer',
'parameters': [name,email,group],
'devMode': true
};
// Make the request.
var op = gapi.client.request({
'root': 'https://script.googleapis.com',
'path': 'v1/scripts/' + scriptId + ':run',
'method': 'POST',
'body': request
});
}
I get a 401 UNAUTHENTICATED error at the moment saying I do not have valid auth credentials.
Is it possible for this webpage to use the API without requiring each webpage visitor to oAuth (which doesn't make sense to me as it's not THEIR data/sheet I am trying to access but my own? I know if I deploy as web app I can set it to execute AS me, but is there any similar equivalent for the Execution API?
I chose to use execution script as I need to be able to run several different functions, and as a webapp my only option would be the doPost() which wouldn't let me differentiate adding to sheets/updating sheets/reading from sheets easily?
Am I missing something completely here? If this is entirely the wrong approach I would be super grateful if someone could point me in the right direction.
Thanks!
Based on this SO question, by adding SpreadsheetApp calls, you've modified the authentication scope required for your script. You need to update your scope to include Spreadsheets.
To use the API, you must supply a valid OAuth token that covers all the scopes used by the script. To find the correct scopes to include in the authentication token, open the project in the script editor, then select File > Project properties and click the Scopes tab.
Here is the link for the list of OAuth scope.
Check also this SO question for more information.
I am making a website for the first time. I am sorry for any dumb question but I really have no background. However, I am trying to learn.
I developed the website on Weebly (www.i2i.network) and I am trying to include a LinkedIn SignUp button through their API service to monitor the people who are using the website.
So far I copied and pasted what I have found on the LinkedIn SDK guide
<script type="in/Login"></script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
IN.User.logout(callbackFunction, callbackScope);
api_key: [API] //I put my API key here
authorize: true
onLoad: onLinkedInLoad
lang: [LANG_LOCALE]
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~").result(onSuccess).error(onError);
}
</script>
The button appeared the first time and it opens the connection to my LinkedIn profile. That's exciting! :D (Geek)
At this point I still don't know if I retrieve any data from the LinkedIn API service and if "yes" how to manage them and possibly include them in Intercom.io.
As far as I understood I should receive from LinkedIn API the following:
{
"firstName": "Frodo",
"headline": "Jewelery Repossession in Middle Earth",
"id": "1R2RtA",
"lastName": "Baggins",
"siteStandardProfileRequest": {
"url": "https://www.linkedin.com/profile/view?id=…"
}
}
Do I actually receive the answer? How do I read it? How do I use it in the following Intercom.io script?
<script>
window.intercomSettings = {
app_id: "k9sz4pfb",
name: "Nikola Tesla", // Full name
email: "nikola#example.com", // Email address
created_at: 1312182000 // Signup date as a Unix timestamp
};
</script>
<script>(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/k92zopfb';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()</script>
I know this might be a very basic question but I am starting from zero and I like to learn by practicing...
Furthermore, if you have any suggestion about website or tutorial where I could learn step-by-step it will be really appreciated.
Thank you for your help,
Giacomo
Double check the syntax but this should get you started.
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
var dataOutput =
// I added the callback event DONE. This assures the data method is called when the this API call is successful and complete.
var dataOutput = IN.API.Raw("/people/~").result(onSuccess).error(onError).done( {
if (dataOutput != null) {
DoSomethingWithYourData(dataOutput);
}
});
}
function DoSomethingWithYourData(dataOutput) {
console.log(dataOutput);
// Parse your data or assign it to a control. do whatever here.
}
And to answer your other question, you can add this to a JS script file and reference it on other pages, but you would have to keep any control IDs/class names added to this script file the same, so my tip would be to keep this file very generic so that it does not depend on anything else and only deals with working with LinkedIn's data.
I recommend these links for further reading so that you can expand on your code.
Jquery Parse JSON
JQuery AJAX
JQuery Callbacks
In Google Script Project I have 2 Google-API functions that should give out the same output.
can somebody please explain to me what I am wrong with, or maybe is it a bug in the API?
I have a group with 904 members.
Function "listMembersOfGroup1" is using the "GroupsManager" API, and is working correctly. the Logger displais "904.0".
And here is the code:
function listMembersOfGroup1() {
var group = GroupsManager.getGroup("group#domain.com");
var members = group.getAllMembers();
Logger.log(members.length);
}
But function "listMembersOfGroup2", which is using the "GroupsApp" API, is not working correctly (as far I understand). the Logger displais "753.0".
And here is the code:
function listMembersOfGroup2() {
var group = GroupsApp.getGroupByEmail("group#domain.com");
var users = group.getUsers();
Logger.log(users.length);
}
Is there any good reason why the "GroupApp" API gives out a different number?
Thanks in advance for your help.
.
(This is my first question on my first day on this site, I hope my question follows the rules.)
Welcome to StackOverflow. Your post was well explained.
The first API GroupsManager is used by domain administrators to manage their domain groups Check Here.
The secong one GroupsApp is used to manage google groups Google Groups API.
Your second call is retrieving users that belongs to the google groups mail passed as URL. Check full documentation here
So you're working with different google products.
i was wondering, the documentation has tutorials for implementing use of the Analytics API in several languages.
Now in PHP they show how to store the access token and maintain it , now i assume the JS somehow mentains it in some sort of local storage but i don't wish the user to authenticate each time he visitis so my plan is to save the access & refresh token in my database and simply applying it to the client-side instead of going through the all pop up procress.
According to tutorial this :
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, result);
Fires the popup which returns the access token but i'll say again i'm intrested in submiting token from database.
How can that be done?
is there some gapi.auth.setToken(token) method which after i could make calls to Core Reporting API?
I arrived here looking for a solution using this after having already written PHP to do the auth using google's PHP client libraries. I wanted to share the stored token as you mentioned, and be able to use javascript without re-authenticating, and/or triggering the popup (there may be a solution to this using the .init(callback) method, see docs/links at end).
Is there some gapi.auth.setToken(token) method
It turns out you can, there is the exact setToken(token) function you mention, and, you can even share the auth token generated earlier in PHP. What I'm not sure about yet, is if we should do it :)
I'm using PHP to do the initial auth, but presumeably in the javascript client you'd be able to call setToken() on something that you'd stored with getToken() in the same manner as this example. There may also be better approaches to this, like CORS (see links at end) mentioned in the API Authentication docs that I haven't had a chance to investigate any of these yet, but, I can give an example to answer the question, and might be useful to others needing the same behaviour
I first found Google developer Dan Holevoet's blog post with some sample JS code.
http://googleappsdeveloper.blogspot.com.au/2011/12/using-new-js-library-to-unlock-power-of.html
It's great to be able to query the API directly with javascript, and dynamically load lists etc, but the thing that worried me about this of course was storing clientid etc in js..
// Snippet from Dan's post
var clientId = 'YOUR_CLIENT_ID';
var apiKey = 'YOUR_API_KEY';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
checkAuth();
}
But, according to Dan in an answer to the same question:
The apiKey is used in conjunction with designated referrers, which you
must declare in the APIs Console. If the key is sent from an
unauthorized referrer, it will not work. You should make your accepted
referrer list as limited as possible to ensure that others do not use
your apiKey for their own requests.
Now, my example is for the calendar API, but it all seems pretty consistent with the other APIs as well.
Note: This snippet was for proof-of-concept purposes only, and probably shouldn't be used in production. I assume the referrer protection mentioned makes something like this OK to do, but more thought needs to be given. It could be done by hidden input, AJAX call etc.. But in the end, they're all going to be visible in the javascript.
What I did to test the concept was to:
Authenticate via PHP client libs, using the same script/URL as callback (see [API console][2] for these callbacks)
On sucessful auth, in callback, set a global javascript variable in the page to the stored PHP auth token
Once page is loaded, on your first click event to use the javascript (or even in document ready), call authMe() to set the token
Then proceed as normal, calling any javascript API methods that you have given scope to in the initial PHP authentication process (in this case makeApiCall())
Like so:
In the php callback routine, regardless of whether authenticated yet (assuming that your callback URL is the same script), make this var global
<script type="text/javascript">
// A place to stick PHP's auth token once the auth dance is done
var dodgey_global_access_token = {};
</script>
Now, in php callback routine once we've checked that we're authenticated, and $_SESSION['token'] = $client->getAccessToken(); has been called (IE storing the auth token somewhere for later), or at least $client->getAccessToken() has something meaningful:
<script type="text/javascript">
// Set the js var via PHP here.. Yeck... Note json encode in php and parse in jquery
dodgey_global_access_token = $.parseJSON (<?php echo json_encode ($client->getAccessToken() ); ?>);
// dodgey_global_access_token now contains the auth token structure
// Removed auth-related functions in Dan's code - we'll already have a token
// Dan's orig function to list events in 'primary' calendar
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
// My function to setToken with the token injected from PHP authentication
function authMe () {
// Stuff the token into the gapi object
gapi.auth.setToken( dodgey_global_access_token );
// Now call the original 'makeAPICall' function now that we're 'authenticated'
makeApiCall();
}
</script>
Note: I used jquery in my example to quickly parse the JSON, we're already using it in the project, but if not, you'll have to find another library to do so
Relevant/useful docs:
// Sorry, as a new poster I can only post 2 hyperlinks,
// so embedding this in code snippet
//
// http://code.google.com/p/google-api-javascript-client/wiki/ReferenceDocs#gapi
// http://code.google.com/p/google-api-javascript-client/wiki/Authentication
// http://code.google.com/p/google-api-javascript-client/issues/detail?id=22
// http://code.google.com/p/google-api-javascript-client/wiki/CORS
// https://code.google.com/apis/console
Let me know if anything's unclear, and can post a working sample to demo.
Google API documentation has changed a bit from when this answer was first provided. google-api-javascript-client is no longer the recommended library for accessing google api libraries and Google suggests using discovery documents to load specific libraries.
As a result, the workflow that you are looking for in order to load all the libraries and set the access token would look like this:
var token = 'someaccesstokenfromoauth2'
gapi.load('client:auth2', function(){
gapi.client.load(
'https://analyticsreporting.googleapis.com/$discovery/rest',
'v4'
).then(function(){
gapi.auth.setToken({ access_token: token })
// business logic with gapi.client.analyticsreporting()
})
})
Load gapi with:
<script src="https://apis.google.com/js/api.js"></script>