Slim 3 - how to get all get/ put/ post variables? - slim

How I can get all get/ put/ post variables like in Slim 2 for Slim 3?
Slim 2,
$allGetVars = $app->request->get();
$allPutVars = $app->request->put();
$allPostVars = $app->request->post();
How can I do that in Slim 3?
And, for example, http://example.com/books/1?title=hello&content=world
How can I get the params in title and content in Slim 3 now?
Slim 2,
$title = $app->request->get('title');
$content = $app->request->get('content');
How can I do that in Slim 3?

Get all get/put/post parameters:
//GET
$allGetVars = $request->getQueryParams();
foreach($allGetVars as $key => $param){
//GET parameters list
}
//POST or PUT
$allPostPutVars = $request->getParsedBody();
foreach($allPostPutVars as $key => $param){
//POST or PUT parameters list
}
Single parameters value:
//Single GET parameter
$getParam = $allGetVars['title'];
//Single POST/PUT parameter
$postParam = $allPostPutVars['postParam'];

To Get all request params:
$request->getParams()

Request Uri: getQueryParams()
Request Body: getBody()/getParsedBody()
It's not exactly what you are looking for but it comes pretty close.

You can use the map() method to combine get, post & put into a single route.
$app->map(['GET', 'POST', 'PUT'], function(Request $request, Response $response, array $args)) { }
The first argument is an array of the HTTP methods that you want to match. The second parameter is the function that handles the request; pass a request, response and an array of arguments.

Related

Karate Framework- AWS Auth throwing error "the request signature we calculated does not match the signature you provided" [duplicate]

First of all, thanks for build karate it's a very useful for test API's and UI's. We are using it to test a lot of our endpoints but we would like to know if there is a way or which is the best approach to handle requests with signature as part of the request in the header.
In our case we have two headers:
ApiKey: this value is always the same
Signature: this value depends on the request body content
Is there any way to inject the signature value just before the request is executed based on the request body content?
Here you can see two samples of the requests
Sample 1:
* url 'https://dev.sample.com'
* path '/api/user/getAll'
* header Content-Type = 'application/json'
* header ApiKey = 'XXX'
* header Signature = 'YYY'
And request { }
When method POST
Then status 200
Sample 2:
* url 'https://dev.sample.com'
* path '/api/user/getAll'
* header Content-Type = 'application/json'
* header ApiKey = 'XXX'
* header Signature = 'ZZZ'
And request { name: 'John' }
When method POST
Then status 200
Thanks
Karate has a "hook" for generating headers, but as of now it is not "aware" of the currently built request body + headers: https://github.com/intuit/karate#configure-headers
We got a similar request here, and are thinking of adding this capability: How to retrieve raw request contents before making a REST call in Karate DSL?
Maybe the OAuth examples will give you the way forward for your case for now: https://stackoverflow.com/a/55055111/143475
Feel free to raise an enhancement request, and we can get this in to the next version (with your help to test it). I'm thinking - what if you are able to call karate.get('request') from within the header JS function.
But for now all you need to do is do something like this:
* def body = { some: 'json' }
* karate.set('requestBody', body)
* url someUrl
* request body
* method post
And in the header.js function
function fn() {
var body = karate.get('requestBody');
var sign = Utils.sign(body);
return { Signature: sign };
}
EDIT: this will be implemented in Karate 1.0 onwards: https://github.com/intuit/karate/issues/1385

How to technically send the query parameters to google cloud REST API?

I'm trying to call this REST API
How is one expected to add these params? maxResult
Page token
all
filter
How do I technically send the query parameters?
What part of the payload or options?
I couldn't find an example.
/**
* Checks if dataset already exists in project.
*
* #return {boolean} Returns true if dataset already exists.
*/
function datasetExists() {
// Get a list of all datasets in project.
var url =
'https://bigquery.googleapis.com/bigquery/v2/projects/${projectId}/datasets';
var options = {
method: 'GET',
contentType: 'application/json',
payload: ""
};
var response = authUrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
Logger.log(result);
if (result.entities) {
Logger.log('Dataset with ID = %s created.', dataSet.id);
// return a list of identified entities
return result.entities;
}
All the Google Cloud API use the same definition pattern.
Path parameter, which is in the path of the url, like that
https://bigquery.googleapis.com/xxx/yyy/<pathparameters>/zzz
Query parameters that come in the URL, but at the end, after a ? and separated with &. Most of the time it's tokenPage, pageSize, filters,...
https://bigquery.googleapis.com/xxx/yyy/<pathparameters>/zzz?queryparam1=value1&queryparam2=value2
The body to provide when you perform a POST, PUT, PATCH, DELETE. in JSON (therefore you need to add the content type header when you use it).
Finally, in term of security, the APIs requires a Bearer Access Token in the Authorization header

pass data flutter/dart get method

On the new version of the dart http module for flutter I have a problem
indeed I want to use an API with the get method by passing arguments
'http://host.com?data1=1&data2=2' ...
And since the new version we have to put the url this way
http.get(
Uri.http ('host.com', '/'),
)
or I don't know how to pass the data
Use the query parameters parameter of the Uri.http constructor.
Uri.http ('host.com', '/', {
'data1': '1',
'data2': '2',
...
})
You have to put it in the form
Uri.http ('host.com', '/',parameters),
Inside parameters you have to put a Map like
Map<String, String> parameters = { "data1" : "1" }
And if you are using http dont forget to put
<application android:usesCleartextTraffic="true"/>
inside your AndroidManifest.xml because otherwise you get the next error :) .
For url parameters, you can try just:
String url = 'http://host.com';
url += '?data1=1';
var response = await http.get(url);
You can simply wrap your old url String with Uri.parse.
http.get(Uri.parse('http://host.com?data1=1&data2=2'));

Retrieving SendGrid Transactional Templates List

I have been trying to retrieve list of SendGrid transactional templates using API. I'm using correct API key and getting an empty array while there are about 5 transactional templates existing in my SendGrid account. Here is the response:
{
"templates": []
}
Any guesses what could be wrong?
Any guesses what could be wrong?
Yep, their documentation could be!
I also stuck with the problem and finally managed to solve it once I opened the devtools and saw how they request their own API from the UI. Long story short - one has to pass additional generations=dynamic query parameter. Here is the C# code I use:
var client = new SendGridClient("key");
var response = await client.RequestAsync(
SendGridClient.Method.GET,
urlPath: "/templates",
queryParams: "{\"generations\": \"dynamic\"}");
Using Api 7.3.0 PHP
require("../../sendgrid-php.php");
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
#Comma-delimited list specifying which generations of templates to return. Options are legacy, dynamic or legacy,dynamic
$query_params = json_decode('{"generations": "legacy,dynamic"}');
try {
#$response = $sg->client->templates()->get();
$response = $sg->client->templates()->get(null, $query_params);
echo $response->body();
exit;
} catch (Exception $e) {
echo '{"error":"Caught exception: '. $e->getMessage().'"}';
}
I had the same problem using the python wrapper provided by Sendgrid.
My code was similar to this:
response = SendGridAPIClient(<your api key>).client.templates.get({'generations': 'legacy,dynamic'})
This returned an empty array.
To fix you have to name the param or to pass None before the dict:
response = SendGridAPIClient(<your api key>).client.templates.get(None, {'generations': 'legacy,dynamic'})
or
response = SendGridAPIClient(<your api key>).client.templates.get(query_params={'generations': 'legacy,dynamic'})

Posting multiple images to tumblr using tumblr.js api

I am trying to creating a app which can send posts to tumblr using tumblr.js api.
I could send single image using the createPhotoPost method, but I have to send multiple image in a single post via this method.
From the documentation it says that createPhotoPost method has a "data" parameter which can be an array with "URL-encoded binary contents"
When ever I try to send something in the data Array it returns "[Error: form-data: Arrays are not supported.]".
Can someone please help to solve this issue and please explain what should we pass in the array (Really I am not getting what is URL-encoded binary contents)?
Thanks in advance
There is an error in tumblr.js
https://tumblr.github.io/tumblr.js/tumblr.js.html#line504
The documentation at https://www.tumblr.com/docs/en/api/v2#posting is correct.
Basically the issue is that its not supposed to be
data = [ one , two ] its litterally params['data[0]'] = one ; params['data[1]'] = two; (?A PHP Convention)
var request = require('request')// already a tumblr.js dependency
var currentRequest = request({
url:'https://api.tumblr.com/v2/blog/someblog.tumblr.com/post',
oauth:keys,
},function(err,response,body){
currentRequest//
debugger
cb()
})
var params = {
'type' :'photo',
'caption':'Click To Verify You Are A Robot',
}
var params_images = [
fs.createReadStream('image'),
fs.createReadStream('image')
]
// Sign it with the non-data parameters
currentRequest.form(params)
currentRequest.oauth(keys);
// Clear the side effects from form(param)
delete currentRequest.headers['content-type'];
delete currentRequest.body;
// And then add the full body
var form = currentRequest.form();
//###add params_images to params keys 'data[0]' 'data[1]' 'data[2]' ....
params_images.forEach(function(image,index){
params['data['+index+']']
})
for (var key in params) {
form.append(key, params[key]);
}
// Add the form header back
var form_headers = form.getHeaders()
for(var key in form_headers){
currentRequest[key] = form_headers[key]
}