Passing parameters to Guzzle post request - post

I am trying to pass some parameters to Guzzle post request based on the API instructions below, but I get a bad request error msg, I have specified the database ID, but it still shows on the error msg.
INSTRUCTIONS:
To query for SQL statement results, send a POST to /api/dataset/. The request body value for query should be of the format {"database":2,"type":"native","native":{"query":"SELECT * FROM s_mystudy.participant","template_tags":{}},"parameters":[]}, where 2 is the database ID found >earlier, and the inner "query" value is the SQL statement to execute; in this case it is SELECT * >FROM s_mystudy.participant.
The keys for "parameters" and "template_tags" relate to the use of variables and filters, which >are used in reports created in Metabase. However in this context the simplest approach would be >to vary the provided SQL statement to include the appropriate parameters.
ERROR:
PHP Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: POST https://ccs.insight.openclinica.io/api/dataset/?database=10&type=native&native%5Bquery%5D=select%20%2A%20from%20s_sdms_dsgtest.participant resulted in a 400 Bad Request response:
{"via":[{"type":"clojure.lang.ExceptionInfo","message":"database is required for all queries whose type is not `intern (truncated...)
WHAT I HAVE:
$params = [
'headers' => $auth_headers,
'query' => [
"database" => 10,
"type" => 'native',
"native"=> [
"query"=>"select * from s_sdms_dsgtest.participant"]]
//'template_tags'=>[]],
//'parameters'=>[]]
];
$databases = $client->post('api/dataset/json', $params);

Related

Is there a way to trigger Jenkins parameterized jobs by sending JSON for the params - without using a query param string?

I am using python to trigger a Jenkins job. Right now I'm using python requests lib; I trigger the job directly as:
response = requests.post("https://jenkinsurl/job/myJob/buildWithParameters", auth=(user, password), verify=False)
I need to send build parameters to the job. All tutorials I see, indicate to send the paramaters as a query string on the job URL (example - if I wanted to send params 'param1' with 'val1' and 'param2' with 'val2', I'd post as follows:)
response = requests.post("https://jenkinsurl/job/myJob/buildWithParameters?param1=val1&param2=val2", auth=(user, password), verify=False)
The problem is that I need to send sensitive params, which I can't supply in plaintext as part of an URL. Is there a way to send the params as part of the post body? I can't seem to find the syntax/structure the json would need be in, to accomplish this.
I was able to get this to work by passing the params directly to the 'data' option in requests.
So in the example above (to send params 'param1' with value 'val1' and 'param2' with value 'val2' to the Jenkins job, this worked:)
var jobParams = {'param1': 'val1', 'param2': 'val2'}
response = requests.post("https://jenkinsurl/job/myJob/buildWithParameters, data=jobParams, auth=(user, password), verify=False)
EDIT: If you are facing this issue, make sure not to solve it by sending the params to requests' 'params' arg - it will work (trigger the job with the params) but all it's doing is generating the query string for you - those param/values would still get tacked on the URL

Swapping Rails 4 ParamsParser removes params body

I'm trying to follow this solution to add a params parser to my rails app, but all that happens is that I now get the headers but no parameters from the body of the JSON request at all. In other words, calling params from within the controller returns this:
{"controller"=>"residences", "action"=>"create",
"user_email"=>"wjdhamilton#wibble.com",
"user_token"=>"ayAJ8kDUKjCiy1r1Mxzp"}
but I expect this as well:
{"data"=>{"type"=>"residences",
"attributes"=>{"name-number"=>"The Byre",
"street"=>"Next Door",
"town"=>"Just Dulnain Bridge",
"postcode"=>"PH1 3SY",
"country-code"=>""},
"relationships"=>{"residence-histories"=>{"data"=>nil},
"occupants"=>{"data"=>nil}}}}
Here is my initializer, which as you can see is almost identical to the one in the other post:
Rails.application.config.middleware.swap(
::ActionDispatch::ParamsParser, ::ActionDispatch::ParamsParser,
::Mime::Type.lookup("application/vnd.api+json") => Proc.new { |raw_post|
# Borrowed from action_dispatch/middleware/params_parser.rb except for
# data.deep_transform_keys!(&:underscore) :
data = ::ActiveSupport::JSON.decode(raw_post)
data = {:_json => data} unless data.is_a?(::Hash)
data = ::ActionDispatch::Request::Utils.deep_munge(data)
# Transform dash-case param keys to snake_case:
data = data.deep_transform_keys(&:underscore)
data.with_indifferent_access
}
)
Can anyone tell me where I'm going wrong? I'm running Rails 4.2.7.1
Update 1: I decided to try and use the Rails 5 solution instead, the upgrade was overdue anyway, and now things have changed slightly. Given the following request:
"user_email=mogwai%40balnaan.com
&user_token=_1o3Kpzo4gTdPC2bivy
&format=json
&data[type]=messages&data[attributes][sent-on]=2014-01-15
&data[attributes][details]=Beautiful+Shetland+Pony
&data[attributes][message-type]=card
&data[relationships][occasion][data][type]=occasions
&data[relationships][occasion][data][id]=5743
&data[relationships][person][data][type]=people
&data[relationships][person][data][id]=66475"
the ParamsParser middleware only receives the following hash:
"{user":{"email":"mogwai#balnaan.com","password":"0h!Mr5M0g5"}}
Whereas I would expect it to receive the following:
{"user_email"=>"mogwai#balnaan.com", "user_token"=>"_1o3Kpzo4gTdPC2b-ivy", "format"=>"5743", "data"=>{"type"=>"messages", "attributes"=>{"sent-on"=>"2014-01-15", "details"=>"Beautiful Shetland Pony", "message-type"=>"card"}, "relationships"=>{"occasion"=>{"data"=> "type"=>"occasions", "id"=>"5743"}}, "person"=>{"data"=>{"type"=>"people", "id"=>"66475"}}}}, "controller"=>"messages", "action"=>"create"}
The problem was caused by the tests that I had written. I had not added the Content-Type to the requests in the tests, and had not explicitly converted the payload to JSON like so (in Rails 5):
post thing_path, params: my_data.to_json, headers: { "Content-Type" => "application/vnd.api+json }
The effects of this were twofold: Firstly, since params parsers are mapped to specific media types then withholding the media type meant that rails assumed its default media type (in this case application/json) so the parser was not used to process the body of the request. What confused me was that it still passed the headers to the parser. Once I fixed that problem, I was then faced with the body in the format of the request above. That is where the explicit conversion to JSON is required. I could have avoided all of this if I had just written accurate tests!

What is the expected JSON Block for a desire2learn POST Org Parent?

I believe I have tried all combinations to POST to this route and continue to get a 404. What am I doing wrong?
I want to set the parent of a courseOffering to a different, but existing courseTemplate. The courseOffering orgUnitId is 31273, the new parent (courseTemplate) orgUnitId is 31286. The route is use is:
POST .../d2l/api/lp/1.2/orgstructure/31273/parents/
(also tried without the trailing /)
The JSON Block is:
{"OrgUnitId":31286}
I have also tried Id and Identifier instead of OrgUnitId and a string, "31286" instead of an int and orgUnitId (lower case) - all result in 404.
fwiw, a get with the same route works just fine.
cwt
from the Valence docs:
POST /d2l/api/lp/(version)/orgstructure/(orgUnitId)/parents/
Give the provided org unit a new parent org unit.
Parameters:
version (D2LVERSION) – API version.
orgUnitId (D2LID) – Org unit ID.
JSON Parameters:
OrgUnitId (D2LID as single JSON number) – Org unit to add as a parent.
The docs say that the expected input data for this POST is an org unit ID value provided as "a single JSON number".
When you say you're passing:
{"OrgUnitId": 31286}
what you're providing is a JSON object (composite) with a single property, named "OrgUnitId" that has a JSON number value. In fact, what you should provide is:
31286
But you should still indicate this is a JSON body, so you should set the HTTP request Content-Type header to application/json). Here's an excerpt from an interactive session successfully making this call; we dump the various components of the HTTP response/request object for you (r is the response, r.request is the original request that prompted the response):
In [40]: r.request.method
Out[40]: 'POST'
In [41]: r.request.url
Out[41]: 'https://{host}/d2l/api/lp/1.1/orgstructure/8083/parents/?x_b={user_id}&x_c={app_sig}&x_a={app_id}&x_d={user_sig}&x_t=1391183251'
In [42]: r.request.headers
Out[42]: CaseInsensitiveDict({'Content-Length': '4', 'User-Agent': 'python-requests/2.2.1 CPython/3.3.3 Darwin/12.5.0', 'Content-Type': 'application/json', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, compress'})
In [43]: r.request.body
Out[43]: '6984'
In [44]: r.status_code
Out[44]: 200
Course offerings and course templates have a special relationship in that every course offering must have a course template as a parent. You might be able to first add the new course template as a parent to the course offering, and then delete the old one, or the back-end service might just not let you sever off a course template from a course offering at all.

adding data to fusion tables using an url in a browser

I have been trying to read/write from/to a fusion table directly from my browser using different urls. For Reading a use "https://www.googleapis.com/fusiontables/v1/query?sql=SELECT * FROM WHERE ID = '1' &key=" This works well and i can read data in Json.
For inserting data i use "https://www.googleapis.com/fusiontables/v1/query?sql=INSERT INTO (ID, Adress) VALUES (1, 'Prästkragsvägen 33') &key=" In this case i get the following error:
"domain": "fusiontables",
"reason": "cannotWriteDataOnGetRequests",
"message": "The operation is not supported for GET requests. Please try again using POST."
"code": 501
The table is set to public. How should the url for an INSERT command look like?
Regards
Alfred
For inserts and updates into fusiontable you will need POST requests. Your browser's address bar only does get requests.
You could try console with jquery $.ajax or curl in a terminal

Trouble handling HTTP responses and parsing JSON data

I am using Ruby on Rails 3 and I would like to solve an issue with the following code where a web client application receive back some JSON data from a web service application that uses a Rack middleware in order to respond.
In the web client app model I have
response_parsed = JSON.parse(response.body)
if response_parsed["account"]
...
else
return response
end
In the above code the response.body come back from the web service app that uses a Rack middleware to respond to the web client:
accounts = Account.where(:id => ids)
[200, {'Content-Type' => 'application/json'}, accounts.to_json] # That is, response.body = accounts.to_json
Data transmission is ok, but I get the following error
TypeError
can't convert String into Integer
*Application Trace*
lib/accounts.rb:107:in `[]'
The line 107 corresponds to
if response_parsed["account"]
...
Where and what is the problem? How to solve that?
If I try to debug the respons.body I get
# Note: this is an array!
"[{\"account\":{\"firstname\":\"Semio\",\"lastname\":\"Iaven\"\"}}]"
If I'm saying something you already realize, forgive me.
It looks like your response is a one-element array with a hash in it as the first element. Because the response is an array, when you use the [] it is expecting a integer representing the index of the item in the array you'd like to access, and that is what the error message means--it expected that you'd tell it the integer value of the item you wanted, but instead you gave it a string.
If you instead do:
response_parsed[0]['account']
It seems like you'd get what you want.

Resources