Community @ The Turning Gate

Support community for TTG plugins and products.

NOTICE

The Turning Gate's Community has moved to a new home, at https://discourse.theturninggate.net.

This forum is now closed, and exists here as a read-only archive.

  • New user registrations are disabled.
  • Users cannot create new topics.
  • Users cannot reply to existing topics.

You are not logged in.

#1 2020-05-03 06:27:23

gaufde
Member
From: Ojai, CA
Registered: 2014-07-11
Posts: 72
Website

Getting Started with new JSON API

Congratulations on Backlight 3 Matt and Ben!

Even though I owned Backlight 1, I never got around to switching away from CE4 until a few weeks ago. With the new release, I am curious to see what sort of things are possible now that we have this new API. I know very little about how to handle these sorts of things, but this seems like a great opportunity to learn. However, I am having trouble accessing the endpoints as described in the new documentation.

If I understand correctly, you are supposed to be able to access an endpoint by going to yoursite.com/backlight/api, and then the browser will display the data retrieved. However, this doesn't seem to be working for me.

Also, I am somewhat clueless about where I am meant to make modifications. The documentation mentions that the API needs to be instantiated and so I assume that once I understand what that means I will have a better idea about how all the pieces fit together. The system for dealing with PHPlugins and custom css are fairly straightforward as example files are already included in their proper locations. I assume that I will need to create a new file to play with the JSON API, but where is that file meant to live?

Is there a good place for me to get a crash course on how all these pieces fit together? I'm not too worried about learning code syntax as that is relatively easy to google. I'm mainly having trouble figuring out what the relevant pieces are and how they interact to create something useful.


Graceson Aufderheide
gracesonaufderheide.com

Offline

#2 2020-05-03 06:43:37

Matthew
Administrator
From: San Francisco, CA
Registered: 2012-09-24
Posts: 5,795
Website

Re: Getting Started with new JSON API

Hi Graceson,

Just to make sure you've got it, the JSON API documentation is here:
https://backlight.me/docs/json-api

Some base knowledge of JavaScript or PHP is assumed, so it's not fully exhaustive.

In JS, you can interact with the API via the provided libraries, or you could use whatever your preferred style for making XHR requests. For modern browsers, that's the Fetch API; for supporting older browsers, then probably jQuery's AJAX. These are the two things being used by our libraries, so again, I'd recommend using them rather than writing your own.

In PHP, you should be able to make API requests using cURL. I am personally less familiar with PHP.

Either way, I would put the work into a PHPlugins function. There's already examples there how to inject JS, and I believe there's some use of cURL in one of the Wordpress-related samples.

Because the API is more intended for advanced users, I doubt I'll be blogging tutorials about it. But I will like cobble together some examples at some point, and we'll start to leverage it more within Backlight itself in future updates.


Matt

The Turning Gate, http://theturninggate.net

Offline

#3 2020-05-03 07:10:17

gaufde
Member
From: Ojai, CA
Registered: 2014-07-11
Posts: 72
Website

Re: Getting Started with new JSON API

Hi Matt,
Thanks for the quick response!

I am sort of starting from scratch as all of my web coding experience comes from fiddling around with CE4 or Backlight customizations.

So it sounds like there are two ways of accessing the new API: one is through Fetch API, and the other is by using PHPlugins to inject JS. What are the two different use cases for these methods?

