vendredi 31 août 2018

Guzzle HTTP send file stream throws error- "json_encode error: Type is not supported"

I am using Guzzle client in my Laravel application to send a request to API endpoint along with a file. I am achieving this by creating a multipart data as follow-

$rid = $this->wsl->curlWSl('POST', '/throttle', [], [
            'verify' => false,
            'multipart' => [
                [
                    'name'     => 'csv',
                    'contents' => fopen($dest, 'rb')
                ],
                [
                    'name' => 'name',
                    'contents' => $request->input('name')
                ],
                [
                    'name' => 'description',
                    'contents' => $request->input('description')
                ],
                [
                    'name' => 'header',
                    'contents' => '1'
                ]
            ]
]);

The curlWSL method I have defined a below -

public function curlWSl(string $method, string $path, Array $headers = [], Array $data = null, Array $options = [])
    {
        $endPoint = $this->getUri() . $path;

        if (!empty($headers)) {
            $options['headers'] = $headers;
        }

        if ($method == 'GET' && $data) {
            $endPoint .= http_build_query($data);
        }
        if ($method == 'POST') {
            $options['json'] = $data;
        }

        try {
            $response = $this->getClient()->request(
                $method,
                $endPoint,
                $options
            );
        } catch (\Exception $ex) {
            return ['statusCode'=>$ex->getCode(), 'errorMsg' => $ex->getMessage()];
        }

        return json_decode($response->getBody()) ?? (string)$response->getBody();
    }

Doing this, throws me an exception -

InvalidArgumentException {#296 ▼
  #message: "json_encode error: Type is not supported"
  #code: 0
  #file: "/var/www/html/vendor/guzzlehttp/guzzle/src/functions.php"
  #line: 327
  trace: {▶}
}

I am sure, this is because of fopen file stream because when I remove that, my request is received at the endpoint.

I am also looking for some help on how can I validate the request data at the API endpoint using laravel validators.

Your help is much appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire