cadev
cadev

Reputation: 143

Post request from drupal 8 (Guzzle)

I'm trying to do a post request from Drupal to a Redmine Api to sending a json. But I get an error when i attemp it.

Data to be sent:

$rawdata = '{
    "issue": {
      "project_id": 85,
      "subject": "Test from drupal",
      "priority_id": 4
    }
 }';

$data = json_encode($rawdata);

Post Request:

$request = \Drupal::httpClient()->post($url,array(

      'headers' => array(
                  'Accept' => 'application/json',
                  'Content-type' => 'application/json',
                  'X-Redmine-API-Key' => $this->apiKey),
        ));
    $request->setBody($data); 
    $response = $request->send($request);

And this is the error that appears:

[:error] [pid 8316] [client XXX.XXX.XXX.XXX] FastCGI: server "/usr/lib/cgi-bin/php5-fcgi_xxxx" stderr: PHP message: Uncaught PHP Exception GuzzleHttp\\Exception\\ClientException: "Client error: 422" at dir/to/project/vendor/guzzlehttp/guzzle/src/Middleware.php line 69, referer: http://url-from-project/create

I have researched on the error and it seems there is a problem with content-type in headers. But if I try to send the request without the headers options, it appears a 401 Client error that is related to authentification.

It would be like this:

 $request = \Drupal::httpClient()->post($url,array(
        'Accept' => 'application/json',
        'Content-type' => 'application/json',
        'X-Redmine-API-Key' => $this->apiKey,
        ));

And it throws this error:

[:error] [pid 8159] [client XXX.XXX.XXX.XXX] FastCGI: server "/usr/lib/cgi-bin/php5-fcgi_xxxx" stderr: PHP message: Uncaught PHP Exception GuzzleHttp\\Exception\\ClientException: "Client error: 401" at /dir/to/project/vendor/guzzlehttp/guzzle/src/Middleware.php line 69, referer: http://website.com/create

Anyone has any hint?

Im struggled with this. Any help will be appreciated.

Upvotes: 0

Views: 4995

Answers (1)

Matthew Downie
Matthew Downie

Reputation: 31

Well, first off, I don't recommend manually typing up JSON and trying to convert it. Secondly, it looks like you are converting a JSON string for no reason. Just send the string itself. The format will be invalid the way you are sending it. Hope this helps.

Upvotes: 2

Related Questions