Do you have any examples for when one method would be used over another? My guess right now is that the FetchAPI (or jQuery's AJAX) is useful to place Backlight managed photos or galleries onto any website where as if you wanted to create a custom page in Backlight with multiple galleries then maybe the PHPlugins route would be easier.

Also, is my understanding of how to access the API endpoints correct? Visiting https://gracesonaufderheide.com/backlight/api just redirects me to the homepage.


Graceson Aufderheide
gracesonaufderheide.com

Offline

#4 2020-05-03 07:49:11

Matthew
Administrator
From: San Francisco, CA
Registered: 2012-09-24
Posts: 5,795
Website

Re: Getting Started with new JSON API

First thing to decide, whether you intend to work in JS or PHP. Either way, the top bit of the documentation, "The API", defines the available endpoints. The endpoints are the same, regardless, but you're meant to understand already how to use them.

I'm not a PHP guy. If using PHP, I don't know the extent of your options, but cURL is one way you should be able to interact with the API. In phplugins-pangolin-sample.php, look for the function with "Get a list of blog titles from Wordpress JSON API", and that's an example how to use cURL, and then how to utilize the response to render HTML.

In JavaScript, I've provided two convenience libraries that allow you to interact with the API without having to write the fetch requests yourself. The library api.js is written in ES6 JavaScript, and should be used if you're only targeting modern web-browsers. If you're concerned about supporting older browsers, including Internet Explorer, then you should use jquery.api.js instead.

The simplest starter I can give is this, in PHPlugins:

function scripts() {
  if ($this->hasAlbum()) {
    $albumId = $this->album->getId();
    echo '
      <script src="/backlight/modules/module-publisher/lib/js/jquery.api.js"></script>
      <script>
        var backlight = new Backlight()

        backlight.getAlbum('. $albumId .', {
          done: function(data) {
            console.log(data)
          },
        })
      </script>
    ';
  }
  return false;
} // END /**/

And that will just log the response to the console. You'll need to figure out what to do with it.

Make sure you go into the Settings and enable the JSON API. That was a late addition, and I've just now added it to the docs.


Matt

The Turning Gate, http://theturninggate.net

Offline

#5 2020-05-07 02:08:19

Nico3939
Member
From: France
Registered: 2016-10-05
Posts: 235
Website

Re: Getting Started with new JSON API

Hum interesting hmm but if you put album reference number like documentation it send an error:

Example:

backlight.getAlbum('. $albumId .', {

By:

backlight.getAlbum('12345', {

Last edited by Nico3939 (2020-05-07 02:08:53)

Offline

#6 2020-05-07 02:41:56

Daniel Leu
Moderator
Registered: 2012-10-11
Posts: 1,624
Website

Re: Getting Started with new JSON API

The error is because you introduce a syntax error. The single quotes are there to terminate the string that started after the echo statement.

Using double quotes should do the trick:

backlight.getAlbum("12345", {...

Daniel Leu | Photography   
DanielLeu.com
My digital playground (eg, Backlight tips&tricks): lab.DanielLeu.com

Offline

#7 2020-05-07 03:10:35

Nico3939
Member
From: France
Registered: 2016-10-05
Posts: 235
Website

Re: Getting Started with new JSON API

This can be OK for displayed photos count of album id 343971 on any page page? But don’t work...

function scripts() {  
	
if ($this->hasAlbum()) {
	$albumId = $this->album->getId();
		 echo '
		  <script src="/backlight/modules/module-publisher/lib/js/jquery.api.js"></script>
      <script>
        var backlight = new Backlight()
        
        backlight.getAlbum("343971", {
          done: function  footer_top() {
          	if ($this->hasAlbum()) {
		 echo '<span data-lang="fr"><p class="imagenum"><strong>'.$this->album->getNumberOfPhotos().' images dans la photothèque</strong></p></span><span data-lang="en"><p class="imagenum"><strong>'.$this->album->getNumberOfPhotos().' images in the stock photo collection</strong></p></span>';
}
	return true;
},
          })
      </script>
   ';
  }
  return false;
}

Last edited by Nico3939 (2020-05-07 05:33:43)

Offline

#8 2020-05-07 06:14:26

Matthew
Administrator
From: San Francisco, CA
Registered: 2012-09-24
Posts: 5,795
Website

Re: Getting Started with new JSON API

You're mixing PHP into JS. You can't do that.

Basically, your entire "done:..." function, you're writing as PHP.


Matt

The Turning Gate, http://theturninggate.net

Offline

#9 2020-05-07 08:38:31

Nico3939
Member
From: France
Registered: 2016-10-05
Posts: 235
Website

Re: Getting Started with new JSON API

ah ok thank you, not easy all that!

Offline

#10 2020-05-07 10:00:57

Daniel Leu
Moderator
Registered: 2012-10-11
Posts: 1,624
Website

Re: Getting Started with new JSON API

I wrote up a small example for you, Nicolas. This is plain php and you can use it in your phplugins file. Just use the example code where you like to have the count, such as inside the footer. Have fun!

http://lab.danielleu.com/blog/using-bac … -from-php/


Daniel Leu | Photography   
DanielLeu.com
My digital playground (eg, Backlight tips&tricks): lab.DanielLeu.com

Offline

#11 2020-05-07 16:03:04

Nico3939
Member
From: France
Registered: 2016-10-05
Posts: 235
Website

Re: Getting Started with new JSON API

Whao!  whao! Daniel your great! thanks you very much for that but my limited knowledge means that I don't know how to call this function in the place I want... hmm

Should I put this:

$posts = $this->dlp_get_wp_rest_response("https://yoursite.domain/backlight/api/get_album/12345");
echo "Array length: " . count($posts['album']['photos']);

in a function such as:

 function  footer_top() {

Thanks Nico

Offline

#12 2020-05-07 21:46:19

Daniel Leu
Moderator
Registered: 2012-10-11
Posts: 1,624
Website

Re: Getting Started with new JSON API

You have an idea and are not certain, why don't just try it? Worst Case it doesn't work and you remove the code ;-)

function footer_top() {
   $posts = $this->dlp_get_wp_rest_response("https://yoursite.domain/backlight/api/get_album/12345");
   echo "Array length: " . count($posts['album']['photos']);
}

I hope I didn't made any typos ;-)


Daniel Leu | Photography   
DanielLeu.com
My digital playground (eg, Backlight tips&tricks): lab.DanielLeu.com

Offline

#13 2020-05-09 08:21:23

Nico3939
Member
From: France
Registered: 2016-10-05
Posts: 235
Website

Re: Getting Started with new JSON API

Thank you very much Daniel
It seems it don't work

Offline

#14 2020-05-09 10:56:51

Daniel Leu
Moderator
Registered: 2012-10-11
Posts: 1,624
Website

Re: Getting Started with new JSON API

Nico3939 wrote:

Thank you very much Daniel
It seems it don't work

3533 images dans la photothèque

That's a big library! Nice that it works now!


Daniel Leu | Photography   
DanielLeu.com
My digital playground (eg, Backlight tips&tricks): lab.DanielLeu.com

Offline

#15 2020-05-09 17:55:51

Nico3939
Member
From: France
Registered: 2016-10-05
Posts: 235
Website

Re: Getting Started with new JSON API

thank you very much Daniel, in fact this is a code that I have been using since version 2 of Backlight but it does not display the number of images of an album on a page without an album.  I would have liked to be able to display the number of images in the footer of each page, including the pages with only text, but I have to make a reason, my limited knowledge in php does not allow me to achieve this.

Offline

#16 2020-05-10 03:02:06

Daniel Leu
Moderator
Registered: 2012-10-11
Posts: 1,624
Website

Re: Getting Started with new JSON API

I'm confused, Nico. My version posted here can be run on any page.


Daniel Leu | Photography   
DanielLeu.com
My digital playground (eg, Backlight tips&tricks): lab.DanielLeu.com

Offline

#17 2020-05-10 23:12:42

Nico3939
Member
From: France
Registered: 2016-10-05
Posts: 235
Website

Re: Getting Started with new JSON API

No problem  Daniel, thank you for all.

This:

function dlp_get_wp_rest_response($url){
    $curl = curl_init();
     curl_setopt_array($curl, array(
       CURLOPT_RETURNTRANSFER => 1,
       CURLOPT_URL => $url,
       CURLOPT_USERAGENT => 'User Agent X'
     ));
     $posts = curl_exec($curl);
     curl_close($curl);
     return json_decode($posts, true);	
}

	function footer_top {
   $posts = $this->dlp_get_wp_rest_response("https://www.phototheque.nicolaslogerot.com/backlight/api/get_album/343971");
   echo "Array length: " . count($posts['album']['photos']);
}

Send me:

Something went wrong
Unexpected error: syntax error, unexpected '{', expecting '(' in perso-home.php on line 145


Line 145 is: function footer_top {

Offline

#18 2020-05-10 23:25:50

rod barbee
Moderator
From: Port Ludlow, WA USA
Registered: 2012-09-24
Posts: 17,830
Website

Re: Getting Started with new JSON API

ttg functions need to be followed by a pair of parentheses
function footer_top () {

https://backlight.me/docs/using-phplugi … k-function


Rod 
Just a user with way too much time on his hands.
www.rodbarbee.com
ttg-tips.com, Backlight 2/3 test site

Offline

#19 2020-05-10 23:43:24

Nico3939
Member
From: France
Registered: 2016-10-05
Posts: 235
Website

Re: Getting Started with new JSON API

Oh yes thank you Rod,

Now the error is:

Something went wrong
count(): Parameter must be an array or an object that implements Countable in perso-home.php on line 147

Offline

#20 2020-05-11 00:03:41

rod barbee
Moderator
From: Port Ludlow, WA USA
Registered: 2012-09-24
Posts: 17,830
Website

Re: Getting Started with new JSON API

that will be a Daniel question wink


Rod 
Just a user with way too much time on his hands.
www.rodbarbee.com
ttg-tips.com, Backlight 2/3 test site

Offline

#21 2020-05-11 02:05:58

Daniel Leu
Moderator
Registered: 2012-10-11
Posts: 1,624
Website

Re: Getting Started with new JSON API

Nico3939 wrote:

Oh yes thank you Rod,

Now the error is:

Something went wrong
count(): Parameter must be an array or an object that implements Countable in perso-home.php on line 147

Can you try it on an album with less images?


Daniel Leu | Photography   
DanielLeu.com
My digital playground (eg, Backlight tips&tricks): lab.DanielLeu.com

Offline

#22 2020-05-11 07:14:05

Matthew
Administrator
From: San Francisco, CA
Registered: 2012-09-24
Posts: 5,795
Website

Re: Getting Started with new JSON API

You should probably wrap the whole thing in a condition to determine whether or not you're dealing with an album.

if ($this->hasAlbum()) {
  ...
}

You can see other examples of this being used in the samples.


Matt

The Turning Gate, http://theturninggate.net

Offline

#23 2020-05-11 10:30:57

Daniel Leu
Moderator
Registered: 2012-10-11
Posts: 1,624
Website

Re: Getting Started with new JSON API

I'm running this code, Nicolas, and it works without problems:

function footer_bottom() {
   $posts = $this->dlp_get_wp_rest_response("https://www.phototheque.nicolaslogerot.com/backlight/api/get_album/343971");
   echo "Array length: " . count($posts['album']['photos']);
}

I'm surprised that even performance doesn't seem to be an issue when doing this over the internet. It will be even faster on your machine.


Daniel Leu | Photography   
DanielLeu.com
My digital playground (eg, Backlight tips&tricks): lab.DanielLeu.com

Offline

#24 2020-05-11 18:53:46

Nico3939
Member
From: France
Registered: 2016-10-05
Posts: 235
Website

Re: Getting Started with new JSON API

Ok Daniel and thank you very much,

I tried to remove all the other functions from the PHP files and leave only this one but I have to resolve to the fact that it does not work on my installation

My php:

<?php
/*
 *  TTG Core Elements "PHPlugins" User Hooks v1.2 - initialization mainline
 *
 *  developed by john bishop images (http://johnbishopimages.com)
 *  for Matthew Campagna of The Turning Gate (http://theturninggate.net)
 *
 */

function user_load($style, $path) {
  $g_tsvrl = explode(' ', $style); // Extract gallery type
  define ('G_STYLE', strtoupper($g_tsvrl[1])); // and set global for later
  $g_path = str_ireplace('\\','/',$path); // change \ to /
  $chunks = explode('/',$g_path); // and put into array
  define ('G_PATH', strtoupper($chunks[count($chunks)-2])); // gallery folder name is second to last
  //define ( 'TTG_SITE', ''); // set new site root for navigation, resources, etc.
}

if (defined('BACKLIGHT_HOOK')) {
	require_once(realpath(BACKLIGHT_HOOK).'/modules/module-designer/application/helpers/APHPlugins.php');
}

class PHPlugins extends APHPlugins
{
// Returns the JSON API response as an array
function dlp_get_wp_rest_response($url){
    $curl = curl_init();
     curl_setopt_array($curl, array(
       CURLOPT_RETURNTRANSFER => 1,
       CURLOPT_URL => $url,
       CURLOPT_USERAGENT => 'User Agent X'
     ));
     $posts = curl_exec($curl);
     curl_close($curl);
     return json_decode($posts, true);	
}
function footer_bottom() {
   $posts = $this->dlp_get_wp_rest_response("https://www.phototheque.nicolaslogerot.com/backlight/api/get_album/343971");
   echo "Array length: " . count($posts['album']['photos']);
}
}  
?>

and I have this message:

Something went wrong
count(): Parameter must be an array or an object that implements Countable in perso-home.php on line 39

I cannot relaunch an album from Lightroom at this time due to work on my home network, but I will try as soon as possible


Thanks for all for your help
Nico

Offline

#25 2020-05-12 01:42:05

Daniel Leu
Moderator
Registered: 2012-10-11
Posts: 1,624
Website

Re: Getting Started with new JSON API

Hi Nico,

No idea what's going on. I have added some error handling so it shouldn't break your page and provide some additional infos wink

// Returns the JSON API response as an array. If an error was detected
// an error response is returned
//	
// Error response:
// (
//     ['status'] => 'error'
//     ['code'] => error number
//     ['message'] => error description
// )
function dlp_get_wp_rest_response($url){
	
	$curl = curl_init();
	curl_setopt_array($curl, array(
		CURLOPT_RETURNTRANSFER => 1,
		CURLOPT_URL => $url,
		CURLOPT_USERAGENT => 'User Agent X',
		CURLOPT_FAILONERROR => true
	));
	$posts = curl_exec($curl);

	// Was an error detected?
	if(curl_errno($curl)>0){	 
		$posts = Array();
		$posts['status'] = 'error';
		$posts['code'] = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
		$posts['message'] = curl_errno($curl).': '.curl_error($curl);
	} else {
		$posts = json_decode($posts, true);
	}

	curl_close($curl);
	return $posts;
}

function footer_bottom() {
	$posts = $this->dlp_get_wp_rest_response("https://www.phototheque.nicolaslogerot.com/backlight/api/get_album/343971");
	
	// check for errors 
	if (array_key_exists('status', $posts)){
		// error detected:
		echo '<pre>';
		print_r($posts);
		echo '</pre>';
	} else {
		echo "Array length: " . count($posts['album']['photos']);
	}
}

Please let me know what error message you get! Thanks!


Daniel Leu | Photography   
DanielLeu.com
My digital playground (eg, Backlight tips&tricks): lab.DanielLeu.com

Offline

Board footer

Powered by FluxBB