Getting Error for jersey client request headers? - jersey

I need to set these headers for a REST call via jersey client.
clickatell message send rest call
curl -i \
-X POST \
-H "X-Version: 1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer Your Authorization Token" \
-H "Accept: application/json" \
My code is:
Client client = Client.create();
WebResource webResource = client.resource("https://api.clickatell.com/rest/message");
ClientResponse response = webResource
.header("Authorization", "Bearer clickATellAuthKey")
.header("X-Version", "1")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.post(ClientResponse.class, input);
I am getting this error:
{"error":{"code":"001","description":"Authentication
failed","documentation":"http://www.clickatell.com/help/apidocs/error/001.htm"}}
the document says the auth header is not specified. The request is working fine in Postman ( chrome restful client extension) with same headers
Need help.

1) Your headers seem to be going through. If they were not, you would get an error about not setting a version header.
2) The 001 error means your auth token was either not specified, or is incorrect.
3) I suggest that you copy and paste your entire auth token and try again. Watch out for _ or . characters as they are part of the token.

Thanks #whatever_sa there are some improvements required as well in code and also there was an issue with auth key your answer at least make me check the auth key once more. here is the working code
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
.header(MessageServices.API_AUTH_HEADER, MessageServices.AUTH_KEY)
.header(MessageServices.API_VERSION_HEADER, MessageServices.API_VERSION)
.post(ClientResponse.class, input);

Related

How to add Supabase Order by in get request using Postman

I need to add order in supabase result while calling the supabase bash in postman.
I am doing same in flutter like below
Future getPropertiesFromBirmingham() async {
var response = await client
.from('properties')
.limit(10)
.order('created_at', ascending: false);
return response;
}
Need to use same in postman but not getting anything on this.
I didn't find much on this topic, Tried using order in params but it didn't work.
You can get examples of cURL requests directly in Supabase API docs.
You can also check for more documentation directly in the PostgREST website.
curl 'https://supabase_project_ref.supabase.co/rest/v1/properties?limit=10&order=created_at.desc' \
-H "apikey: SUPABASE_KEY" \
-H "Authorization: Bearer SUPABASE_KEY"
You can also control where the NULLs will be (if any) by adding either of the following:
nullslast
nullsfirst
curl 'https://supabase_project_ref.supabase.co/rest/v1/properties?order=created_at.desc.nullslast' \
-H "apikey: SUPABASE_KEY" \
-H "Authorization: Bearer SUPABASE_KEY"

Laravel API: validate doesn't access the PUT request data in my API

Context
I am implementing a user information update using a PUT request in Laravel 8. I use Postman to send the request and see the results.
Expected behavior
My PUT request reaches the controller's function that is censed to update the authenticated user. The latter is updated successfully. So the validate call is executed succesfully and finds the data in the request.
Actual behavior
My PUT request reaches the controller's function that is censed to update the authenticated user. The latter is not updated successfully. In fact, the validate call is executed succesfully but doesn't find the data in the request.
Instead, data validation says:
{
"message": "The given data was invalid.",
"errors": {
"email": [
"The email field is required."
],
"name": [
"The name field is required."
]
}
}
The route & The request
Postman request
curl --location --request PUT 'https://XYZ/api/set_user_data' \
--header 'X-Requested-With: XMLHttpRequest' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer 12|leRLA5yopCLIxe0oN9MMThctqD78iJDjZdZQkcgs' \
--data-urlencode 'email=XYZ#XYZ.FR' \
--data-urlencode 'name=test2'
It means in Postman terminology that no "Params" are sent, an Authorization Bearer token is sent, some Headers are sent and some Body's x-www-form-urlencoded data are sent.
API Route
In routes/api.php:
Route::put('/set_user_data', [UserController::class, 'setUserData'])->name('set_user_data');
UserController::setUserData:
public function setUserData(Request $request) {
if(!Auth::check()) {
return 'unauthenticated.';
}
$request->validate([
'email' => 'required|email',
'name' => 'required|string'
]);
// ... update user here but out of topic
}
What I tried to do... or to not do
Some Stackoverflow answers are: send a POST request and send in the body _method=PUT. I don't want to do this. I really prefer to send a PUT request. Because I am developing an API. It totally justifies the fact that I must use a PUT request and not a PUT one.
Some Stackoverflow answers are: use x-www-form-urlencoded not a simple form. It doesn't fix the problem; moreover it's already the case. Maybe it could help with images sending. (notice I don't want to send any image here).
Question
Why Laravel's validate don't find the data of my request and how to fix it?
You are sending the request as "Content-type: application/json", but you are not sending the body as valid JSON.
You are sending this:email=XYZ#XYZ.FR&name=test2
You should send this:
{"email":"XYZ#XYZ.FR", "name": "test2"}
a valid JSON object

How to correctly pass body to spring rest template?

SOLUTION: The API endpoint to get this specific information is the only one different from all the other ones. Thus I was trying to contact an outdated one.
Everything described in the post works like a charm.
Using kotlin and spring, I want to send a POST request to an API.
This is a curl, generated via postman, that works correctly:
curl --location --request POST 'URL' \
--header 'Content-Type: application/json' \
--data-raw '{
"username":"username",
"password":"password"
}'
However, with spring + rest template using the following code, it seems that the body is not parsed correctly, as the API I am contacting sends me back a 401, that occurs when password/username provided are incorrect/missing.
val body = JwtQuery(getUsername(), getPassword())
return restTemplate.postForObject(url, body, Jwt::class.java)!!
This is the JwtQuery class:
data class JwtQuery (
val username: String,
val password: String
)
Note that getUsername() and getPassword() return the expected value.
What am I doing wrong ?
Edit 1: setting headers
Using:
val body = JwtQuery(getUsername(), getPassword())
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
val bodyEntity = HttpEntity(body, headers)
return restTemplate.postForObject(url, bodyEntity, Jwt::class.java)!!
Still returns the same error (401)
edit 2: marshaled JwtQuery
val body = JwtQuery(mesProperties.getUsername(), mesProperties.getPassword())
val marshaled = ObjectMapper().writeValueAsString(body)
println(marshaled)
Output:
{"username":"username","password":"password"}

