Axios and POST request to Zendesk API - node.js

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);
});

Related

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;
}

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

How to use request parameters in query string to retrieve JobNimbus contacts

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);
});

Send post request with Axios with body and headers

I am working on a project where I need to create a short URL for a link using bitly.
I got success by using the request package of Nodejs.
This is what I have done so far.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
var options = {
url: api_url,
method: "POST",
headers: headers,
body: dataString,
};
request(options, (error, body) => {
if (error) {
return res.status(404).send(error);
}
return res.render("index", { error: "", data: JSON.parse(body.body) });
});
my question is how can we use Axios instead of the request package because the request package is deprecated.
I tried but did not get success.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
const response = await axios.post(
api_url,
{ long_url: req.body.url },
{
headers: headers,
}
);
return res.render("index", { error: "", data: response });
I am getting errors like the body is not defined.
Please help me. Thank you!
const response = await axios.post(api_url, dataString, {
headers: headers,
});
console.log(response.data);
return res.render("index", { error: "", data: response.data });

Resources