Node.js 3rd party REST API call - node.js

Im using nodejs to make a call to a 3rd party API. My code code returns the correct data for an id that I'm passing in my backend. When I run my app, to retrieve the data I go to localhost:5000/api/Dls.
My code
app.get("/api/Dls", (req, res) => {
const response = {
success: false
};
if (req.user && Authorized.myToken) {
response.success = true;
response.data = {};
response.data.user = req.user;
const id = response.data.user.sub;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + 'id',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Now I'm trying to do something like this localhost:5000/api/Dls/1234 instead of using a hard coded id in the backend
I attempted doing the following but when I enter a valid id in the url (ex. localhost:5000/api/Dls/1234) I get this "", any idea to what I should be doing?
app.get("/api/Dls/:id", (req, res) => {
const response = {
success: false
};
if (Authorized.myToken) {
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Any feedback would be appreciated!

You are not passing the route id to the api.
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + req.params.id,
headers:{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};

Related

Node Js get request in for loop and collect responses in an object

nodejs / meteorjs newbie here,
I am trying to query an api in for loop and collect all responses in one object and return that object. here is my code set up
const req = require('request');
const getallJira = (namespace, services) => {
let allJiraResponses = {};
for (let i in services) {
let _serviceName = services[i];
const options = {
method: 'POST',
url: 'https://jira/jira/rest/api/2/search',
headers: {
'Content-Type': 'application/json',
Authorization: base64Auth,
Accept: 'application/json',
},
body: JSON.stringify({
jql: `NAMESPACE = ${namespace} AND labels = 'kind/promotion' AND (SERVICE_NAME = '${_serviceName}' OR 'Service Name/Package Name' = '${_serviceName}')`,
maxResults: 1000000,
startAt: 0,
fields,
}),
};
request(options, function(error, response) {
if (error) throw new Error(error);
const jiraResponse = JSON.parse(response.body);
allJiraResponses[_serviceName] = jiraResponse;
});
}
return allJiraResponses;
};
however the final allJiraResponses is returned empty because of the asynchronous nature of request. How do i record all the responses from jira API in the object and return it to the caller of getallJira
I think you should separate into function to make it clearer
the first one to get the result for a single service
const getJiraService = ( namespace, serviceName) => new Promise((resolve, reject) => {
const options = {
method: 'POST',
url: 'https://jira/jira/rest/api/2/search',
headers: {
'Content-Type': 'application/json',
Authorization: base64Auth,
Accept: 'application/json',
},
body: JSON.stringify({
jql: `NAMESPACE = ${namespace} AND labels = 'kind/promotion' AND (SERVICE_NAME = '${serviceName}' OR 'Service Name/Package Name' = '${serviceName}')`,
maxResults: 1000000,
startAt: 0,
fields,
}),
};
request(options, function(error, response) {
if (error) {
resolve({serviceName, error});
return;
}
const jiraResponse = JSON.parse(response.body);
resolve({serviceName, jiraResponse})
});
})
const getallJira = async (namespace, services) => {
const results = await Promise.all(services.map(s => getJiraService(namespace, s));
return results.reduce((res, {serviceName, error, jiraResponse}) => {
if(!!jiraResponse){
return {
...res,
serviceName: jiraResponse
};
}
return res;
}, {})

AutoDesk forge viewer Api integration issue

I am integrating Forge Api in my NodeJs application.
All other Api works e.g authentication , creating bucket and translation a model.When I redirect to the html page to view my model it gives the 404 error..I have been stuck on this.
Below is the code and images attached.Authentication and bucket creation Api's skipped in the below code..
Folder structure is
->server
-->app.js
-->viewer.html
App.js
app.post('/api/forge/datamanagement/bucket/upload/uploads/:filename', function (req, res) {
console.log(req.params.filename);
console.log("Token",access_token)
var fs = require('fs'); // Node.js File system for reading files
fs.readFile(`./uploads/${req.params.filename}`, function (err, filecontent) {
console.log(filecontent)
Axios({
method: 'PUT',
url: 'https://developer.api.autodesk.com/oss/v2/buckets/' + encodeURIComponent(bucketKey) + '/objects/' + encodeURIComponent(req.params.filename),
headers: {
Authorization: 'Bearer ' + access_token,
'Content-Disposition': req.params.filename,
'Content-Length': filecontent.length
},
data: filecontent
}).then(function (response) {
// Success
console.log(response);
console.log("IdUrn ====>>>>>>>"+ response.data.objectId)
var urn = response.data.objectId.toBase64();
console.log("In Response")
res.redirect('/api/forge/modelderivative/' + urn);
}).catch(function (error) {
// Failed
console.log(error.message);
res.send(error.message);
});
});
});
app.get('/api/forge/modelderivative/:urn', function (req, res) {
console.log("urrrr",req.params.urn)
var urn = req.params.urn;
var format_type = 'svf';
var format_views = ['2d', '3d'];
Axios({
method: 'POST',
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/job',
headers: {
'content-type': 'application/json',
Authorization: 'Bearer ' + access_token
},
data: JSON.stringify({
'input': {
'urn': urn
},
'output': {
'formats': [
{
'type': format_type,
'views': format_views
}
]
}
})
})
.then(function (response) {
// Success
console.log("Translated=============>>>",response);
res.redirect('/viewer.html?urn=' + urn);
})
.catch(function (error) {
// Failed
console.log(error);
// res.send(error.message);
});
});
Response in the network Tab

Azure Face API - Node JS Cannot sent local file in form of binary

I have tried to send the base64 form image into the Azure Face-API, with a config like this
var config = {
method: 'post',
url: endpoint,
params: {
returnFaceId: true,
returnFaceLandmarks: false,
returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
},
body:Buffer(facesBase64, 'base64'),
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-Type': 'application/octet-stream'
}
};
but it always gets error 400. Is the binary form I sent wrong? facesBase64 is already in Base64 form.
EDIT
facesBase64 is full of base64 like this value
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ......
I think you can't send the base64 image into the Azure Face-API.
UPDATE
Send local image to faceapi.
'use strict';
const request = require('request');
const fs = require("fs");
// Replace <Subscription Key> with your valid subscription key.
const subscriptionKey = "eb8d5ea******8877c0" ;
const uriBase = 'https://pan***api.cognitiveservices.azure.com/face/v1.0/detect';
const imageBuffer = fs.readFileSync('jason.jpg');
// Request parameters.
const params = {
'returnFaceId': 'true',
'returnFaceLandmarks': 'false',
'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
};
const options = {
uri: uriBase,
qs: params,
body: imageBuffer,
headers: {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonResponse = JSON.stringify(JSON.parse(body), null, ' ');
console.log('JSON Response\n');
console.log(jsonResponse);
});
I tried the method you mentioned for testing and got the following results.
{
"error": {
"code": "InvalidImage",
"message": "Decoding error, image format unsupported."
}
}
Below is my test code.
'use strict';
//const request = require('request');
const fs = require("fs");
const axios = require("axios");
const request = require('request').defaults({ encoding: null });
// Replace <Subscription Key> with your valid subscription key.
const subscriptionKey = "eb8d5ea0********8877c0" ;
const uriBase = "https://pans***api.cognitiveservices.azure.com"+ '/face/v1.0/detect'
const imgUrl="https://pan***torage.blob.core.windows.net/ja**b/ja**.jpg";
var imageBuffer;
request.get(imgUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data;
data = "data:" + response.headers["content-type"] + ";base64," + Buffer.from(body).toString('base64');
imageBuffer=data;
aa();
}
});
function aa(){
// Request parameters.
const params = {
'returnFaceId': 'true',
'returnFaceLandmarks': 'false',
'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
};
const options = {
uri: uriBase,
qs: params,
body: imageBuffer,
headers: {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonResponse = JSON.stringify(JSON.parse(body), null, ' ');
console.log('JSON Response\n');
console.log(jsonResponse);
});
}
Suggest.
If you really want to implement your function in this way, it is recommended to raise a support on the portal. Consult the official answer, which image formats currently supported by faceapi.
You can also submit suggestions to the official product group.

Can't get data from Spotify api

I want to get the data of artists followed by a user, but when I make the request, it just gives me an error code 400, and the message 'Only valid bearer authentication supported'. I'm not sure what's wrong. Here's the code I'm using.
app.get('/callback', function(req, res) {
var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
if (state === null || state !== storedState) {
res.redirect('/#' +
querystring.stringify({
error: 'state_mismatch'
}));
} else {
res.clearCookie(stateKey);
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,
refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me/following?type=artist&limit=50',
headers: { 'Authorization': 'Bearer' + access_token },
json: true
};
request.get(options, function(error, response, body) {
console.log(body);
});
res.redirect('/#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
} else {
res.redirect('/#' +
querystring.stringify({
error: 'invalid_token'
}));
}
});
}
});

how to authenticate to oracle cloud ipnetwork API using auth token?

I am unable to authenticate to oracle cloud using auth token.I am using "request" node module in node js to connect to oracle cloud using its REST endpoint.I am passing the authentication token in header and the response i am getting is"HTTP 401 Unauthorised".Dont know why it is happening.Any help is appreciated.
Here's an example that first obtains a token and then uses it for a subsequent request.
Start by setting these environment variables:
OC_REST_ENDPOINT
OC_IDENTITY_DOMAIN
OC_USER
OC_PASSWORD
For example:
export OC_REST_ENDPOINT=https://api-z999.compute.us0.oraclecloud.com/
export OC_IDENTITY_DOMAIN=myIdentityDomain
export OC_USER=some.user
export OC_PASSWORD=supersecretpassword
Then use the following example:
const request = require('request');
const restEndpoint = process.env.OC_REST_ENDPOINT;
const identityDomain = process.env.OC_IDENTITY_DOMAIN;
const user = process.env.OC_USER;
const password = process.env.OC_PASSWORD;
request(
{
method: 'POST',
uri: restEndpoint + 'authenticate/',
headers: {
'content-type': 'application/oracle-compute-v3+json',
},
body: JSON.stringify({ // Must be a string, buffer or read stream
user: '/Compute-' + identityDomain + '/' + user,
password: password
})
},
function(err, res, body) {
if (err) {
console.log(err);
return;
}
if (res.statusCode !== 204) {
console.log('Something broke.');
return;
}
console.log('Got auth token');
let token = res.headers['set-cookie'][0];
request(
{
method: 'GET',
uri: restEndpoint + 'instance/',
headers: {
'accept': 'application/oracle-compute-v3+directory+json',
'cookie': token
}
},
function(err, res, body) {
if (err) {
console.log(err);
return;
}
console.log(body);
}
);
}
);

Resources