How do I transform this curl request with javascript axios - javascript

I want to perform a request to the Google speech API, to return the translation of audio I sent to the API
If I use the curl command below, I successfully retrieve the data, but I don't know how to pass it to an Axios request.
curl command:
curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) -H "Content-Type: application/json; charset=utf-8" "https://speech.googleapis.com/v1/operations/{speech_name}"

// creating axios
const api = axios.create({
baseURL: https://speech.googleapis.com/v1/operations,
crossDomain: true,
responseType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'your_key
},
});
// calling api
api.get('/speech_name')
.then(res=>{
console.log(res);
}).
catch('error');
Note : you can use other request method also api.post(url)

Related

cURL with -F Option into NodeJS with Axios

I'm attempting to convert this CURL command
curl -X POST "https://serverless-upload.twilio.com/v1/Services/ZS5798711f7bee1284df67427071418d0b/Assets/ZH4912f44da25f4b1a1c042a16a17f2eac/Versions" \
-F Content=#./mapping/mapping.json; type=application/json \
-F Path=mapping.json \
-F Visibility=private \
-u username:password
into a post request using the package axios,
I've tried
url = `https://serverless-upload.twilio.com/v1/Services/${service_uid}/Assets/${asset_uid}/Versions`
data = {
'Path': 'mapping.json',
'Visibility': 'private',
'Content': JSON.stringify(mapping),
'filename': 'mapping.json',
'contentType': 'application/json'
}
await axios.post(url, data, {
auth : {
user: `${accountSid}:${authToken}`
},
headers: {
'Content-Type': 'multipart/form-data',
}
}).then((r) => console.log(r));
but I'm unsure if this is malformed or not
Twilio developer evangelist here.
The Twilio Node library actually uses axios under the hood, you can see it in action in the RequestClient. We also have a stand-alone Serverless API client which is part of the Twilio Serverless Toolkit you can use, but it is written with got instead.
You can use the Serverless API module to save yourself the work of recreating this request.
If you decide to continue with axios, here are the changes you should make.
Auth
Authorization is done via the Authorization header, passing a base 64 encoded string made up of the account Sid and auth token.
headers: {
Authorization: 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
}
Data
When uploading an asset, it is done as multipart form data. To build up multipart data in Node.js you can use the form-data module. Something like this should work:
const FormData = require("form-data");
const form = new FormData();
form.append("Path", "mapping.json");
form.append("Visibility", "private");
form.append("Content", JSON.stringify(mapping));
form.append("filename", "mapping.json");
form.append("contentType", "application/json");
await axios.post(url, form, {
headers: {
Authorization: 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64'),
...form.getHeaders(),
},
}).then((r) => console.log(r));
Let me know how you get on with that.

Send logs from Javascript to ElasticSearch

Is there any Javascript api that allows me to send post requests, either directly through axios post or through Node JS, to Elastic Search? This is to SEND logs to Elastic Search.
You can send POST requests using fetch.
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});

Converting cUrl token call to axios

I am trying to authenticate and API by calling to a seperate server, receiving a token to store, which is then used to Auth and API.
At the moment I have a token hardcoded in, because every time I submit a request with axios it returns "error": "invalid_request"
This cUrl script works fine curl -v -X POST -u "username:password" -d "grant_type=client_credentials" https://thewebsite/token -H 'cache-control: no-cache' and I can connect with Postman when I imported and added Basic Auth. I have tried to copy all the settings in, so many different ways.
I need to create an axios instance that is then passed to another function for the actual POST operation:
const settings = {
baseURL,
timeout: 5000,
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'cache-control': 'no-cache',
},
auth: {
username: username
password: password
},
data: {
grant_type: 'client_credentials',
},
};
this.axiosInstance = axios.create(settings);
In Postman the response looks like this:
"access_token": string,
"expires_in": 3600,
"token_type": "bearer"
I feel like it is an obvious syntax error, like the details need to be sent as a param or a header.

jQuery, How do I format a JSON request with authorization?

I'm new to JSON requests, cURL, etc. and I can't figure out how to correctly format a JSON request with authorization. I'm trying to call on a Spotify API and they reccomend a cURL request:
GET https://api.spotify.com/v1/search
and
curl -X "GET" "https://api.spotify.com/v1/search?q=tania%20bowra&type=artist" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer ReallyLongKey"
I don't know how to use cURL and GET so I tried to use ajax:
function Search() {
$.ajax({
url: 'https://api.spotify.com/v1/search?q=Muse&type=track%2Cartist&market=US&limit=10&offset=5',
datatype: 'json',
type: 'get',
cache: false,
success: function(Data) {
//stuff
}
});
}
How do I use cURL or add authentication to the ajax method? Thanks in advance,
Justin.

Access MailChimp API 3.0 (GET)

I'm trying to make a GET request through jQuery to the Mailchimp API. It seems though my custom header is not correctly set as I get a Your request did not include an API key. error.
It works fine if I make the request using curl on my Ubuntu machine:
curl --header "Authorization: apikey 709XXXXXXXXXXXXXXXXXXXXXXXXXXXXX-us11" https://us11.api.mailchimp.com/3.0/campaigns
Here's my code:
$.ajax({
type: 'GET',
url: 'https://us11.api.mailchimp.com/3.0/campaigns',
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
headers: {
'Authorization': 'apikey 709XXXXXXXXXXXXXXXXXXXXXXXXXXXXX-us11'
}
}).done(function (response) {
console.log(response); // verbose
});
I even tried adding this above:
$.ajaxSetup({
headers: { 'Authorization': 'apikey 709XXXXXXXXXXXXXXXXXXXXXXXXXXXXX-us11' }
});
You need to add the key via Basic Auth like and as far I am aware off, You can't query it from front-end, it must be on the back-end.
Find an example in NodeJS:
headers: {
'Authorization': 'Basic ' + new Buffer(`anything:${MailChimpKey}`).toString('base64');
}
MailChimp not allowed to direct access with ajax. Once make Server WebRequest. It will surely work.

Categories

Resources