Using Backand with PHP

Originally appeared in the Backand blog

PHP is one of the most common server-side programming languages as evidenced by the popularity of WordPress and MediaWiki, for example.

Backand provides a Backend As A Service (BAAS) by automatically constructing a REST API for a database schema specified as a JSON.

It is natural to interact with your Backand data from PHP through Backand REST API.

Using Backand REST API With PHP

Using Backand REST API is a two step process:

  1. Obtain the authorization token

  2. Make GET/POST calls to fetch/update/create/delete data.

All calls follow the pattern demonstrated in Backand REST API Playground that is provided once you create a database in Backand.

Calls send JSON parameters and return JSON results.

We describe two ways to use Backand from PHP, using Curl and using Httpful.

Using Curl

Obtaining the Authorization Token

To get the token, use your username, password and app name.

Make a POST call to the TOKEN_URL.

The response is a JSON object with fields access_token and token_type.

define(‘API_URL’, ‘https://api.backand.com:8080');

define(‘TOKEN_URL’, API_URL . ‘/token’);

  $email = ‘johndoe@example.com’;

  $password = ‘secret’;

  $app_name = ‘test’;

// get token

$vars = array(

  ‘username’ => $email,

  ‘password’ => $password,

  ‘appname’ => $app_name,

  ‘grant_type’ => ‘password’

);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, TOKEN_URL);

curl_setopt($ch, CURLOPT_POST, true);

  curl_setopt($ch, CURLOPT_POSTFIELDS,  http_build_query($vars));

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  curl_setopt($ch, CURLOPT_HTTPHEADER,

    array(

        ‘Content-Type: application/x-www-form-urlencoded;     charset=utf-8’,

        ‘Accept: application/json’

    )

 );

 $server_output = curl_exec ($ch);

 curl_close ($ch);

 $server_output_json = json_decode($server_output);

 // retrieve the access token and token type

 $access_token = $server_output_json->access_token;

 $token_type = $server_output_json->token_type;

Now that we have the access token, we can make authenticated calls to the REST API.

Making API GET/POST Calls

API calls use the REST_URL.

   define(‘REST_URL’, ‘https://api.backand.com:8078');

In both types of calls you need to set the Authorization and AppName.

For GET calls, we add a query string to the url.

For POST calls, we send body parameters as JSON (using json_encode).

Make GET Call

We will fetch the first first page of rows in items table

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, REST_URL . ‘/1/objects/items?pageSize=20&pageNumber=1’);

    curl_setopt($ch, CURLOPT_POST, false);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_HTTPHEADER,

       array(

          ‘Accept: application/json’,

          ‘Content-Type: application/json’,

          ‘Authorization: ‘ . $token_type . ‘ ‘ . $access_token,

          ‘AppName: ‘ . $app_name

        )

     );

     $server_output = curl_exec ($ch);

     curl_close ($ch);

     $server_output_json = json_decode($server_output);

The result has two fields, totalRows giving the number of rows retrieved, and data holding the retrieved rows.

We loop on the rows and print them:

   echo ‘result’ . PHP_EOL;

   echo ‘total_rows:’ . $server_output_json->totalRows . PHP_EOL;

   foreach ($server_output_json->data as $item) {

         echo $item->Id . ‘ ‘ . $item->name . ‘ ‘ . $item->description . PHP_EOL;

   }

Make POST Call

We create a new row in items table by doing a POST on the REST_URL:

   $vars = array(

        ‘name’ => ‘Laptop’,

        ‘description’ => ‘Mac Book Pro’

   );

   $ch = curl_init();

   curl_setopt($ch, CURLOPT_URL, REST_URL . ‘/1/objects/items’);

    curl_setopt($ch, CURLOPT_POST, true);

   curl_setopt($ch, CURLOPT_POSTFIELDS,  json_encode($vars));

   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

   curl_setopt($ch, CURLOPT_HTTPHEADER,

      array(

          ‘Content-Type: application/json’,

         ‘Accept: application/json’,

         ‘Authorization: ‘ . $token_type . ‘ ‘ . $access_token,

         ‘AppName: ‘ . $app_name

       )

   );

  $server_output = curl_exec ($ch);

  curl_close ($ch);

  $server_output_json = json_decode($server_output);

The result has a __metadata field with the id of the new row:

   echo ‘id of new row:’ . $server_output_json->__metadata->id . PHP_EOL;

Using Httpful

Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane.

To use Httpful, install Httpful using Composer.

By using this composer.json file,

   {

          “require": {

                    “nategood/httpful": “*"

           }

   }

so you have execute from the command line in the project folder,

    php composer.phar install

This will create a vendor folder in your project folder.

In your PHP file include bootstrap.php as:

  include(‘./vendor/nategood/httpful/bootstrap.php’);

Httpful calls follow the same pattern as Curl calls and use the same URLs. So we will just show the code here:

Obtaining the Authorization Token

      // get token

    $vars = array(

         ‘username’ => $email,

         ‘password’ => $password,

         ‘appname’ => $app_name,

         ‘grant_type’ => ‘password’

    );

   $response = \Httpful\Request::post(TOKEN_URL)

       ->body(http_build_query($vars))

       ->addHeader(‘Content-Type’,’application/x-www-form-urlencoded’)

         ->addHeader(‘charset’, ‘utf-8’)

        ->addHeader(‘Accept’, ‘application/json’)

        ->send();

    // retrieve the access token and token type

    $access_token = $response->body->access_token;

    $token_type = $response->body->token_type;

Make GET Call

      $response = \Httpful\Request::get(REST_URL . ‘/1/objects/items?pageSize=20&pageNumber=1’)

         ->addHeader(‘Accept’, ‘application/json’)

         ->addHeader(‘Content-Type’,’application/json’)

         ->addHeader(‘Authorization’, $token_type . ‘ ‘ . $access_token)

         ->addHeader(‘AppName’, $app_name)

         ->send();

Make POST Call

      $vars = array(

           ‘name’ => ‘Laptop’,

           ‘description’ => ‘Mac Book Pro’

      );

      $response = \Httpful\Request::post(REST_URL . ‘/1/objects/items’)

               ->body(json_encode($vars))

            ->addHeader(‘Accept’, ‘application/json’)

            ->addHeader(‘Content-Type’,’application/json’)

            ->addHeader(‘Authorization’, $token_type . ‘ ‘ . $access_token)

            ->addHeader(‘AppName’, $app_name)

            ->send();