Linkedin v2 API Image upload get error 400 Bad Request - node.js

When I am trying to upload an image using LinkedIn v2 API every time I get a 400 Bad request error.
Reference is taken from Here : Link
Steps I perform in postman:
Step 1:
API: https://api.linkedin.com/v2/assets?action=registerUpload,
Request: POST,
Headers: Authorization: Bearer token, Content-Type: 'application/json', X-Restli-Protocol-Version: '2.0.0'
Request:
{
"registerUploadRequest":{
"owner":"urn:li:organization:724981XXX",
"recipes":[
"urn:li:digitalmediaRecipe:feedshare-image"
],
"serviceRelationships":[
{
"identifier":"urn:li:userGeneratedContent",
"relationshipType":"OWNER"
}
],
"supportedUploadMechanism":[
"SYNCHRONOUS_UPLOAD"
]
}
}
Response: Get uploadUrl
Step2:
End point: uploadURL<from step1's response>,
Request: PUT,
Headers: Authorization: Bearer token, Content-Type: 'image/jpeg', X-Restli-Protocol-Version: '2.0.0', media-type-family:'STILLIMAGE<from step1's response>'
Body: <base_64>
Response: 400 Bad Request
Via curl request working fine.
What I am doing wrong?
Thanks in advance.

'Authorization': Bearer ${ access_token },
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'image/jpg'
body is simply the image file contents or a BLOB
method: POST - worked for me... for some PUT worked

Related

How to solve the error CORS ? mode: 'no-cors'

const result = await fetch(https://example.com', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({"username": "Jochan","countFollowers": 60001}),
});
I am trying to send a request to a third-party API, an error arrives, how can I solve it?
Error:
POST https://example.com net::ERR_ABORTED 500 (Internal Server Error)
you are not authorized to get a response from an API that does not have the appropriate headers set. If it is neither yours API nor public one, you can only try some hacks with CORS proxies from google search

Polar accesslink API POST users not working

I'm currently trying to implement Polar accesslink API on an app, but when trying to POST a new user I still get this error:
url: 'https://www.polaraccesslink.com/v3/users/',
status: 400,
statusText: 'Bad Request',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
I already have the authorization token, which I know expires every 10min, and I'm using the service through a function that takes the token and the userID as parameters. This is my code:
postUser(memberId: string, token: string) {
const inputBody = { 'member-id': memberId };
const headers = {
'Content-Type': 'application/xml', 'Accept': 'application/json', 'Authorization': 'Bearer ' + token
};
const options = {
method: "POST",
headers: headers,
body: JSON.stringify(inputBody)
}
return new Promise<object>((resolve, reject) => {
fetch('https://www.polaraccesslink.com/v3/users', options)
.then(function(res: any) {
console.log(res)
return res.json();
}).then(function(body: any) {
console.log(body);
});
})
}
I'm implementing it the same way as it is specified in https://www.polar.com/accesslink-api/?javascript--nodejs#users but really don't know what might I be doing wrong. Thanks for helping me!.
I don't have experience with this specific API but i can see you send in the header Content-Type the value application/xml but the request body is JSON formatted.
Try send application/json in that header.
The Content-Type header is used in HTTP to specify the body mime type.
more info in: Content-Type HTTP Header - MDN
I also see this is the exact code in the sample but notice they have 2 sample requests and 2 sample results, one in XML and one in JSON each.
Any ideea why this POST gives 'invalid_Request'?
curl --location --request POST 'https://polarremote.com/v2/oauth2/token?grant_type=authorization_code&code=1f9edc0c5e60a0bab4fd3f1f00571a58' --header 'Authorization: Basic ... DA4OS05ZDc2LTJlNTQwZjFkZTc5ZA==' --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json'

axios equivalent of http requests?

