Remove specific cookie in Guzzle response - php

I would like to remove a specific cookie in a Guzzle response object.
My application uses Slim framework and I make calls to an API with Guzzle. Both Slim and Guzzle implement the Request and Response Interface (Psr7) so I can easily return a Guzzle response in a Slim controller like this :
class APIController {
public function call($request, $response) {
// Do stuff with $request (check body and params, change url, etc)
$client = new \GuzzleHttp\Client();
$response = $client->send($request, []);
return $response;
}
}
Everything works fine but the API returns a cookie I want to remove. I can remove the whole header with :
$response = $response->withoutHeader('Set-Cookie');
Is there a native way in Guzzle to remove a specific cookie by name instead of removing the whole header ?

Related

Creating a proxy in Laravel with Guzzle

I need to use an api in my website frontend, but I don't want to expose that api's key to my frontend users, so I've decided to make a proxy. However, I don't think I've necessarily done it in the most clean, straight-forward, Laravel-like or Guzzle-like way. I'll show my work:
In web.php I added a route that looks like this: Route::post('/address-api/{path?}', 'Controller#addressApi')->where('path', '.*'); That way, the entire path after /address-api is passed to my controller, so I can proxy hypothetically ANY post request to that api.
Then in Controller.php I've done this:
public function addressApi($path, Request $request)
{
if (!Str::startsWith($path, '/')) $path = '/' . $path; // make sure it starts with /
$url = 'https://api.craftyclicks.co.uk/address/1.1' . $path;
$postData = $request->all();
$postData['key'] = env('CRAFTYCLICKS_KEY');
$client = new Client();
$response = $client->request('POST', $url, [
'json' => $postData
]);
return response()->json(json_decode($response->getBody(), true));
}
So, whatever json they post to my api, I post to the CraftyClicks api, but I add our secret key to the json. The code above is working, it just doesn't seem like the right way to do it.
The thing I'm not sure about is json_decoding the body and returning it, return response()->json(json_decode($response->getBody(), true));. I feel like there's something... dirty about this. I feel like there must be a cleaner way to return the actual API response exactly as it came in.
At first I was doing return $response->getBody();, but I didn't like that because it didn't have the Content-type: application/json header in the response when I did it that way. Does Guzzle provide, out of the box, a way of just returning their response entirely as-is, headers and all?
Let Laravel have the output; this is cleaner.
return response($response->getBody())
->withHeaders($response->getHeaders());

symfony perform post query

I need to perform post request using using Symfony framework. I can see there is package Symfony\Component\HttpFoundation\Request for this purpose. But when I create post request it seems doens't really perform request and return object data
$response = Request::create(get_api_url().'test','POST', $params);
How can I permorm real post request?
You can use
use Symfony\Component\HttpClient\HttpClient;
$client = HttpClient::create();
$response = $client->request('POST', 'https://...');
More details you can find here

Guzzle map response to object

Is there a way using Guzzle in PHP that when I make a request to an API call that I can map my response to a Response object?
So instead of having to get the response data and then passing my array value as an argument, Guzzle can automatically resolve it to the required class?
In essence, this is what I am doing:
$client = new GuzzleHttp\Client();
$response = $client->request('myapi.users', 'GET');
$responseData = $response->getBody()->getContents();
$user = new User($responseData);
However I would like to try and avoid that boilerplate code by doing something like the following:
$client = new GuzzleHttp\Client();
$user = $client->request('myapi.users', 'GET');
Does Guzzle allow you to map response objects to Responses?
Thanks!
Nope, an HTTP Client (which Guzzle is) is not responsible for that. That's why there is not such a function there.
You can use Guzzle and your own object mapper, BTW, and create an SDK for the API you are using. Like the GitHub SDK, for example, that also uses Guzzle inside, but provides a specific interface for the domain.

Add metadata to all Dingo API responses in Laravel

I am trying to add user-specific Metadata to every API response using Dingo Api. I assumede this would be done in an AddMetadata middleware:
<?php
namespace App\Http\Middleware\Api;
use Closure;
use Dingo\Api\Http\Request;
class AddMetadata {
public function handle(Request $request, Closure $next)
{
$response = $next($request);
/*
* Dingo API response has the ability to modify metadata responses
*/
if ($response instanceof \Dingo\Api\Http\Response) {
$oldMeta = $response->getMeta();
$meta = array_merge($oldMeta, $request->user()->metadata());
$response->setMeta($meta);
}
return $response;
}
}
What I find is the Response at this point is no longer a Dingo API response, therefore I am unable to add metadata. I tried using the Dingo\Api\Http\Response::makeFromExisting() method to create a new response from the old request, I've also tried instantiating a new response but it appears that the Dingo Api response is processed before getting to the middleware.
What would be the most efficient way of adding the user-specific metadata to the response? Ideally I don't want to be adding it to every API endpoint individually.

slim framework withHeader json it does not work

Hello everyone, I'm using slim framework for JSON API all responses work but on headers show text / html, the documentation mentions the function whitHeader:
$app = new \Slim\App;
$app->get('/new/', function (Request $request, Response $response){
$response->getBody()->write(json_encode(['message'=>'ok']));
$response_h = $response->withHeader('Content-Type', 'application/json; charset=utf-8');
return json_decode($response_h);
});
$app->run();
When using $response_h-> getHeaders (); show json header(work) but when running takes another header, I tracked where it replaces the header and is in slim / slim / container.php exactly in current function registerDefaultServices i replace:
Headers $ headers = new (['Content-Type' => 'text / html; charset = UTF-8']);
to
Headers $ headers = new (['Content-Type' => 'application / json; charset = utf-8']);
but it is not the best way, how change the headers?
and try using:
$ app-> response () -> header ();
$ app-> response () -> setHeader ();
In all the return is that the response function () does not exist.
Using official documentation for Slim Framework v2:
The HTTP response returned to the HTTP client will have a header. The HTTP header is a list of keys and values that provide metadata about the HTTP response. You can use the Slim application’s response object to set the HTTP response’s header. The response object has a public property headers that is an instance of \Slim\Helper\Set; this provides a simple, standardized interface to manipulate the HTTP response headers.
<?php
$app = new \Slim\Slim();
$app->response->headers->set('Content-Type', 'application/json');
You may also fetch headers from the response object's headers property, too:
<?php
$contentType = $app->response->headers->get('Content-Type');
If a header with the given name does not exist, null is returned. You may specify header names with upper, lower, or mixed case with dashes or underscores. Use the naming convention with which you are most comfortable.
Using official documentation for Slim Framework v3:
An HTTP response typically has a body. Slim provides a PSR 7 Response object with which you can inspect and manipulate the eventual HTTP response’s body.
Just like the PSR 7 Request object, the PSR 7 Response object implements the body as an instance of \Psr\Http\Message\StreamInterface. You can get the HTTP response body StreamInterface instance with the PSR 7 Response object’s getBody() method. The getBody() method is preferable if the outgoing HTTP response length is unknown or too large for available memory.
Your code should looks like this:
<?php
$app = new \Slim\App();
$app->get('/new/', function(Request $requst, Response $response) {
$response->getBody()->write(json_encode(['YOUR_ARRAY']));
$newResponse = $response->withHeader(
'Content-type',
'application/json; charset=utf-8'
);
return $newResponse;
});
Tested on my environment with Postman. Content-type were changed.

Categories