ProductHunt API Authentication using jQuery - javascript

I'm trying to use the ProductHunt API using jQuery. To use the ProductHunt API, you need to authenticate before you can access the data. I'm using the OAuth Authentication.
Here is the code that I have got.
// api key and secret
key = "api key goes here"
secret = "api secret goes here"
var base_url = "https://api.producthunt.com/v1/"
var token_url = base_url +"oauth/token"
var today_post_url = base_url + "posts"
function get_token(){
var token = '';
$.ajax({
url: token_url,
type: "POST",
async: false,
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: {
"client_id": key,
"client_secret": secret,
"grant_type": 'client_credentials'
},
success: (function(res) {
token = res.access_token;
})
});
return (token);
}
function get_todays_posts() {
token = get_token();
console.log(token);
$.ajax({
url: today_post_url,
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
success: (function(res){
return res;
})
})
}
But when I run get_todays_post(), I get a error message saying GET https://api.producthunt.com/v1/posts 401 (Unauthorized)

Related

"Failed: There was an error while trying to create this media item."

I'm trying to upload a photo on Google Photos, with google api, but i always get this error:
"status":{"code":3,"message":"Failed: There was an error while trying to create this media item."}}
I think that the problem is in the way i take the binary data of photo.
In this code i follow google photo api developers documentation, and it says, after take authorization, to:
1- Upload the raw bytes to a Google Server: to take upload-token
2- Use the upload token to create the media item.
This my node js code:
const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", {
'encoding': 'binary',
'flag' : 'r'
});
var url= 'https://photoslibrary.googleapis.com/v1/uploads';
var headers= {
'Authorization': 'Bearer '+token,
'Content-type': 'application/octet-stream',
'X-Goog-Upload-Content-Type': 'image/png',
'X-Goog-Upload-Protocol': 'raw',
'X-Goog-Upload-File-Name': "2020-05-30T17:29:14+0000_0.png",
};
var body= photo
request({
url: url,
method:'POST',
headers: headers,
rejectUnauthorized: false,
body: JSON.stringify(body)
}, function(error, response, body1){
if(error)
{
console.log(error);
}
else
{
var upToken = body1.toString();
console.log(upToken);
var url= 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate';
var headers= {
'Authorization' : 'Bearer '+token,
'Content-type': 'application/json',
};
var body= {
'newMediaItems': [
{
'description': 'Prague',
'simpleMediaItem': {
'fileName': 'prova',
'uploadToken': upToken,
}
}
]
};
request({
url: url,
method: 'POST',
headers: headers,
rejectUnauthorized: false,
body: JSON.stringify(body),
}, function(error, response, body){
if(error)
{
console.log(error);
}
else
{
res.send(JSON.parse(body));
}
});
}});
Please help me, if anyone has any idea!!
How about this modification?
Modification points:
I think that encoding: "binary" is not required.
In this case, ``const photo = fs.readFileSync("fig1.png", { flag: "r" });andconst photo = fs.readFileSync("fig1.png");` can be used.
Please modify body: JSON.stringify(body) to photo of const photo = fs.readFileSync("fig1.png", { flag: "r" });.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", {
'encoding': 'binary',
'flag' : 'r'
});
var url= 'https://photoslibrary.googleapis.com/v1/uploads';
var headers= {
'Authorization': 'Bearer '+token,
'Content-type': 'application/octet-stream',
'X-Goog-Upload-Content-Type': 'image/png',
'X-Goog-Upload-Protocol': 'raw',
'X-Goog-Upload-File-Name': "2020-05-30T17:29:14+0000_0.png",
};
var body= { 'media-binary-data': photo }
request({
url: url,
method:'POST',
headers: headers,
rejectUnauthorized: false,
body: JSON.stringify(body)
}, function(error, response, body1){
To:
const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", { flag: "r" });
var url = "https://photoslibrary.googleapis.com/v1/uploads";
var headers = {
Authorization: "Bearer " + token,
"Content-type": "application/octet-stream",
"X-Goog-Upload-Content-Type": "image/png",
"X-Goog-Upload-Protocol": "raw",
"X-Goog-Upload-File-Name": "2020-05-30T17:29:14+0000_0.png",
};
request(
{
url: url,
method: "POST",
headers: headers,
rejectUnauthorized: false,
body: photo,
},
function (error, response, body1) {
Note:
In this modification, it supposes that your token can be used for this API. Please be careful this.
When you want to directly put the uploaded image to an alubmn, please include albumId for requesting to https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate.
Reference:
Upload media

How to get the response JSON from API call

I want to retrieve the JSON response from the api call I am doing. Example, I want to retrieve something like this:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is my API call using fetch in react. (yes I know sending password in URL is bad, it's for a school project)
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
console.log(res); //I want to get the JSON stuff here
})
This is the API call I am calling.
app.get('/api/user/:user', function (req, res) {
// console.log(JSON.stringify(req));
// var user = req.body.user;
// var password = req.body.password;
var user = req.params.user;
var password = req.query.password;
console.log(user, password);
var result = { error: {} , success:false};
if(user==""){
result["error"]["user"]="user not supplied";
}
if(password==""){
result["error"]["password"]="password not supplied";
}
if(isEmptyObject(result["error"])){
let sql = 'SELECT * FROM user WHERE user=? and password=?;';
db.get(sql, [user, password], function (err, row){
if (err) {
res.status(500);
result["error"]["db"] = err.message;
} else if (row) {
res.status(200);
result.data = row;
result.success = true;
} else {
res.status(401);
result.success = false;
result["error"]["login"] = "login failed";
}
res.json(result);
});
} else {
res.status(400);
res.json(result);
}
});
When I do console.log(res) in the fetch call, this is what is printed:
Response {type: "basic", url: "http://localhost:3000/api/user/tim?password=123", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "basic"url: "http://localhost:3000/api/user/tim?password=123"proto: Response
When I visit the website, the output is:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is what I want.
In general, this is how you return the response body from the Promise.
fetch(`${baseUrl}/api/user/${user}?password=${password}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}})
.then(response => response.json())
.then‌​(data=> {
console.log(data);
})
Try this way to parse the response:
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then(async (res) => {
const raw = await res.text();
const parsed = raw ? JSON.parse(raw) : { success: res.ok };
console.log(parsed);
})
In this case you can also add some checks for response statuses (if you want, of course) along with parsing the result JSON.
for you to get the JSON body content from the response, you need to use json()
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
const jsonData = res.json();
console.log(jsonData);
})
try this
fetch(${baseUrl}/api/user/${user}?password=${password},{
method:'GET',
headers: {
'Accept': 'application/json',
'Content-Type':
'application/json',
}}) .then(async(response ) => {
await response.json()
})

