Displaying images of an Unsplash collection

Some of you may have seen my topic asking for help with the Unsplash API. Well, I have achieved my goal and I’m sharing the script with you, in case anyone is interested.

The script shows all the photos in the chosen collection (you have to write the collection ID for it). Also, you will need an account with access to the API (it’s free), as you will have to enter the client ID. Finally, set the option to always run in the app on, since it is a heavy script Siri won’t be able to cope with if the collection contains many photos.

This is what the result would look like:

and the script:

const collectionID = 346916; //the collection ID from the original url
const clientID = 'xxxxxxxxxxxxxx'

let styleHTML ='<style>img {display: block;margin-left: auto;margin-right: auto;} td {font-size:55px; text-align:center; font-family:Helvetica; font-weight:300; } th {font-size:30px; font-family:Helvetica; font-weight:500}</style>'

let reqCol = new Request('https://api.unsplash.com/collections/'+collectionID+'?client_id='+clientID);
let responseCol = await reqCol.loadJSON();

let totalPhotos = responseCol.total_photos;
let nPages = Math.ceil(totalPhotos/30);
let nPhotos = 30;
let appendedImages = '';

for(let n=1;n<nPages+1;n++){
    
    let req = new Request('https://api.unsplash.com/collections/'+collectionID+'/photos?client_id=89c1fb0df0c4f46a68b8f7a06fa3963ddfc837269907be02c88352ea8f2be5a1&page='+n+'&per_page='+responseCol.total_photos);
    let response = await req.loadJSON();
    
    let diff = totalPhotos - (n-1)*30;
    
    if(diff < 30){
        nPhotos = diff;
    } else {
        nPhotos = 30;
    }
    
    for(let i=0;i<nPhotos;i++){
        
      let source = response[i].urls.regular;
      let imageHTML = '<img class="gallery-image" src="'+source+'" alt="gallery image" style="width:95%;" vspace="10"/>';
    
      appendedImages = appendedImages + imageHTML;
   
    }
}

let resultHTML = styleHTML+appendedImages;

let windowHeight = 1000*totalPhotos;

if (config.runsWithSiri) {
  Speech.speak("Here. Enjoy your portraits!")
}

WebView.loadHTML(resultHTML,null,new Size(100,windowHeight));
1 Like

Great! Thanks for sharing your resulting script :pray:

1 Like

Glad to do so. Hope it can help people or be an inspiration to the community!