3

I have a plugin that listens for new users to be created. I am then sending that user to system "B" via an API call.

All is working fine the old fashion way, I am curious how to accomplish the same using Guzzle.

$client = new \Guzzle\Http\Client('http://api.site.dev/');
$uri = 'my/endpoint/path';

$request = $client->post($uri, array(
   'headers' => array('Content-type' => 'application/x-www-form-urlencoded'),
   'body' => array(
       'craft_id' => $event->params['user']->id,
       'name' => $event->params['user']->friendlyName,
       'email' => $event->params['user']->email
    ),
    'timeout' => 10
));

$response = $request->send();

Each time I get this response/error back:

Client error response
[status code] 422
[reason phrase] Unprocessable Entity

Which tells me that system "B" isn't getting the information in the correct format. The docs aren't so great with post examples, so I'm not quite sure where I'm going down the wrong path.

Thank you for any suggestions!

  • Are the expecting the content to be JSON/XML encoded by chance? – Brad Bell Aug 15 '16 at 20:54
  • Arg. Yep...that was the problem. Thanks Brad. – Damon Aug 15 '16 at 21:21
  • NP! Be sure and add what worked as an answer, please. :) – Brad Bell Aug 15 '16 at 21:21
4

It is pretty obvious now, but indeed the API is looking for json formatted values and I was in fact sending name:value pairs.

Here is what the updated logic looks like for anyone who comes across this.

MyPlugin.php

$client = new \Guzzle\Http\Client('http://api.site.dev/');
$uri = 'my/endpoint/path';
$post_data = array(
    'craft_id' => $event->params['user']->id,
    'name' => $event->params['user']->friendlyName,
    'email' => $event->params['user']->email
);

$data = json_encode($post_data);

$request = $client->post($uri, array(
    'content-type' => 'application/json'
));

$request->setBody($data);
$response = $request->send();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.