Error when using multiple fetch requests in Zapier - javascript

I tried to find a solution online and on stackoverflow but i think the answers from the other posts focus on other things.
My problem is the error when i try to fetch more then 1 Hubspot api call.
The error message:
body used already for: https://api.hubapi.com/crm/v3/objects/deals?limit=100&archived=false
(returns list of deals)
var data = [];
let Timestamp = new Date().toISOString();
let Webhook = inputData.Webhook.trim();
let Method = inputData.Method.trim();
let JSONObject = {}
let Options = {
method: Method,
headers: {
'Authorization': `Bearer Hidden Key`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(JSONObject)
}
const Request = await fetch(Webhook, Options); // HTTP POST Request
const Response = await Request.json() // HTTP POST Response
data.push(Response);
Response.push(await Request.json());
let Webhook2 = Response.paging.next.link;
if ('paging' in Response) {
for (let i = 0; i < 10; i++) {
if (Webhook2 != "") {
let Options2 = {
method: Method,
headers: {
'Authorization': `Bearer Hidden Key`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(JSONObject)
}
const Request2 = await fetch(Webhook2, Options2); // HTTP POST
const Response2 = await Request2.json();
data.push(Response2);
if ('paging' in Response2) {
let Webhook2 = Response2.paging.next.link;
} else {
let Webhook2 = "";
}
}
}
}
output = data;
If someone could help me with this error i would really appriciate it.
Thanks in advance people.

Related

I get unknown path components: in messenger api

My api is as follows..
const { URL, URLSearchParams } = require("url");
async callSendApi(requestBody) {
let url = new URL(`${API_URL}/${PAGE_ID}/messages`);
url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
The error I get :
message: 'Unknown path components: /messagesaccess_token="access_token"
I cannot find any wrong in this api. but still I get above error.. so I tried following...
async callSendApi(requestBody) {
let url = new URL(`${API_URL}/${PAGE_ID}/messages`);
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
then I get a error saying that cannot set headers after sending to the client..
please help!

Spotify API returning data with Javascript/ React

I'm currently trying to incorporate Spotify's API into my project but I'm having problems fetching the data.
My token is returned in the console which is great but my call to return some data doesn't work.
I'm getting an error :
error:
message: "Only valid bearer authentication supported"
status: 400
[[Prototype]]: Object
[[Prototype]]: Object
Here's what I have so far. Maybe its a simple fix.
// Token
const CLIENT_ID = 'HIDDEN';
const CLIENT_SECRET = 'HIDDEN';
let authParameters = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=client_credentials&client_id=' + CLIENT_ID + '&client_secret=' + CLIENT_SECRET
}
async function getToken() {
let myToken = await fetch('https://accounts.spotify.com/api/token', authParameters)
let tokenReturn = await myToken.json()
console.log(tokenReturn.access_token)
}
// Request
async function searchData() {
const baseUrl = 'https://api.spotify.com/v1/browse/new-releases';
let ArtistParameters = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + tokenReturn
},
}
let artistID = await fetch(baseUrl, ArtistParameters)
let artistList = await artistID.json()
console.log(artistList);
}
useEffect(() => {
getToken()
searchData()
}, [])

Bad respond when trying to get authentication token for Reddit api 'Application Only OAuth'

So i been trying to get access to the reddit api.
I registered to reddit. verified my mail. opened an app and got my credentials.
Followed this official documentation and also came across to this tutorial
All my efforts have failed and don't get any respond.
I am using nodejs. but also tried in postman and failed.
Tried 2 options using fetch and using axios:
const axios = require('axios');
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
class RedditApi {
clientId2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
clientSecret2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
authenticationUrl = `https://www.reddit.com/api/v1/access_token`;
BASE_URL = 'https://www.reddit.com/';
tokenAuth = null;
tokenExpirationTime = null;
currencyObj = null;
constructor(currencyObj) {
this.currencyObj = currencyObj;
console.log("constructor service")
}
async getAuthToken() {
const bodyParams = new URLSearchParams({
grant_type: "https://oauth.reddit.com/grants/installed_client",
device_id: "DO_NOT_TRACK_THIS_DEVICE"
});
console.log(this.clientId2, 'this.clientId');
debugger;
const headersObj = {
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
};
let response = null;
try {
response = await axios.post(this.authenticationUrl,
bodyParams,
{
headers: headersObj
});
debugger;
} catch (error) {
debugger;
console.error(error);
console.log(error.stack);
return null;
}
}
async getAuthToken2() {
try {
// Creating Body for the POST request which are URL encoded
const params = new URLSearchParams()
params.append('grant_type', 'https://www.reddit.com/api/v1/access_token')
params.append('device_id', 'DO_NOT_TRACK_THIS_DEVICE')
// Trigger POST to get the access token
const tokenData = await fetch('https://oauth.reddit.com/grants/installed_client', {
method: 'POST',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}` // Put password as empty
}
}).then(res => {
debugger;
return res.text()
})
debugger;
if (!tokenData.error) {
debugger;
res.send(trendingResult)
}
res.status(tokenData.error).send(tokenData.message)
} catch (error) {
debugger;
console.log(error)
}
}
}
module.exports = RedditApi;
when using axios i get this respond: "Request failed with status code 401"
When using fetch i get this respond: "'403 Forbidden\nRequest forbidden by administrative rules.\n\n'"
Anybody knows what is the problem and how can i fix it?
Many thanks!

Converting C# syntax HTTP call to JS syntax call

I got an HTTP call implemented with C# which calls to an Azure API:
public async Task<string> CheckPipelineRunStatus(string pipelineId, string pipelineRunId, CancellationToken cancellationToken = default)
{
string responseBody = "";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", _token))));
var requestUrl = $"https://dev.azure.com/{_organization}/{_project}/_apis/pipelines/{pipelineId}/runs/{pipelineRunId}?api-version={_api_version}";
using (HttpResponseMessage response = await client.GetAsync(requestUrl, cancellationToken))
{
response.EnsureSuccessStatusCode();
responseBody = await response.Content.ReadAsStringAsync();
}
}
return responseBody;
}
I need to do the same call in a Javascript call and I'm not sure how exactly am I suppose to send the Authorization header.
Here's what I got so far without the header (question in comment inside the code):
async function checkPipelineStatus(url)
{
var params = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
//is the auth supposed to be here? what to do with that 64base string?
}
};
const fetchResult = await fetch(url, params);
const result = await fetchResult.text();
if (!fetchResult.ok)
{
throw result;
}
return result;
}
As requested, here's your JavaScript code with the header inserted:
async function checkPipelineStatus(url)
{
let base64Credentials = btoa(':' + _token);
var params = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
// Insert your own Base64 credentials here:
'Authorization': `Basic ${base64Credentials}`
}
};
const fetchResult = await fetch(url, params);
const result = await fetchResult.text();
if (!fetchResult.ok)
{
throw result;
}
return result;
}

Query for Spotify's Web API Client Credentials Flow

I'm trying to make a http request based on the documentation at https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow Client Credentials Flow.
I've written
const BASE_URL = 'https://accounts.spotify.com/api/token';
fetch(BASE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64(clientID) + ':' + base64(clientSecret)
},
body: JSON.stringify({'grant_type:client_credentials'})
})
Does this follow what it says to do? I'm confused how to write the body of the post request.
What I ended up doing which works:
async authorize(){
let myHeaders = new Headers();
myHeaders.append("Authorization", `Basic ${my_clientID:clientSecret}`);
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "client_credentials");
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
}
let res = await fetch("https://accounts.spotify.com/api/token", requestOptions);
res = await res.json();
return res.access_token;
}
async search(){
const access_token = await this.authorize();
this.setState({access_token});
const BASE_URL = 'https://api.spotify.com/v1/search';
let FETCH_URL = `${BASE_URL}?q=${this.state.query}&type=artist&limit=1`;
const ALBUM_URL = 'https://api.spotify.com/v1/artists';
let myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${access_token}`);
const requestOptions = {
method: 'GET',
headers: myHeaders
}
let res = await fetch(FETCH_URL, requestOptions);
res = await res.json();
console.log("ARTIST", res);
}
From the link you have shared, the client credential flow is a client (server-side) that makes a request to the spotify API server. Thus, it is a server-to-server authentication flow (not authorization). You are using the fecth API which is client-side so that means that your implementation should be server-side. If you are using a node.js runtime server-side framework, just look up the http.request API to make a request server-side.
For example, this would be a pure node.js implementation:
const options = {
hostname: 'https://accounts.spotify.com/api/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64(clientID) + ':' + base64(clientSecret)
}
};
const req = http.request(options, (res) => {
res.setEncoding('utf8');
// process the data bit by bit or in chunks...
res.on('data', (chunk) => {});
// ...and do something with it when there is no more data in response
res.on('end', () => {
console.log('No more data in response.');
});
});
// handle the error explicitly
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.end();
For me, I'm not sure if this is the case for anyone else, but the spotify api was refusing base64(clientID) + ":" + base64(clientKey), but accepting base64(clientID + ":" + clientKey)

Categories