How to start REST client from zf2 skeleton application

1.1k views Asked by At

In short, I want to create a client that uses the HTTP Basic Authentication straight from the skeleton of Zend Framework 2.

The client has to authorize and send the POST with the new message.

Am starting from onscratch (not quite - I have a skeleton F2) can somee explain to me where I need to start and how to initiate Zend_Rest_Client?

Edit: I looked more closely on stack overflow and found a similar question

Now my IndexController.php file looks like this:

<?php 
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use Zend\Http\Request;
use Zend\Http\Client;
use Zend\Stdlib\Parameters;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
         $request = new Request();
         $request->getHeaders()->addHeaders(array(
           'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
         ));
         $someurl="http://apiurl/public_timeline.json";
         $request->setUri($someurl);
         $request->setMethod('GET');
         $request->setPost(new Parameters(array('page' => 1)));

         $client = new Client();
         $response = $client->dispatch($request);
         $data = json_decode($response->getBody(), true);

         print_r($data);

         return new ViewModel();
    }
}

The above code works, but I want to extend this module to support methods that require authentication. How to do so?

1

There are 1 answers

1
edigu On

Zend's Http Client only supports basic HTTP authentication and you can easily authenticate your client just before dispatching the request like this:

$client = new Client();
$client->setAuth('username', 'password');
$response = $client->dispatch($request);

For more advanced authentication mechanisms like Oauth2, I strongly recommend utilizing some 3rd party oauth client library instead of writing your own. There are lot of open source and well-written Oauth2 client libraries exists on github. (for example)

When you grab an access/refresh token (or client id & secret key) from remote provider, just set this information in your request object like this:

$request->getHeaders()->addHeaders(array(
    'Accept' => 'application/json',
    'Authorization' => 'Bearer 1234567890abcdefghxxxx', // access token
));

$client = new Client();
$response = $client->dispatch($request);