How to upload the image using LinkedIn API without using curl request? - linkedin

I've used the curl request to upload an image which successfully worked for me.
curl -i --upload-file ~/Desktop/Myimage.jpg -H 'Authorization: Bearer Redacted' "https://api.linkedin.com/mediaUpload/C5522AQHn46pwH96hxQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQLKRJOn_yNw6wAAAW2T0DWnRStny4dzsNVJjlF3aN4-H3ZR9Div77kKoQ&app=1983914&sync=0&v=beta&ut=1Dnjy796bpjEY1"
I've tried using the same request with "request" package which got failed and redirected me to the "404 page not found" LinkedIn page.
Here is the code:
const options = {
headers: {
'Authorization': `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'multipart/form-data'
},
method: 'put',
url: mediaUploadUrl
}
fs.createReadStream(filePath).pipe(request(options, function(err, httpsResponse, body){
if ( err ) {
console.log('err', err);
response(callback, 400, err);
} else {
console.log(body);
response(callback, 200, { mediaUrn });
}
}));
Documentation page that I've followed: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/rich-media-shares
#linkedin

The request method is supposed to be POST but you are sending PUT instead, below code should work.
const options = {
headers: {
'Authorization': `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'multipart/form-data'
},
method: 'post',
url: mediaUploadUrl
}
fs.createReadStream(filePath).pipe(request(options, function(err, httpsResponse, body) {
if ( err ) {
console.log('err', err);
response(callback, 400, err);
} else {
console.log(body);
response(callback, 200, { mediaUrn });
}
}));

Related

Getting ugcPost details through rest/posts api?

I could not get the ugcPost of a post or comment, the urn looks like: urn:li:ugcPost:7023566176156811264,7023567581345140736
how to use this in the api rest/posts/{ugcPosts urn}
the API returns the error {
"message": "Could not find entity",
"status": 404,
"code": "NOT_FOUND"
}
I have also added the headers
{
Linkedin-Version: 202210,
X-RestLi-Protocol-Version: 2.0.0
}
but it is still returning the same error even though I have encoded the urn, example:
https://api.linkedin.com/rest/posts/urn%3Ali%3AugcPost%3A7023566176156811264?viewContext=Reader
You need to add a bearer token in the header. And viewContext=Reader params is not required as per my knowledge of the documentation. I am sharing a sample example.
var axios = require('axios');
var config = {
method: 'get',
url: 'https://api.linkedin.com/rest/posts/urn%3Ali%3AugcPost%3A7023566176156811264',
headers: {
'X-Restli-Protocol-Version': '2.0.0',
'LinkedIn-Version': '202208',
'Authorization': 'Bearer [your_bearer_token]',
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
You can visit this link for more information.

Translating curl command to Meteor's HTTP call

I try to "translate" this curl command
curl --request POST --header "Content-Type: application/json" --url http://some-url --user userName:apiKey --data '{ "some": "JSON data as string" }'
into Meteor's HTTP call. I tried this:
const options = {
{ "some": "JSON data as object" },
headers: {
'Content-Type': 'application/json',
},
params: {
user: 'userName:apiKey',
},
// Or alternatively
//
// user: 'userName:apiKey',
};
HTTP.call('POST', 'http://some-url', options, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
With curl command it works fine, with HTTP.call I get a 403, Forbidden. Authorization with userName:apiKey seems to fail. How do I specify the userName:apiKey in the HTTP.call example? Or maybe their is another problem?
If you need authentication, you need to add the auth parameter. The params parameter will actually set all the containing properties to be part of the POST request body.
const options = {
data: { "some": "JSON data as object" },
headers: {
'Content-Type': 'application/json',
},
auth: 'userName:apiKey'
}
Read: https://docs.meteor.com/api/http.html#HTTP-call

How to get a more explicit error message when a fetch failed?

I'm on React Native, and
I have a code like this :
fetch('http://someurl.com', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
...dataSample
}),
})
.then(response => console.log(response))
.catch(error => console.error(error))
The request always go in the catch, with this error result :
{ [[object Error]]
line: 24055,
sourceURL: 'http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false' }
NB: When i do a request to the same url/params with postman, the url work very well.
My question is : How can i debug this? and get more explicit error message?

linkedin API cannot create campaign

We have got rw_ads permissions for an app. Through that app We have taken access_token with all given permissions.
As mentioned in the documentation, we have rw_ads permission, but If we try to create/update campaign we are getting the below error.
{
"serviceErrorCode": 100,
"message": "Not enough permissions to access: POST /adCampaignsV2/sdafnk",
"status": 403 }
var request = require("request");
var options = { method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2/sdafnk',
headers:
{ 'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json' },
body:
{ patch:
{ '$set':
{ runSchedule: { end: 1548405000000, start: 1547713800000 },
status: 'ACTIVE' } } },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Code for creation of campaign is mentioned below
var request = require("request");
var options = {
method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2',
headers: {
'Authorization': 'Bearer <accessToken>',
'Content-Type': 'application/json'
},
body: {
account: 'urn:li:sponsoredAccount:<accountId>',
audienceExpansionEnabled: false,
costType: 'CPM',
creativeSelection: 'OPTIMIZED',
dailyBudget: { amount: '200', currencyCode: 'INR' },
locale: { country: 'IN', language: 'en' },
name: 'Campaign text ad test',
objectiveType: 'WEBSITE_TRAFFIC',
offsiteDeliveryEnabled: false,
runSchedule: { end: 1547708400000, start: 1547967600000 },
type: 'TEXT_AD',
unitCost: { amount: '10', currencyCode: 'INR' },
status: 'PAUSED'
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
When you perform a partial update, the header X-RestLi-Method must be included in the request and set to PARTIAL_UPDATE.
Also if you use implicit grant-type, check if you have defined the scope correctly at the start. if you use client-credentials grant-type check if the account has the right permissions.
Direct Sponsored Content can be created by:
Ad Account Users with a role higher than VIEWER. Organization users
with DIRECT_SPONSORED_CONTENT_POSTER or ADMINISTRATOR roles.
also the code you added in this question is for Reactivating a campaign. not for updating/creating one.

HTTP Status 403 - Bad or missing CSRF value but the csrf token is set

I have an ajax request which looks like this:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'url': defaults.addToCartUrl,
'data': JSON.stringify({CSRFToken: Config.CSRFToken,currentUser: currentCustomer, entries: cartItems}),
'type': 'POST',
'dataType': 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRFToken', Config.CSRFToken);
},
'success': function (data, textStatus, jqXHR) {
},
'error': function (jqXHR, exception, m) {
console.log('Cannot move products from
}
});
The problem is that I keep getting this HTTP Status 403 - Bad or missing CSRF value but I set the token as a parameter in the data payload as well as on the request header.
Isn't the beforeSend supposed to set the token to "X-CSRF-Token"? Maybe use ajaxSetup for your headers?
Example:
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});

Resources