I want to make the following http request
POST /v1/images HTTP/1.1
Host: api.medium.com
Authorization: Bearer 181d415f34379af07b2c11d144dfbe35d
Content-Type: multipart/form-data; boundary=FormBoundaryXYZ
Accept: application/json
Accept-Charset: utf-8
--FormBoundaryXYZ
Content-Disposition: form-data; name="image"; filename="filename.png"
Content-Type: image/png
IMAGE_DATA
--FormBoundaryXYZ--
It is Medium API
I have attempted following.
var axios = require("axios")
var data = (await axios("https://example.com/image.png")).data;
axios.post("https://api.medium.com/v1/images",{image: data},{
headers: {
"Content-Type" : "multipart/form-data",
"Authorization" : "Bearer " + process.env.key
}
}).then(x=>console.log(x.data))
And I get following error.
Error: Request failed with status code 400
It uses Medium API to upload image, I want to fetch a remote image, and convert it into multipart/form-data and upload it via API, the HTTP request seems confusing, I want the equivalent axios code, someone please help?
Try using FormData instead of plain object?
Example should be like this
const formData = new FormData();
formData.append('image', data);
axios.post('https://api.medium.com/v1/images', formData, {
headers: {
"Content-Type" : "multipart/form-data",
"Authorization" : "Bearer " + process.env.key
}
});
Reference: How to post a file from a form with Axios

Reddit gives 403 when upvoting via API

I've registered as the Web app as required by the Reddit API for the Oauth access with identity, edit, flair, history, modconfig, modflair, modlog, modposts, modwiki, mysubreddits, privatemessages, read, report, save, submit, subscribe, vote, wikiedit, wikiread scopes.
I'd authorized my app and have exchanged the generated code for the access_token with 3600 seconds validity.
'use strict';
let request = require('request');
const USER_AGENT = 'web:com.example.server:v0.0.1 (by /u/sridharrajs)';
const token = '<my access_token within 3600 seconds validity>';
request({
method: 'POST',
url: 'https://www.reddit.com/api/vote',
headers: {
'User-Agent': USER_AGENT,
'Authorization': `bearer ${token}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
id: "t1_9qy47p",
dir: "1"
},
json: false
}, function (error, response, body) {
if (error) {
console.log('error', error);
} else if (body.error) {
console.log('body.error', body);
}
return console.log(body);
});
But when I try to upvote a reddit submission using API, I get an error.
{"message": "Forbidden", "error": 403}
The link that I'm trying to upvote is Tim Cook warns of ‘data-industrial complex’ in call for comprehensive US privacy laws
I tried switching both bearer and Bearer as per the answer in Reddit API returns HTTP 403, and tried using different User-Agent as suggested in 403 error when trying to get data from Reddit API. Nothing seem to work.
What am I missing?
Solved. I need to use https://oauth.reddit.com instead of www.reddit.com.
You may now make API requests to reddit's servers on behalf of that user, by including the following header in your HTTP requests:
Authorization: bearer TOKEN
API requests with a bearer token should be made to https://oauth.reddit.com, NOT www.reddit.com.

Google API returns 400 BadRequest for batch request

I'm trying to send bath request to GMail API using request for nodejs. The problem is even trough I generate the same query as in documentation, gmail always respond with 400 BadRequest
Those are my headers in form of json
{ 'Content-Type': 'multipart/mixed; boundary=c2db2692-8877-4159-bf02-03e6c5d3ffbf',
authorization: 'Bearer MY_TOKEN',
'content-length': 231 }
Example of body content
--c2db2692-8877-4159-bf02-03e6c5d3ffbf
Content-Type: application/http
Content-ID: <item1:12930812#barnyard.example.com>
GET /gmail/v1/users/sneg0k32#gmail.com/messages/14c6c0c43e9bb16b
--c2db2692-8877-4159-bf02-03e6c5d3ffbf--
Any suggestions why this happens? Request generates extra few spaces and make headers in lowercase, however I'm not sure if this is the problem.
Example of nodejs code
request({
method: 'POST',
uri: 'https://www.googleapis.com/batch',
auth: {
bearer: key
},
headers: {
'Content-Type': 'multipart/mixed'
},
multipart: _.map(queries, function(query) {
return {
'Content-Type': 'application/http',
'Content-ID': "<item1:12930812#barnyard.example.com>",
body: 'GET ' + query
}
})
}, function(error, response, body) {
console.log(response.request.headers)
_.map(response.request.body, function(chunk) {
console.log(chunk.toString())
})
console.log(body)
})
UPD: This is clearly an issue with how I make my node call, send same request via HTTPTester and everything worked fine
UPD2: Decided to use bachelor, however I haven't figured what was causing this issue with plain request
Quite hard to troubleshoot such a problem. I would more than likely say it's down to the spaces. I had a similar issue that was because the request body was seen as invalid due to it's structure.
Uppercase or lowercase headers shouldn't cause an issue.
If it helps I've created a node module to creating batch requests: https://www.npmjs.com/package/batchelor. Feel free to use it.

Resources