How to create user in openfire using restapi in nodeJs application?

This is my function in NodeJs app which I am using to create user in openfire.
var createUser = function(objToSave, callback) {
const options = {
method: 'POST',
uri: url.resolve(Config.APP_CONSTANTS.CHAT_SERVER.DOMAIN_NAME, '/plugins/restapi/v1/users'),
headers: {
'User-Agent': 'Request-Promise',
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: objToSave
}
request(options)
.then(function(response) {
callback(null, response);
})
.catch(function(error) {
// Deal with the error
console.log(error);
callback(error);
});
};
the objToSave is a json object contains username and password.
{
"Username": "gabbar",
"Password": "gabbar#123"
}
when i run this function i am getting the following error..
{
"statusCode": 400,
"error": "Bad Request"
}
I configured my secret-key properly and domain name is localhost://9090, can anybody tell me what I am doing wrong ? thanks in advance.
I think the options you provided needs JSON.stringify object before send it
The modified options is as below
const options = {
method: 'POST',
uri: url.resolve(Config.APP_CONSTANTS.CHAT_SERVER.DOMAIN_NAME, '/plugins/restapi/v1/users'),
headers: {
'User-Agent': 'Request-Promise',
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: JSON.stringify(objToSave)
}
I find out that problem was with request-promise. it was not properly sending data in the required format. so Instead of that now I am using different module minimal-request-promise. and It worked like charm for me. After using that, my code looks something like this.
var requestPromise = require('minimal-request-promise');
var createUser = function(objToSave, callback) {
const options = {
headers: {
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(objToSave)
};
requestPromise.post('http://localhost:9090/plugins/restapi/v1/users', options)
.then(function(response) {
callback(null, response);
})
.catch(function(error) {
// Deal with the error
console.log(options);
console.log(error);
callback(error);
});
};

How to call Web API from ExtJS with token based authentication

Ext.Ajax.request({
url: 'Employee/Search',
method: 'POST',
headers: { "Content-Type":"application/json","Accept": "application/json","Authorization": "OAuth oauth_token=158ghhBtgf2586525hggfgdf" },
jsonData: {
"FirstName": txtFirstName.getValue()
},
success: function(response) {
},
failure: function(response) {
}
});
This is giving me 401 (Unauthorized Request)
I am using adal.js library by Microsoft, and using the following code:
window.acquireTokenCallback = function (error, token) {
if(error || !token) {
Ext.alert('ADALERROR', error || 'Token empty');
return;
}
// Apply token to all future Ajax requests.
Ext.Ajax.setDefaultHeaders({
'Authorization': 'Bearer ' + token,
'Accept': 'application/json'
});
// Load Settings from Server.
me.loadSettings();
};

Parse webrequest to Coinbase gives 401 not authorized

I'm trying to send bitcoin through Coinbase's API, and this is my code:
// create object to send as data
var transaction = {
to : correctusermail, // "my#email.com"
amount_string : amount, // "1.00"
amount_currency_iso : currency // "EUR"
};
// get correct auth key from user
var authq = new Parse.Query(Parse.User);
authq.get(objectid, {
success: function(userObject) {
correctauth = userObject.get("provider_access_token");
console.log(correctauth);
console.log(transaction);
// send post request
// make post request
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
access_token: correctauth,
transaction: transaction
},
success: function(httpResponse) {
response.success(120);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(111);
}
});
},
error: function(userObject, error) {
response.error(150);
}
});
As you can see I'm making sure that my correctauth var is correct by logging it, which works just fine.
All the other variables are correct, I've checked them. So what am I missing? It's probably very small.
From my understanding of the Coinbase API documentation, the access_token should always be part of the URL, e.g.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money?access_token='
+ correctauth,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
transaction: transaction
},
// ... etc ...

Categories