I'm trying to change a password over a rest interface with rest-client.
With the instructions shown below a basic authentication is required.
I think I implemented the basic authentication right in my request. My problem is that I don't know how I should set a new Password in the requestBody
The instructions, example:
URL: {base_url}/accounts/{uid}/password
HTTP-Method: POST
Request Body: text/plain
Response Body: text/plain
HTTP Status Code: 201, 400
Entitlement: Owner
Request:
POST /accounts/345/password HTTP/1.1
Content-Type: text/plain;charset=UTF-8
newPassword
Response:
Status Code: 201 Created
My code:
#response = RestClient::Request.new(
:method => :post,
:url => 'https://zomgo.de:7849/server/rest/accounts/50s89c-a76b-475/password',
:user => 'hrums80',
:password => 'mzsdfr4',
:newPassword => 'Amerika69'
).execute
With this code I get the following error:
Http 415 unsopported media type
Can someone say me how I can set a new password in the request body ? And what's the meaning of that error. Thanks
Related
First, if this question is badly formed, I apologize.
In simple terms, the API server documentation that I'm trying to connect to provides this guidance:
Authentication Workflow The authentication workflow comprises of two steps:
Use your refresh token to get a client-scoped access token
Use the client-scoped access token to access resources
I'm stuck at step one.
I am using Guzzle 6.x and trying to authenticate via OAuth2.
Using Postman, I able to obtain the access token easily. I'd like to do this in my code using Guzzle. (or whatever it takes).
Postman generated the following PHP HttpRequest snippet. Can I do that with Guzzle? (does the question even make sense?)
<?php
$request = new HttpRequest();
$request->setUrl('https://api-tra/v3/partners/oauth2/token');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'cache-control' => 'no-cache',
'Connection' => 'keep-alive',
'Content-Length' => '559',
'Accept-Encoding' => 'gzip, deflate',
'Content-Type' => 'multipart/form-data; boundary=--------------------------158986490184667130446156',
'Host' => 'api-train.daxko.com',
'Postman-Token' => '28b9d8ac-d0ae-4036-9a61-202e9b39b220,f89cb196-9ada-4c1a-92f7-afc322fec03b',
'Cache-Control' => 'no-cache',
'Accept' => '*/*',
'User-Agent' => 'PostmanRuntime/7.19.0',
'Authorization' => 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3yYWluLWF1dGgiLCJzdWIiOiJmbWN3ZWJzaXRlX3RyYWluIiwiaWF0IjoxNTcwNTQ4OTE3LCJleHAiOjE1NzA1NDg5MTcsImFwaSI6Im9wc19hcGlfdjJfYXV0aCJ9.EnbGN121Ei5hlkPFT6Iqyd1h9_WXDGKplu5RsCH5QZs',
'content-type' => 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
));
$request->setBody('------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="grant_type"
client_credentials
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="client_id"
fmcwebsite_train
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="client_secret"
blC}g!!E#{+_k.VLH
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="scope"
client:2069
------WebKitFormBoundary7MA4YWxkTrZu0gW--');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
You are using client credentials and in that flow refresh tokens are not typically used. Instead just send the access token to the API. If you use the token for long you may also need to check for a 401 response status when you call the API. If so then re-authenticate and call the API again with a new access token.
Ruby rest client is not able to send headers, my java service is not able to read headers when I trigger post request from ruby as below. My Service layers throws error Header companyID is missing. When run the same http request in Postman it works.
response = RestClient::Request.new({
method: :post,
url: 'https://example.com/submitForm',
headers:{content_type: 'application/x-www-form-urlencoded',
companyID:'Company1',
Authorization:'Basic HELLO1234'},
payload: { data: str_res}
}).execute do |response, request, result|
case response.code
when 400
[ :error, JSON.parse(response.to_str) ]
when 200
[ :success, JSON.parse(response.to_str) ]
puts request.headers
else
fail "Invalid response #{response.to_str} received."
end
end
Here is postman code that works. Need similar in Ruby Rest, pls advise.
POST /submitForm HTTP/1.1
Host: example.com
companyID: Company1
Authorization: Basic HELLO1234
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 528cafa1-2b5d-13a1-f227-bfe0171a9437
data=My Own data
Below worked. Looks like headers should be in same line.
payloadString = "data=My Own data"
response = RestClient::Request.new({
method: :post,
url: 'https://example.com/submitForm',
payload: payloadString,
headers: {content_type: 'application/x-www-form-urlencoded', companyID:'Company1', Authorization:'Basic HELLO1234'}
}).execute do |response, request, result|
case response.code
when 400
[ :error, JSON.parse(response.to_str) ]
when 200
[ :success, JSON.parse(response.to_str) ]
else
fail "Invalid response #{response.to_str} received."
end
end
Try using the RestClient post method:
result = RestClient.post(
'https://example.com/submitForm',
payload,
{
content_type: 'application/x-www-form-urlencoded',
companyID: 'Company1',
Authorization: 'Basic HELLO1234'
}
)
Payload in this instance is a string, so you'll need to figure out the appropriate structure for application/x-www-form-urlencoded. For example:
payload.to_json => '{"data": "str_res"}'
Looking at the docs there aren't any good examples of how to make a POST request. I need to make a POST request with a auth_token parameter and get a response back:
response = RestClient::Request.execute(method: :post,
url: 'http://api.example.com/starthere',
payload: '{"auth_token" : "my_token"}',
headers: {"Content-Type" => "text/plain"}
)
400 bad request error:
RestClient::BadRequest: 400 Bad Request
from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/abstract_response.rb:74:in `return!'
from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/request.rb:495:in `process_result'
from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/me/request.rb:421:in `block in transmit'
Any good examples how to make a POST request using RestClient?
EDIT:
This is how I make the request in the model:
def start
response = RestClient::Request.execute(method: :post,
url: 'http://api.example.com/starthere',
payload: '{"auth_token" : "my_token"}',
headers: {"Content-Type" => "text/plain"}
)
puts response
end
Try using a hash like this:
def start
url= 'http://api.example.com/starthere'
params = {auth_token: 'my_token'}.to_json
response = RestClient.post url, params
puts response
end
If you just want to replicate the curl request:
response = RestClient::Request.execute(method: :post, url: 'http://api.example.com/starthere', payload: {"auth_token" => "my_token"})
Both Curl and RestClient defaults to the same content type (application/x-www-form-urlencoded) when posting data the this format.
In case you land here having the same Issue, Just know that this is a common error that happens when your environment variables are not "set".
I put this in quotes because you might have set it but not available in the current terminal session!
You can check if the ENV KEY is available with:
printenv <yourenvkey>
if you get nothing then it means you need to re-add it or just put it in your bash files
FYI: Putting my ENV variables in my ~/.bash_profile fixed it
I'm building an app in Rails using the Spotify web API. I built a method to refresh a user's token, but am receiving a 400 error. According the the Spotify Web API docs, the header of my request needs to be in the following format:
Authorization: Basic <base64 encoded client_id:client_secret>
Using Httparty gem, here's the POST method to refresh the access token:
def refresh_token
client_id = "foo"
client_secret = "bar"
client_id_and_secret = Base64.encode64("#{client_id}:#{client_secret}")
result = HTTParty.post(
"https://accounts.spotify.com/api/token",
:body => {:grant_type => "refresh_token",
:refresh_token => "#{self.oauth_refresh_token}"},
:headers => {"Authorization" => "Basic #{client_id_and_secret}"}
)
end
Here's what "result" ends up being:
=> #<HTTParty::Response:0x7f92190b2978 parsed_response={"error"=>"invalid_client", "error_description"=>"Invalid client secret"}, #response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, #headers={"server"=>["nginx"], "date"=>["Sun, 31 Aug 2014 22:28:38 GMT"], "content-type"=>["application/json"], "content-length"=>["70"], "connection"=>["close"]}>
I can decode client_id_and_secret and it returns "foo:bar", so I'm at a loss as to why I'm receiving a 400 error. Any insight is much appreciated.
Found the issue... it was with the Base64 encoding in Ruby. Apparently (as shown in Strange \n in base64 encoded string in Ruby) using the Base64.encode64('') method adds an extra line within the code. Using Base64.strict_encode64('') solved the issue.
Updated code:
def refresh_token
client_id = "foo"
client_secret = "bar"
client_id_and_secret = Base64.strict_encode64("#{client_id}:#{client_secret}")
result = HTTParty.post(
"https://accounts.spotify.com/api/token",
:body => {:grant_type => "refresh_token",
:refresh_token => "#{self.oauth_refresh_token}"},
:headers => {"Authorization" => "Basic #{client_id_and_secret}"}
)
end
I do this curl in Terminal which works excellent:
$ curl https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000 -H "Authorization: Token xxxxxxxxxxxxxxxxxxxxxx"
Output is json.
Now I want to access the json string via my rails app. I have tried RestClient to do this, but somehow I always get a 401 unauthorized error. I believe the token gets not send correctly via header. I have tried the following:
RestClient.get 'https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000', {token: 'xxxxxxxxxxxxxxxxxxxxxx'}
and
RestClient.get 'https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000', :params => {:token => 'xxxxxxxxxxxxxxxxxxxxxx'}
with no success. Maybe I use a wrong syntax for sending the token in the header?
Doku is here http://rubydoc.info/github/rest-client/rest-client - I could not find any mistakes.
# GET request with modified headers
RestClient.get 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
# POST request with modified headers
RestClient.post 'http://example.com/resource', {:foo => 'bar', :baz => 'qux'}, {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
# DELETE request with modified headers
RestClient.delete 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
Source: https://github.com/rest-client/rest-client#headers