How to use request parameters in query string to retrieve JobNimbus contacts - node.js

I am trying to fetch a contact in JobNimbus based on their display name. According to their docs under "Retrieve All Contacts", I should be able to do this.
Below is the code they recommend:
var axios = require('axios');
var config = {
method: 'get',
url: 'https://app.jobnimbus.com/api1/contacts',
headers: {
'Authorization': 'bearer <token>',
'Content-Type': 'application/json'
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Below is their request parameters example:
{
"must": [
{
"range": {
"date_created": {
"gte": 1459749600,
"lte": 1459835940
}
}
}
]
}
How do I request a contact based on their display_name?

It explains how to filter your search in the docs here. Just have to include the search criteria in the query params.
var axios = require('axios');
var config = {
method: 'get',
url: 'https://app.jobnimbus.com/api1/contacts?filter={"must":[{"term":{"first_name":"John"}},{"term":{"last_name":"Smith"}}]}
',
headers: {
'Authorization': 'bearer <token>',
'Content-Type': 'application/json'
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});

Related

Axios and POST request to Zendesk API

I'm trying a custom ticket form with the Zendesk API for end users. I followed this tutorial but it uses Python whereas I use Node and React. I use Axios but I got an error response
data: { error: "Couldn't authenticate you" }
Here is my code
var axios = require('axios');
var config = {
method: 'post',
url:'https://subdomain.zendesk.com/api/v2/requests.json',
headers: {
'content-type': 'application/json'
},
data:{'request':{'subject': 'test', 'comment': {'body': 'ceci est un test'}}},
auth:('MY_EMAIL/token:_TOKEN'),
};
axios(config)
.then(function (response) {
res.send(response.data);
})
.catch(function (error) {
console.log(error);
});
You should set your token as header like so:
var axios = require('axios');
const token = '{base-64-encoded email_address/token:api_token}'
var config = {
method: 'post',
url:'https://subdomain.zendesk.com/api/v2/requests.json',
headers: {
'content-type': 'application/json',
'Authorization': `Basic ${token}`
},
data:{'request':{'subject': 'test', 'comment': {'body': 'ceci est un test'}}}
};
axios(config)
.then(function (response) {
res.send(response.data);
})
.catch(function (error) {
console.log(error);
});

a single script in node to get authToken from some xyz oath2 /token end point and call the following api. I have coded something like this below

// getToken.mjs
import axios from 'axios';
import qs from 'qs';
var data = qs.stringify({
'client_id': 'xxxx-xxx',
'client_secret': 'xxxx-xxx',
'scope': 'https://graph.microsoft.com/.default',
'grant_type': 'client_credentials'
});
const config = {
method: 'get',
url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded', },
data : data
};
export let accessToken = axios(config)
.then(function (response) {
console.log((response.data.access_token));
})
.catch(function (error) {
console.log(error);
});
--------- Calling the API in the second script -----
//get response.js
import axios from "axios";
import { accessToken } from "./getToken.mjs";
const config = {
method: 'get',
url: 'https://graph.microsoft.com/v1.0/me/',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${accessToken}`,
}
};
export let data000 = axios(config).then(function (response) {
console.log(JSON.stringify(response.data));
}).catch(function (error) {
console.log(error);
});
console.log(data000);
On executing the > node response.js ... returns 401, client secret, and id is correct. However, I feel the accessToken is not getting imported and hence the error. How do I fix this?
Try to use POST method to get accessToken.
const config = {
method: 'post',
url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded', },
data : data
};

Node js passing query string to url

I am using the request promise plugin request to create the get and post api. I want to pass the URL with a parameter. below is my code. How to pass parameter value in URL?
async function getDetails (req) {
var options = {
url: 'http://localhost:3000/api/student/id/{studen_id}/branch/{studentbranch}',
method: 'GET',
headers: {
'User-Agent': 'my request',
'Authorization': 'Bearer {my token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
},
json: true
};
let res= await rp(options)
.then(function (body) {
return body;
})
.catch(function (err) {
console.log("error get balance",err)
});
return res;
}
To pass the parameter by URL, you can pass like this:
http://localhost:3000/api/student/?id={studen_id}&branch={studentbranch}
async function getDetails (req) {
var options = {
url: 'http://localhost:3000/api/student/id/'+encodeURIComponent(req.body.id)+'/branch/'+encodeURIComponent(req.body.branch),
method: 'GET',
headers: {
'User-Agent': 'my request',
'Authorization': 'Bearer {my token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
},
json: true
};
let res= await rp(options)
.then(function (body) {
return body;
})
.catch(function (err) {
console.log("error get balance",err)
});
return res;
}

API call works with Postman, but does not with Axios

I am using third party API. The way it works is:
I send post request then Token is returned in response.
Then i use that Token to check status. Afterwards, report is returned in response
In postman, i make both calls separately and it is working, but in Axios I have 1 async function and 2 await Promises.
Postman(NodeJs - Axios) looks like this:
For getting Token:
var data = JSON.stringify({
"security": {
"pLogin": "a",
"pPassword": "io"
},
"data": {
"pHead": "005",
"pCode": "00433",
"pLegal": 1,
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportId": 8,
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
For getting Report with the token:
var data = JSON.stringify({
"data": {
"pHead": "005",
"pCode": "00433",
"pToken": "kgqjismxdrpjnjaqnlnbmovcsvnkarfd",
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/status',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
My async function with Axios:
/* 1. Searching for client in database (Full name is used, but can be changed)*/
const client = await client.findOne({
name: body.name,
family_name: body.family_name,
patronymic: body.patronymic
});
if (!client) {
return res.status(401).json({ message: "Client is not registered" });
}
/* 2. If client was found in database, make an API call */
let credit_report;
try{
credit_report = await axios.post(
'http://10.22.50.10/report',
{
security: {
pLogin: 'a',
pPassword: 'io',
},
data: {
pHead: "005",
pCode: "00433",
pLegal: 1,
pClaimId: client.claim_id,
pReportId: 8,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
}catch(err){
return res.status(400).json({errorMessage: err.message})
}
// await new Promise(resolve => setTimeout(resolve, 3000));
if(!credit_report.data.data.token) return res.status(400).json({message: credit_report.data});
const credit_report_status = await axios.post(
'http://10.22.50.10/report/status',
{
data: {
pHead: "005",
pCode: "00433",
pToken: credit_report.data.data.token,
pClaimId: client.claim_id,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
console.log(credit_report_status)
if(credit_report_status.data.data.result == '05000') return res.status(200).json({ message: 'Client fetched.', clientData64: credit_report_status.data.data.reportBase64});
else return res.status(400).json({message: credit_report_status.data})
When I am using Postman to check my module, it is saying Error 400 Bad Request

incorrect behaviour of node-fetch while trying to get token from an api

I want to connect to an external api using some node-fetch code. My code first sends the login details & should receive a token from the api. Then this token is used for all the later communications.
Here is the code :
import fetch from 'node-fetch';
function getTokenForAuth(info) {
try {
var auth_token = '';
fetch(api_url + '/api/api-token/', {
method: 'POST',
body: JSON.stringify(info),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(function(res) {
return res.json();
})
.then(function(json) {
auth_token = json;
})
return auth_token.token;
}
catch (e) {
console.log('[-] Error: Token Not Received');
console.log('[!] Exception: ' + e);
}
}
function getJSONFromRelativeURL(relativeURL, info) {
return fetch(`${api_url}${relativeURL}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token ' + getTokenForAuth(info)
}
})
.then(function(res) {
console.log(res);
return res.json();
})
.then(function(json) {
console.log(json);
})
}
In the getJSONFromRelativeURL() function's request headers, if I hardcode the token, I get correct results. But if I run the code as it is now, I get an error saying : { detail: 'Invalid token.' }.
I think this is because of async nature of the promise in the fetch function, because of which it sometimes isnt able to send the token in time before the getJSONFromRelativeURL() gets called. I am not sure about this hypothesis & don't know how to correct this.
Your problem is here:
.then(function(json) {
auth_token = json;
})
return auth_token.token;
Your return statement is outside the Promise chain. This means that, at the point you hit return, the fetch request hasn't had a chance to even run yet. You've essentially just told the fetch Promise chain what to do when it does return.
So essentially
I think this is because of async nature of the promise in the fetch function, because of which it sometimes isnt able to send the token in time before the getJSONFromRelativeURL() gets called.
is 100% correct.
What you'll need to do is restructure things a little bit:
function getTokenForAuth(info) {
return fetch(api_url + "/api/api-token/", {
method: "POST",
body: JSON.stringify(info),
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
}).then(function(res) {
return res.json();
});
}
function getJSONFromRelativeURL(relativeURL, info) {
return getTokenForAuth(info)
.then(function(token) {
return fetch(`${api_url}${relativeURL}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${token}`
}
});
})
.then(function(res) {
console.log(res);
return res.json();
})
.then(function(json) {
console.log(json);
});
}
Have not tested it but it looks something like the following. For error handling use .catch(()=>{}) at the end of each chain.
function getTokenForAuth(info) {
var auth_token = '';
return fetch(api_url + '/api/api-token/', {
method: 'POST',
body: JSON.stringify(info),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(function(res) {
return res.json();
})
}
function getJSONFromRelativeURL(relativeURL, info, token) {
return fetch(`${api_url}${relativeURL}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token ' + token
}
})
.then(function(res) {
console.log(res);
return res.json();
})
.then(function(json) {
console.log(json);
})
}
getTokenForAuth(info)
.then((token)=>{
return getJSONFromRelativeURL(relativeURL, info, token)
})

Resources