4

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!

Damon
  • 4,706
  • 1
  • 20
  • 36

1 Answers1

6

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();
Damon
  • 4,706
  • 1
  • 20
  • 36