Spring RestController only considers the first media type and ignores the rest

#RequestMapping(value = "/test", method = RequestMethod.GET, produces = { "text/plain", "application/json" })
If I send a request:
curl --header "Accept: text/plain, application/json" "http://localhost:8229/test/test"
It sends back a 406 Unacceptable response with HTML response body. Expected Response is a JSON object with 200 OK.
But if I reverse the order of mime-types:
curl --header "Accept: application/json, text/plain" "http://localhost:8229/test/test"
Then it sends the expected response (in JSON).
Is this expected behavior? Why is it ignoring the second media type?
PS: I'm using Spring Boot 1.3.5 release
Edit: I get the same error if I send "Accept: */*". That API can return JSON or text/plain depending upon an internal condition.
I guess it's because of not configuring your web config component in server side. Refer to Content Negotiation to configure it.

Unable to get access token for lyft api

I am trying to use the lyft developer api. I created a new app to get the client Id and client secret . I am following the steps in https://developer.lyft.com/docs/authentication to get an access token in my python code. But I always get the error, "unauthorized client". Can anyone point out my mistake?
def __init__(self):
self.client_id = 'MY_ID'
self.client_secret = 'MY_SECRET'
# obtain access token
self.token = self.__generate_token__()
# define variables to be used in the request parameters
token_val = 'Bearer '+self.token
self.headers = {'Authorization':token_val}
def __generate_token__(self):
url = 'https://api.lyft.com/oauth/token'
# define request parameters
payload = {"Content-Type": "application/json",
"grant_type": "client_credentials",
"scope": "public"}
# request data
res = requests.post(url,
data = payload,
auth = (self.client_id, self.client_secret))
# extract the token from the response
token = res.json()['access_token']
return token
This is a working example for a Java client
https://github.com/yschimke/oksocial/blob/175bdbf66e312d8bdf79183a140c2c5270329cf2/src/main/java/com/baulsupp/oksocial/services/lyft/LyftClientAuthFlow.java
The main thing that looks wrong, is sending "Content-Type" in the POST data body instead of as a header indicating the format of the data.
It looks like from the requests api that you should be sending "json = payload" instead of "data". But I'm not an expert on this python API.
The curl equivalent of the above java code also works
$ ./oksocial --curl --authorize lyft --client
Authorising Lyft API
Lyft Client Id [***********]:
Lyft Client Secret [********************************]:
curl -X POST -H "Authorization:Basic ******************" -H "Connection:Keep-Alive" -H "User-Agent:okhttp/3.5.0" -H "Host:api.lyft.com" -H "Accept-Encoding:gzip" -H "Content-Length:55" -H "Content-Type:application/json; charset=utf-8" -H "Content-Type:application/json; charset=utf-8" -d '{"grant_type": "client_credentials", "scope": "public"}' https://api.lyft.com/oauth/token

Resources