Set request content to test in symfony - php

I have to set a test to check the user registragion with an API , but I'm not sure how to set the content, its has to had a header with the token named x-auth-tokenand the body with aform-data` param named data that contains json-string
public function testUserRegister(){
$client = static::createClient();
$server = array('x-auth-token' => '...');
$client->request(Request::METHOD_POST, self::$uri, [], [], $server);
$response = $client->getResponse();
self::assertEquals( Response::HTTP_CREATED, $response->getStatusCode());
}
When I check on the debug ther is no x-auth-token on the headers

Use third parameter of $client->request method to pass your data.
If you want to send payload as form data with JSON, you need to do something like this:
$client->request(..., ..., ['data' => json_encode(...)], ...);
Keep in mind that you maybe need to set correct Content-Type in header (application/x-www-form-urlencoded).

Related

Send Body as raw using Guzzle

I am trying to use Guzzle to send POST request to my web service. this service accepts body as raw. It works fine when I use postman but I doesn't using Guzzle. when using Guzzle, I get only the webservice description as I put the web service URL in the browser.
here is my code:
$body = "CA::Read:PackageItems (CustomerId='xxxxxx',AllPackages=TRUE);";
$headers = [
....
....
];
$client = new Client();
$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',$headers,$body);
echo $body = $response->getBody();
seems headers or body doesn't pass through.
Try like this
$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',['headers' => $headers, 'body' => $body]);
I have recently had to implement Guzzle for the first time and it is a fairly simple library to use.
First I created a new Client
// Passed in our options with just our base_uri in
$client = new Client(["base_uri" => "http://example.com"]);
I then created a POST request, not how I am using new Request instead of $client->request(... though. This doesn't really matter to much that I've used new Request though.
// Create a simple request object of type 'POST' with our remaining URI
// our headers and the body of our request.
$request = new Request('POST', '/api/v1/user/', $this->_headers, $this->body);
so in essence it would look like:
$request = new Request('POST', '/api/v1/user/', ['Content-Type' => "application/json, 'Accept' => "application/json"], '{"username": "myuser"}');
$this->headers is a simple key-value pair array of our request headers making sure to set the Content-Type header and $this->body is a simple string object, in my case it forms a JSON body.
I can simply then just call the $client->send(... method to send the request like:
// send would return us our ResponseInterface object as long as an exception wasn't thrown.
$rawResponse = $client->send($request, $this->_options);
$this->_options is a simple key-value pair array again simple to the headers array but this includes things like timeout for the request.
For me I have created a simple Factory object called HttpClient that constructs the whole Guzzle request for me this is why I just create a new Request object instead of calling $client->request(... which will also send the request.
What you essentially need to do to send data as raw is to json_encode an array of your $data and send it in the request body.
$request = new Request(
'POST',
$url,
['Content-Type' => 'application/json', 'Accept' => 'application/json'],
\GuzzleHttp\json_encode($data)
);
$response = $client->send($request);
$content = $response->getBody()->getContents();
Using guzzle Request GuzzleHttp\Psr7\Request; and Client GuzzleHttp\Client

Sending a custom header with ZEND_HTTP_CLIENT

How can I send a custom header with the ZEND_HTTP_CLIENT. I am trying to send a variable key with a certain value, that I will check later for authenticity
I've tried this
$client = new Zend_Http_Client('http://localhost/v3/files/');
$client->setHeaders('Content-type','multipart/form-data');
$client->setHeaders('key','XXXxXXXXXXXXXXXXXX');
$client->setParameterPost('document_id', $id);
$client->setParameterPost('type_id', $docType['type']);
$client->setParameterPost('file', $form->file);
$response = $client->request(Zend_Http_Client::POST);
and this
$client = new Zend_Http_Client('http://localhost/v3/files/');
$client->setHeaders(array(
'Content-type','multipart/form-data',
'key','XXXxXXXXXXXXXXXXXX'));
$client->setParameterPost('document_id', $id);
$client->setParameterPost('type_id', $docType['type']);
$client->setParameterPost('file', $form->file);
$response = $client->request(Zend_Http_Client::POST);
but it doesnt seem to work. It says key is not a valid type.
I want to send a custom header like this (similar to what happens when you set headers with the Postman client).
Is this possible?
Try with add a config param like this:
$client = new Zend_Http_Client('http://localhost/v3/files/', array('strict' => false));

How do you pass Content-Type header when testing Silex REST service?

I'm testing a Silex REST service as explained here but also trying to automatically decode JSON data as is also explained in the manual but somehow it fails to create the $data parameter.
In my test I'm calling the service with:
$data = file_get_contents(__DIR__.'/resources/billing-info.json');
$client->request('POST', '/users/test_user/bills',array(), array(), array('Content-Type' => 'application/json'), $data);
and in the Controller I try to access the unmarshalled data as
$app->post('/users/{username}/bills', function(Request $request, $username) use($app) {
try {
$myData = $request->data;
.....
} catch (Exception $e){
return $app->json(array('error'=>$e->getMessage()),$e->getCode());
}
});
But the $data is non existent. What am I doing wrong?
You need to change Content-Type to CONTENT_TYPE. If you look at the source code for the Client class, you'll find that the $server argument needs to match the keys given by the $_SERVER superglobal. The content-type header is stored in the CONTENT_TYPE key.
$client->request('POST', '/users/test_user/bills',array(), array(), array('CONTENT_TYPE' => 'application/json'), $data);
Check out the Documentation on the Request-Object. I guess instead of $myData = $request->data; it must be:
$myData = $request->getContent();

How to add form data on Post requests for Buzz HTTP Client on Laravel?

I'm using Buzz HTTP Client for Laravel.
I have a problem adding form data to my POST requests, since it wasn't specified in it's wiki/documentation.
Listed below are the two ways of sending requests.
Example 1:
$response = Buzz::post('http://api.website.com/login');
//how do I add a "username", and "password" field in my POST request?
echo $response;
echo $response->getContent;
Example 2:
$request = new Buzz\Message\Request('POST', '/', 'http://google.com');
$response = new Buzz\Message\Response();
//how do I add a "username", and "password" field in my POST request?
$client = new Buzz\Client\FileGetContents();
$client->send($request, $response);
echo $request;
echo $response;
The answer here is going to really depend on what the API expects. Lets assume, the API expects the password and username sent as JSON in the content of the request. The example http request would look something like:
POST /login HTTP/1.1
Content-Type: application/json
{
"username": "bugsBunny",
"password": "wh4tsUpD0c"
}
To do this with Buzz, this should work:
$jsonPayload = json_encode([
‘username’ => ‘bugsBunny’,
‘password’ => ‘wh4tsUpD0c
]);
$headers = ['Content-Type', 'application/json'];
$response = Buzz::post('http://api.website.com/login', $headers, $jsonPayload);
If you're attempting to submit a form on a given website, you shouldn't use the above method. Instead use Buzz's built in form method which will attach the correct headers.
use Buzz\Message\Form;
$request = new Form(Form::METHOD_POST, ‘login’, ‘api.website.com’);
$request->setFields([
‘username’ => ‘bugsBunny’,
‘password’ => ‘wh4tsUpD0c’
]);
$response = new Buzz\Message\Response();
$client = new Buzz\Client\Curl();
$client->send($request, $response);
On a side note, I'd suggest not using this library. The library is, as you stated, Laravel integration for Buzz. The issue here is, the author should have made buzz a dependency listed in composer, rather than include the Buzz source directly. This prevents updates to Buzz from making their way into this project. You can see on the actual Buzz repo, the last commit was 29 days ago. Also if another package is using Buzz and including it correctly by composer, composer would install both packages. But when an instance of Buzz was created, you couldn't be certain which version was being loaded. You should just use Buzz, which can be found on packagist.
// assuming $headers and $jsonPayload are the same as in previous example.
$browser = new Buzz\Browser();
$response = $browser->post('http://api.website.com/login', $headers, $jsonPayload);
It was foolish of me to not read the code first before asking.
The form data is actually pased on the third parameter for the function. Though it accepts strings only so don't forget to json encode your data.
Buzz Class
public function post($url, $headers = array(), $content = '')
{
....
....
}
Buzz::post($url, array(), json_encode(array('Username'=>'usernamexx','Password'=>'p#$$w0rD')) );

Send raw json HTTP request for an API call in Yii 1.x.x

I asked a similar question earlier, in a nutshell I have an API application that takes json requests and outputs an json response.
For instance here is one of the requests that I need to test out, how can I use this json object with my testing to emulate a 'real request'
{
"request" : {
"model" : {
"code" : "PR92DK1Z"
}
}
The response is straightforward (this bit has been done).
From other users on here this is the optimised method using Yii to do this, I am just unsure how to emulate the json request - e.g essentially send a JSON HTTP request, can anyone assist on how to do this?
public function actionMyRequest() {
// somehow add my json request...
$requestBody = Yii::app()->request->getRawBody();
$parsedRequest = CJSON::decode($requestBody);
$code = $parsedRequest["request"]["model"]["code"];
}
I don't understand if you want your app to send an http request and get the result or at the opposite receive a http request
I answered for the first assumption, I'll change my answer if you want the other
For me the best way to send an HTTP request is to use Guzzle http client.
This is not a yii extension, but you can use third party libraries with yii.
Here's an example from Guzzle page:
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode(); // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody();
So in your case you could do something like:
public function actionMyRequest() {
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.your-url.com/');
$requestBody = $res->getBody();
$parsedRequest = CJSON::decode($requestBody);
$code = $parsedRequest["request"]["model"]["code"];
}

Categories