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;
2
Answers
As @Cbroe mention about attach file before sending post request you can make this like this example:
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 requestjust check the
/vendor/laravel/framework/src/Illuminate/Support/Facades/Http.php
for full reference of HTTP client.You can have your request like this.