Kubernetes changes content type - php

I have a service in PHP.
One endpoint calls to other endpoint in these service.
For connection I use guzzle.
Content sent from 1st endpoint to 2nd should be application/json.
On docker it works correctly but when I deploy to Kubernetes,
in logs I see that request content is application/x-www-form-urlencoded.
Even if content type is hardcoded:
private function getPostRequestOptions($postData) : array
{
return [
'headers' => [
'Content-Type' => 'application/json',
'Request-ID' => $this->requestId
],
'body' => json_encode($postData),
'connect_timeout' => static::CONNECT_TIMEOUT,
'timeout' => static::TIMEOUT,
'http_errors' => true,
];
}
public function sendPost(string $path, $postData): \stdClass
{
return $this->executeRequest(
'POST',
$this->getFullUrl($path),
$this->getPostRequestOptions(
$postData
)
);
}
Does someone have any clue why it happens like this?

The problem was Dynatrace monitoring for php 7.
New version of plugin stopped cutting headers.

Related

Trying to use Laravel HTTP to upload a file to a 3rd party

I have the following Postman request for testing a third party API;
What I am trying to do is convert this into code using Laravel's HTTP class, the code i currently have is;
public function uploadToThridParty()
{
$uploadContents = [
'id' => 'this-is-my-id',
'fileUpload' => true,
'frontfile' => Storage::get('somefrontfile.jpg'),
'sideview' => Storage::get('itsasideview.png'),
];
$request = Http::withHeaders(
[
'Accept' => 'application/json',
]
);
$response = $request
->asForm()
->post(
'https://urltoupload.com/upload', $uploadContents
)
}
But every time I run this, the 3rd party API comes back with Invalid ID, even though if i use Postman with the same ID it works fine.
I cant seem to figure out where i am going wrong with my code;
As #Cbroe mention about attach file before sending post request you can make this like this example:
public function uploadToThridParty()
{
$uploadContents = [
'id' => 'this-is-my-id',
'fileUpload' => true
];
$request = Http::withHeaders(
[
'Accept' => 'application/json',
]
);
$response = $request
->attach(
'frontfile', file_get_contents(storage_path('somefrontfile.jpg')), 'somefrontfile.jpg'
)
->attach(
'sideview', file_get_contents(storage_path('itsasideview.png')), 'itsasideview.jpg'
)
->post(
'https://urltoupload.com/upload', $uploadContents
)
}
Also i think you need remove asForm method because it's override your header accept type to application/x-www-form-urlencoded that is way your exception is Invalid ID
Some third party API would require you to have the request with content type as multipart/form data
you can double check all the headers being pass on your postman request HEADERS tab and view on Hidden headers.
If you indeed need your request to be in multipart/form-data, You can use the multipart options of guzzle.
Although this doesnt seem to be on Laravel HTTP-Client docs, you can simply pass a asMultipart() method in your HTTP request
just check the /vendor/laravel/framework/src/Illuminate/Support/Facades/Http.php for full reference of HTTP client.
You can have your request like this.
public function uploadToThridParty() {
$uploadContents = [
[
'name' => 'id',
'contents' => 'this-is-my-id'
],
[
'name' => 'fileUpload',
'contents' => true
],
[
'name' => 'frontfile',
'contents' => fopen( Storage::path( 'somefrontfile.jpg' ), 'r')
],
[
'name' => 'sideview',
'contents' => fopen( Storage::path( 'itsasideview.jpg' ), 'r')
],
];
$request = Http::withHeaders(['Accept' => 'application/json']);
$response = $request->asMultipart()->post('https://urltoupload.com/upload', $uploadContents );
}

How to post an image to this web service

http://labelary.com/viewer.html
This webservice has an 'undocumented' service where you can post them a png, and then send you back the image encoded as a zpl file (for label printers). don't worry, I'm not trying to do anything they don't want me to do, it's mentioned at the bottom here that they allow this undocumented use of their api
So, when you use the api from within the web portal, it makes a post request to this url: http://api.labelary.com/v1/graphics
If I upload a png and then look in the Network tab of Chrome developer tools, I can see that it posted a Form Data, file: (binary)
In their documentation, they actually recommend this Ruby library: https://github.com/rjocoleman/labelary -- this has implemented into it a way to send the post request with the file up to that url and get the zpl data back.
If you navigate to labelary/lib/labelary/image.rb you can see the code for the encode function:
def encode
response = Labelary::Client.connection.post '/v1/graphics', { file: #file }, { Accept: 'application/json' }
image = response.body
return '^GFA,' + image['totalBytes'].to_s + ',' + image['totalBytes'].to_s + ',' + image['rowBytes'].to_s + ',' + image['data'] + '^FS'
end
It makes that request using the faraday request library, if that's of any relevance.
So basically, I'm trying to implement this request in php+laravel using Guzzle. Now I know how to make a post request, but I don't exactly know how to send an image, and I searched around and came up with this code, which isn't working:
$pngPath = storage_path('image.png'); // this is a confirmed real file on my system in the storage folder
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://api.labelary.com/v1/graphics', [
'headers' => [
'Content-Type' => 'multipart/form-data'
],
'multipart' => [
[
'name' => 'file',
'contents' => fopen($pngPath, 'r'),
]
]
]);
When I make that request, I get this error message that doesn't have much detail: ERROR: HTTP 400 Bad Request
I just needed to modify a bit of my request and it worked -- I think it might have been the Content-Type header messing me up more than anything.
This is what the request looks like now:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://api.labelary.com/v1/graphics', [
'headers' => [
// 'Content-Type' => 'multipart/form-data'
'Accept' => 'application/json'
],
'multipart' => [
[
'Content-Type' => 'image/png',
'name' => 'file',
'contents' => fopen($pngPath, 'r'),
'filename' => basename($pngPath)
]
]
]);
Sorry for wasting everyone's time!

