How Can I add an API Key to a JS AJAX Request? - ajax

I've been accessing an API via cURL on the command line. In attempting to convert this to javascript, I've had issues.
The code below functions correctly within the command line:
curl -X GET --header "Accept: application/json" --header "Api-Key: vZKoJwFB1PTJnozKBSANADc3" "https://api.commonstandardsproject.com/api/v1/jurisdictions"
The following is the attempted javascript conversion:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("GET", "https://api.commonstandardsproject.com/api/v1/jurisdictions", true);
xhttp.setRequestHeader("Api-Key", "vZKoJwFB1PTJnozKBSANADc3");
xhttp.setRequestHeader("Accept", "application/json");
xhttp.send();
Error messages return a basic 401 error, ostensibly indicating some issue with my input of the Api-Key. Have I made any noticeable errors? Thanks for the help.

Related

How to add Supabase Order by in get request using Postman

I need to add order in supabase result while calling the supabase bash in postman.
I am doing same in flutter like below
Future getPropertiesFromBirmingham() async {
var response = await client
.from('properties')
.limit(10)
.order('created_at', ascending: false);
return response;
}
Need to use same in postman but not getting anything on this.
I didn't find much on this topic, Tried using order in params but it didn't work.
You can get examples of cURL requests directly in Supabase API docs.
You can also check for more documentation directly in the PostgREST website.
curl 'https://supabase_project_ref.supabase.co/rest/v1/properties?limit=10&order=created_at.desc' \
-H "apikey: SUPABASE_KEY" \
-H "Authorization: Bearer SUPABASE_KEY"
You can also control where the NULLs will be (if any) by adding either of the following:
nullslast
nullsfirst
curl 'https://supabase_project_ref.supabase.co/rest/v1/properties?order=created_at.desc.nullslast' \
-H "apikey: SUPABASE_KEY" \
-H "Authorization: Bearer SUPABASE_KEY"

Google cloud text-to-speech : the server responded with a status of 403 ()

I am trying to build a web page which will translate the text into mp3 using google cloud text-to-speech. After lots of search I found using REST API I can request the API to translate the text into mp3.
I am using JQuery and AJAX for the HTTP request.
Problem is that I am requesting the cloud server to translate the text using following data,
"data" : {
"input": {
"text": encodeURIComponent(text)
},
"voice" : {
"languageCode" : "en-US",
"name" : "en-US-Wavenet-A",
},
"audioConfig" : {
"audioEncoding" : "MP3",
}
},
By sending this I'm getting error 403 which clearly says that I do not have access to perform the requested action, in this document
I know without API key and authorization I cannot access the service. So my questions is how can I send my API key and authorizations keys so that I can get the authorization and perform the requested action.
Edit-1
I am sending request to server using following URL,
https://texttospeech.googleapis.com/v1beta1/text:synthesize?further_parameters_goes_here
If anyone want more information I can give it. Any help will be appreciated.
Thank you in advance.
Regards,
Vaibhav M
First you need to get your Google Cloud's API Key from your acount (https://cloud.google.com/docs/authentication/api-keys) and try the code bellow, replacing your-api-key in the script:
$( document ).ready(function() {
// An element to play the speech from Google Cloud
var Sound = (function () {
var df = document.createDocumentFragment();
return function Sound(src) {
var snd = new Audio(src);
df.appendChild(snd); // keep in fragment until finished playing
snd.addEventListener('ended', function () {df.removeChild(snd);});
snd.play();
return snd;
}
}());
// The settings for the Ajax Request
var settings = {
"async": true,
"crossDomain": true,
"url": "https://texttospeech.googleapis.com/v1/text:synthesize",
"method": "POST",
"headers": {
"x-goog-api-key": "**your-api-key**",
"content-type": "application/json",
"cache-control": "no-cache",
},
"processData": false,
"data": "{'input':{'text':'I have added the event to your calendar.'},'voice':{'languageCode':'en-gb','name':'en-GB-Standard-A','ssmlGender':'FEMALE'},'audioConfig':{'audioEncoding':'MP3' }}"
}
// The Ajax Request, on success play the speech
$.ajax(settings).done(function (response) {
console.log(response.audioContent);
var snd = Sound("data:audio/wav;base64," + response.audioContent);
});
});
You need to pass your API key as a header, the header field is "X-Goog-Api-Key". Also make sure you're setting the proper body encoding in the request using the "Content-Type" header, in your case I think it should be "Content-Type: application/json; charset=utf-8". And lastly, I'm think you shouldn't be encoding the text field in the request body.
If you don't have the API key yet, you can follow these steps to get to it
Create a project (or use an existing one) in the Cloud
Console.
Make sure that billing is enabled for your project.
Enable the Text-to-Speech API.
Create an API key.
I'm not familiar with JQuery and AJAX syntax, but you could use this curl command for reference
Curl -H "X-Goog-Api-Key: PUT_YOUR_API_KEY_HERE" \
-H "Content-Type: application/json; charset=utf-8" \
--data "{
'input':{
'text':'Android is a mobile operating system developed by Google,
based on the Linux kernel and designed primarily for
touchscreen mobile devices such as smartphones and tablets.'
},
'voice':{
'languageCode':'en-gb',
'name':'en-GB-Standard-A',
'ssmlGender':'FEMALE'
},
'audioConfig':{
'audioEncoding':'MP3'
}
}" "https://texttospeech.googleapis.com/v1beta1/text:synthesize" > synthesize-text.txt
I found out two possibilities that can help you.
Obtain a Bearer token.
If you installed the Cloud SDK, you can easily get the token with this command: gcloud auth application-default print-access-token. It can be executed in the Cloud Shell too. Just be sure that the default user you are logged in has the appropriate role to access the text-to-speech service. Then, attach the token to the header request, for example a final request can look like this.
curl -H "Authorization: Bearer ya29.GqUB8gVkiMCyl2ZCKEfS8Tb9QmS_LRb1bQP__fIPYbCU.....LUAlCRJU9OpFc_hCzSVUwlAZAhac2aZhoh" \
-H "Content-Type: application/json; charset=utf-8" \
--data "{
'input: {
'text': 'my custom text'
},
'voice' : {
'languageCode' : 'en-US',
'name' : 'en-US-Wavenet-A'
},
'audioConfig' : {
'audioEncoding' : 'MP3'
}
}" "https://texttospeech.googleapis.com/v1beta1/text:synthesize"
This link integrates the request and the command in one step.
Obtain an API key.
An API key is more portable than a token, but it can be used by anyone who possess it. It's recommended to restrict such key to the text-to-speech service. Then, you should use the key in the endpoint URL, for example "https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=AIzaSynAJU-EGnhdDaaXH4NVcc". A complete example looks like the following:
curl -H "Content-Type: application/json; charset=utf-8" \
--data "{
'input':{
'text':'my custom text'
},
'voice':{
'languageCode':'en-gb',
'name':'en-GB-Standard-A',
'ssmlGender':'FEMALE'
},
'audioConfig':{
'audioEncoding':'MP3'
}
}" "https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=AIzaSynAJU-EGnhdDaaXH4NVcc"

Static webpage in s3 bucket and making ajax request inside the page to call lambda function

I have uploaded a html page in s3 bucket and that html page makes an ajax post request to the api gateway url to send an email.
The problem is that the same api gateway url if I use postman to make a post request to it the email is sent but with the html page in s3 having ajax code doesn't work.
Any idea, or help will be helpful for me. Thanks
----Ajax code
$.ajax("https://apigateway-url/email_sending", {
"type": "POST",
"data": JSON.stringify(formData),
"contentType": "application/json"
}).done(function () {
console.log("Done")
}).fail(function () {
console.log("Failed");
// console.log(data);
});
I have tried so many help from net like edit cors configuration in s3 or enable cors in api gateway, but none worked for me.
NodeJs code for send Email
var sendemail = require('./sendemail')
app.post('/email_sending',function(req,res){
console.log("Request received For sending mail")
sendemail.send(req.body,function(err, data){
// res.setHeader('Access-Control-Allow-Origin', '*');
res.end("Success");
})
})
sendemail module snippet is :
ses.sendemail(data, done)
I considered this website but didn't get the solution : https://codehabitude.com/2016/04/05/forms-to-emails-using-aws-lambda-api-gateway/
Its very likely you aren't setting up the CORS headers correctly in apigateway. The apigateway documentation http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html clearly describes the process.
Once you've setup CORS and deployed the changes, you can verify the CORS preflight request using the below curl command
curl -H "Origin: http://example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: X-Requested-With" \
-X OPTIONS --verbose \
https://apigateway-url/email_sending
Also, note that you need to deploy the changes after you setup CORS (Big blue Deploy API button - http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-deploy-api-with-console.html) before the change is reflected in your API

Nodejs Ajax Call with XMLHttpRequest Header

I am trying to write a script for Hubot to make an AJAX call to Strawpoll.me. I have a cURL command that works exactly how I want but I am having trouble translating that into a Node.js function.
curl --header "X-Requested-With: XMLHttpRequest" --request POST --data "options=1&options=2&options=3&options=4&options=5&title=Test&multi=false&permissive=false" http://strawpoll.me/api/v2/polls
Here is what I currently have in my script.
QS = require 'querystring'
module.exports = (robot) ->
robot.respond /strawpoll "(.*)"/i, (msg) ->
options = msg.match[1].split('" "')
data = QS.stringify({
title: "Strawpoll " + Math.floor(Math.random() * 10000),
options: options,
multi: false,
permissive: true
})
req = robot.http("http://strawpoll.me/api/v2/polls").headers({"X-Requested-With": "XMLHttpRequest"}).post(data) (err, res, body) ->
if err
msg.send "Encountered an error :( #{err}"
return
msg.reply(body)
The script version is returning {"error":"Invalid request","code":40}
I can't tell what I am doing wrong. Thanks for your help.
For POST requests, curl sets the Content-Type to application/x-www-form-urlencoded. Hubot uses Node's http client, which OTOH, doesn't use any defaults for the Content-Type header. Without an explicit Content-Type header, the resource at http://strawpoll.me/api/v2/polls is not able to discern the request body. You'll have to set the Content-Type header manually to mimic curl's request.
robot.http('http://strawpoll.me/api/v2/polls')
.headers({'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded'})
.post(data)

Parse Cloud - make a GET endpoint

I have made simple cloud function:
Parse.Cloud.define("clientsnames", function(request, response) {
var query = new Parse.Query("Clients");
query.select('name')
query.find({
success: function(results) {
response.success(results)
},
error: function() {
response.error("Failed");
}
})
});
But to call it I always must use POST
curl -s -X POST \
-H "X-Parse-Application-Id: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-H "X-Parse-REST-API-Key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-H "Content-Type: application/json" \
-d "{}" \
https://api.parse.com/1/functions/clients
Which is, of course, a bad idea, and the request itself is obviously should be GET. But when I use GET with this request, I just get 404 (Document not found).
Is it possible to define a GET endpoint using Parse Cloud?
You can use Express js hosted on Parse CloudCode to setup custom endpoints
That way you can configure GET, POST without even using the Parse keys in the headers.
Head over to
https://www.parse.com/docs/cloud_code_guide#webhooks for detailed example

Resources