0
votes

I am having difficulty with an API and guzzle. The API requires a json content type, and basic auth. The api example request is

POST /endpoint/v1/create?id=1
[
  {
    "Name": "Test Room"
  }
]

My Code:

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Middleware;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7;

$client = new Client(['base_uri' => env('base_uri')]);
$headers = [
  'Authorization' => 'Basic',
  'Accept'        => 'application/json',
  'Content-Type'  => 'application/json',
];

$uri='/endpoint/v1/create?id=' . env('id');
$payload = ['Name' => 'Test Name'];

  $response = $this->client->request('POST', $uri, ['auth' => ['username', 'password'], 'headers' => $headers, 'json' => $payload]);

All seems good to me. I've used guzzle this way in the past. However, The server responds with a "No data was submitted" Message.

The request:

POST /endpoint/v1/create?id=1 HTTP/1.1
User-Agent: GuzzleHttp/6.3.3 curl/7.58.0 PHP/7.2.5-1+ubuntu18.04.1+deb.sury.org+1
Authorization: Basic {Auth basic string goes here}
Host: {host goes here}
Accept: application/json
Content-Type: application/json

{"Name":"Test Name"}

The Response:

HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
WWW-Authenticate: Basic
Date: Thu, 21 Mar 2019 01:04:21 GMT
Content-Length: 36

{"Message":"No data was submitted."}

EDIT: I'm able to successfully complete this request in postman. The API responds to [{"Name":"Test Name"}] but not {"Name":"Test Name"}, does anyone know how to replicate that with guzzle?

1

1 Answers

0
votes

I was able to solve this problem by wrapping the payload in an array like so: $payload = [['Name' => 'Test Name']];