Empty Body on POST Request in Guzzle6/PSR7

I use Guzzle6 in the PSR7 flavor because it integrates nicely with Hawk authentication. Now, I face problems adding a body to the request.
private function makeApiRequest(Instructor $instructor): ResponseInterface
{
$startDate = (new CarbonImmutable('00:00:00'))->toIso8601ZuluString();
$endDate = (new CarbonImmutable('00:00:00'))->addMonths(6)->toIso8601ZuluString();
$instructorEmail = $instructor->getEmail();
$body = [
'skip' => 0,
'limit' => 0,
'filter' => [
'assignedTo:user._id' => ['email' => $instructorEmail],
'start' => ['$gte' => $startDate],
'end' => ['$lte' => $endDate],
],
'relations' => ['reasonId']
];
$request = $this->messageFactory->createRequest(
'POST',
'https://app.absence.io/api/v2/absences',
[
'content_type' => 'application/json'
],
json_encode($body)
);
$authentication = new HawkAuthentication();
$request = $authentication->authenticate($request);
return $this->client->sendRequest($request);
}
When I var_dump the $request variable, I see no body inside the request. This is backed by the fact that the API responds as if no body was sent. I cross-checked this in Postman. As you can see, the body specifies filters and pagination, so it is easy to see that the results I get are actually not filtered.
The same request in Postman (with body) works flawlessly.
As the parameter be can of type StreamInterface I created a stream instead and passed the body to it. Didn't work either.
Simple JSON requests can be created without using json_encode()... see the documentation.
use GuzzleHttp\Client;
$client = new Client([
'base_uri' => 'https://app.absence.io/api/v2',
'timeout' => 2.0
]);
$response = $client->request('POST', '/absences', ['json' => $body]);
Found the problem, actually my POST body is NOT empty. It just turns out that dumping the Request will not hint anything about the actual body being enclosed in the message.
I can recommend anyone having similar problems to use http://httpbin.org/#/HTTP_Methods/post_post to debug the POST body.
Finally, the problem was that my content_type header spelling was wrong as the server expects a header Content-Type. Because of this, the JSON data was sent as form data.

Guzzle 6 PUT request not sending form params

I have the following code that I use whenever I want to make POST requests using Guzzle:
$request = $client->request('POST', $url, [
'form_params' => $params,
'headers' => [
'Referer' => '(intentionally removed)',
'Accept' => 'application/json',
]
]);
The code works without any issues and the information within $params is always sent, however when I change the request type from POST to PUT so that the request becomes:
$request = $client->request('PUT', $url, [
'form_params' => $params,
'headers' => [
'Referer' => '(intentionally removed)',
'Accept' => 'application/json',
]
]);
The request suddenly stops sending the data contained within $params.
I have tested the endpoint the request is send to with Insomnia with both POST and PUT requests and both types are processed as expected, so I am certain the issue is not there.
What can be causing the data from Guzzle to be send using the POST method but not when using the PUT?
This behaviour described in guzzle documentation form-params
form_params - Used to send an application/x-www-form-urlencoded POST request.
Probably, you enough pass the parameters in json format:
$request = $client->request('PUT', $url, [
'json' => $params,
'headers' => [
'Referer' => '(intentionally removed)',
'Accept' => 'application/json',
]
]);

POST Request works with Postman, but not with Guzzle

In my Laravel application, I periodically need to POST data to an API using Guzzle.
The API users a bearer token to authenticate, and requests and accepts raw json. To test, I accessed the API using Postman, and everything worked wonderfully.
Postman Headers:
Accept:application/json
Authorization:Bearer [token]
Content-Type:application/json
And Postman Body:
{
"request1" : "123456789",
"request2" : "2468",
"request3" : "987654321",
"name" : "John Doe"
}
Postman returns a 200, and a JSON object as a response.
Now, when I try the same with Guzzle, I get a 200 status code, but no JSON object gets returned. Here's my Guzzle implementation:
public function getClient($token)
{
return new Client([
'base_uri' => env('API_HOST'),
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json'
]);
}
$post = $client->request('POST', '/path/to/api', [
'json' => [
'request1' => 123456789,
'request2' => 2468,
'request3' => 987654321,
'name' => 'John Doe',
]
]);
Is there some trick to POSTing JSON with Guzzle? If not, is there a way to debug what's going on under the hood?
I cannot, for the life of me, understand what the difference is between the Postman POST and the Guzzle POST.
You have to use headers config sections for headers, not the root level.
return new Client([
'base_uri' => env('API_HOST'),
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
]);

Categories