When I try to send a Guzzle-POST, I always get a error returned:
{"errors":[{"code":"0","status":"400","title":"Bad Request","detail":"The JSON payload is malformed."}]}
As I don't see any error,inside the data-array itself, maybe it can be a wrong header information? It is an simple POST request to shopware 6 API where I try toadd a new article.
$payload= [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'form_params' =>[
"name" => "productname",
"productNumber" => "101003",
"stock" => 2,
"taxId" => "50ee15989533451095c9d7e03d9ce479",
"price" => [
[
"currencyId" => "b7d2554b0ce847cd82f3ac9bd1c0dfca",
"gross" => 15,
"net" => 10,
"linked" => false
]
]
]
];
$response = $client->request('POST', 'http://shopware6.shop.de/api/product',
$data
);
If I use Postman or RESTer or similar tools, I get a positive result, It works. So I guess I am missing sth. inside my guzzle-request (which is a copy of the origin documentation from https://shopware.stoplight.io/docs/admin-api/ZG9jOjEyMzA4NTUy-product-data )
I am using guzzle with kamermans oauth2 middleware
A simple GET-request is working too:
$response = $client->request('GET', 'http://shopware6.shop.de/api/product/{productid}',
[
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]
);
CodePudding user response:
You are missing the entire authentication in your request, which you might've omitted on purpose but I thought I should add it in the following example for the sake of completion.
Aside from that the cause for the bad request is using the key 'form_params'
, which is only used for Content-Type: multipart/form-data
, instead of 'json'
for the payload.
$response = $client->request('POST', 'http://localhost/api/oauth/token', [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'json' => [
'grant_type' => 'client_credentials',
'client_id' => '...',
'client_secret' => '...',
],
]);
$token = json_decode($response->getBody()->getContents(), true)['access_token'];
$payload = [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
'json' => [
'name' => 'productname',
'productNumber' => '101003',
'stock' => 2,
'taxId' => '...',
'price' => [
[
'currencyId' => '...',
'gross' => 15,
'net' => 10,
'linked' => false,
],
],
],
];
$response = $client->request('POST', 'http://localhost/api/product', $payload);