POSTMAN PUT request not updating values - javascript

Assuming the position of the API tester of https://imgur.com/ , Im testing the PUT request to change account settings.
I am following this api doc
Link for above https://apidocs.imgur.com/#7bc88d39-d06d-4661-afff-38ea5b9a1d0a
Steps to check this
Add the relevant info as below, I am setting show_mature and newsletter_subscribed to true
2. Set the Access token
3. Click on send
the response for this is 200 as shown below
Check if the details have updated as shown in the following screenshot
Expected: To have show_mature and newsletter_subscribed values set to true
Actual: show_mature and newsletter_subscribed values are false
Would be really appreciated if someone could let me know why this is happening? Thanks

From the Imgur API docs...
Need help?
The Imgur engineers are always around answering questions. The quickest way to get help is by posting your question on StackOverflow with the Imgur tag.
Real helpful Imgur 🙄.
Answering here to provide a canonical answer in the imgur tag for this nonsense.
All the API examples in the documentation use some form of multipart/form-data request body payloads. Eg
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer {{accessToken}}");
var formdata = new FormData();
var requestOptions = {
method: 'PUT',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("https://api.imgur.com/3/account/{{username}}/settings", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
and
curl --location --request POST 'https://api.imgur.com/oauth2/token' \
--form 'refresh_token="{{refreshToken}}"' \
--form 'client_id="{{clientId}}"' \
--form 'client_secret="{{clientSecret}}"' \
--form 'grant_type="refresh_token"'
With the exception of any upload related endpoints, this is ABSOLUTELY INCORRECT. Passing data as multipart/form-data requires the API to handle that request content-type and guess what, the Imgur API does not.
What they do accept is application/x-www-form-urlencoded.
In Postman that's the x-www-form-urlencoded option, not form-data
In cURL that's the -d option, not --form
In JavaScript that's URLSearchParams, not FormData

Related

how to put --data in GET method ? since GET not recieving body parameter

i've given the api endpoint with GET method but i think it needs a body, when i test it on postman it works fine but in react native when i try to fetch it it shows error [TypeError: Body not allowed for GET or HEAD requests]
my backend partner send this curl, how to use the --data since GET are not recieving any body
curl --request GET \
--url http://base_url/api/v2/order/all \
--header 'Content-Type: application/json' \
--cookie 'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZU51bWJlciI6IjA4ODc3NzA5MjIxIiwidXNlcm5hbWUiOiJGbG8iLCJpYXQiOjE2NTEwMzIxNTYsImV4cCI6MTY1MTA3NTM1Nn0.JkwTPvjig7bd8Q27MvZ7DsUCz68Qyzh3EctFTRh-m0E; connect.sid=s%253AgtaL-l_60sBGAdEhTiHspbzX3rBBiEFg.O5z0JBi7Oqo1UXSZOxQckm2FNhG3A%252BWZod951CC5Cys' \
--data '{
"userId":"79025884",
"limit":10,
"page":1
}'
this is my function
function GetActivity() {
const url = APIConfig.SERVER.ORDER + "/all";
fetch(url, {
method: "GET",
headers: { "content-type": "application/JSON" },
body: JSON.stringify({
userId: "79025884",
limit: 10,
page: 1,
}),
})
.then((response) => response.json())
.then((data) => {
console.log("GetActivity Order:", data);
setOrderList(data.data);
})
.catch((error) => {
console.error("Error:", error);
});
}
For a GET request, any parameters you want to pass to the API end point will need to be sent as part of the url I believe.
E.g. http://example.com/id/1 (where 1 is the dynamic value for the ID parameter)
I think the error you are seeing is because your trying to set a "body" value for a get request, which would be used with a POST request instead for example.
The same problem I faced several days ago, and I made some research about it. I can say that even though it is possible to use get method with body in postman you can't use get method with body with fetch or axios, because body is not allowed. And I think you should allow post method in your backend if your want to send data. You can read in depth about it here.
You need to add it to the URI or the HTTP request headers depending on the data. Usually URI path for hierarchical resource identification data and URI query for non-hierarchical. There are standard HTTP headers for many things including pagination. https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests They are for byte ranges, but you can use custom units like pages. Another way is doing pagination with URI.
GET https://example.com/api/v1/orders/by-user-id/79025884/?page=1&limit=10
GET https://example.com/api/v1/orders/by-user-id/79025884/ "Range: items=1-10"

YouTubeAPI: How to upload thumbnail (JS)

I tried uploading thumbnail on youtube using this guide: https://developers.google.com/youtube/v3/docs/thumbnails/set
I was able to successfully run it on postman using this curl:
curl --location --request POST 'https://www.googleapis.com/upload/youtube/v3/thumbnails/set?videoId=<video id>' \
--header 'Authorization: OAuth <token>' \
--header 'Content-Type: image/png' \
--form 'thumbnail=#"/C:/Users/user/Pictures/nami.PNG"'
However I have trouble translating that into js, what I did so far is:
// the "file" is the File from <input type="file"> - data on this looks ok
uploadThumbnail async (file) {
const formData = new FromData();
const formData.append('thumbnail', file, 'test.png');
await fetch.post('https://www.googleapis.com/youtube/v3/thumbnails/set', {
headers: {
Authorization: 'Oauth <token>',
'Content-Type': 'multipart/form-data' // I also tried using the file.type here (image/png)
},
query: {
videoId: <video id>
},
body: formData,
})
}
(to simplify the logic, I only manually typed the code above, so pardon if there are any typo.)
but this throws The request does not include the image content. I don't understand, I also tried converting the File into Blob, but same error.
As pointed out on the comments on my main post, I combined the answers and came up with this (this works!)
await fetch.post(`https://www.googleapis.com/upload/youtube/v3/thumbnails/set?videoId=${videoId}&uploadType=media`, {
headers: {
Authorization: 'Bearer <token>',
'Content-Type': file.type
},
body: file,
})
Mistakes are:
My endpoint is wrong and is missing uploads (this API is different from other youtube endpoints, so if you are reusing a variable base_url better check it out.
Using Oauth instead of Bearer.
There are no query in fetch
No need to convert and add the formData, pass the file directly instead.

Need help converting cURL command to Javascipt

I am trying to get recipe nutritional information from Edamam API. In the API docs, the cURL command is:
curl -d #recipe.json -H "Content-Type: application/json" "https://api.edamam.com/api/nutrition-details?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"
I am using Axios and Javascript to try to access the API with a Post command:
import axios from "axios";
var postData = './recipe.json'
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',}
};
axios.post('https://api.edamam.com/api/nutrition-details?app_id=XXXXXXXX&app_key=XXXXXXXXXXXXXXXXXXXXX', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
I receive a 400 error back. Any thoughts on what I need to do to make this work would be appreciated.
postData needs to be a string of JSON.
You appear to be passing it a string containing a filename.
You might want to read './recipe.json' with axios.get() to fetch the data from it.
In your cURL the option -d #recipe.json is sending the content of the file recipe.json
But, In your Code postData = './recipe.json', You are just passing the name instead of reading it.
First you need to read the data from recipe.json,Then you need to send it through request.

Getting error 415 - Unsupported media Type in fetch api

Following curl request is working and it's generating token. But when I use it as fetch API, I'm getting 415 error - Unsupported media type.
curl -k -X POST -H "Content-Type: application/x-www-form-urlencoded" -u "Secret_ID:Secret_Key" -d "grant_type=password&username=mahesh#gmail.com&password=Welcome1234&scope=https://si01-test.prod.com/bca/api" "https://identity.com/oauth2/v1/token"
I'm using fetch API like this:
let username = 'Secret_ID';
let password = 'Secret_Key';
let formdata = new FormData();
let headers = new Headers();
formdata.append('Content-Type','application/x-www-form-urlencoded');
formdata.append('grant_type','password');
formdata.append('username','mahesh#gmail.com');
formdata.append('password','Welcome1234');
formdata.append('scope','https://si01-test.prod.com/bca/api');
headers.append('Authorization', 'Basic VGVzdF9zaTAxX0FQUElEOjNkZGI4MmYxLWI5OTktNDlhMy1hMmM5LWQ1OGMyOTU2ODg4Yg=='); // encoded username and password
fetch('https://identity.com/oauth2/v1/token', {
method: 'POST',
headers: headers,
body: formdata
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
What's wrong here? Any suggestion will be appreciable..
So as I mentioned, Request is working fine in CuRL / Postman and it makes my life easier.
If you you have curl command and its working fine then you can just import that command directly in postman and it will work fine.
Now if your request is working fine in postman, then you can just copy code of it in any language that is given in Postman.

cURL command works, but Fetch API call returns 200 with 400 validation error in Response Payload

Having a huge issue I came across in sending a POST request using Fetch to get a URL shortened.
I am good and able to do a POST request by cURL command to this url shortener API:
Curl command
curl -d 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch' http://fakeurlforexample/api/shorten/
Response
{"url": "https://fakeurlforexample/BdzfM3", "long_url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch", "name": "BdzfM3"}
And I get this great response payload from the API.
But when I do this by Fetch with this code I provided below, I get a 200 OK and in the response payload I have a 400 validation error that I am missing the API key.
However, the request payload in the developer console shows that the parameters were passed on properly to the API (I think...)
{"api_key":"xxxxxxxxxxxxxxxxx","url":"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"}
Here is my code:
let get_url = 'http://fakeurlforexample.com/api/shorten/';
let request = new Request(get_url, {
method: 'POST',
body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
});
fetch(request)
.then(function() {
console.log(request);
console.log(request.url);
})
Does anyone see the mistake I am making here?
Been beaten down by this for across hours upon hours this week now. Thanks for any help and assistance! And no, I can't easily transition the code to axios as it is right now. This is a demonstration so I'm really just trying to get it to work.
From the curl manpage Options section on -d, --data <data>:
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.
Whereas with your request, you are sending a JSON object (Content Type: application/json):
let request = new Request(get_url, {
method: 'POST',
body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
});
Since you know the API endpoint accepts application/x-www-form-urlencoded because the curl request succeeds, you can set the content type as application/x-www-form-urlencoded and send the body as a string:
let request = new Request(get_url, {
method: 'POST',
headers: new Headers({'content-type': 'application/x-www-form-urlencoded'}),
body: 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'
});
Maybe its because you are defining headers 2 times.

Categories

Resources