How to Fetch and Search Images from Unsplash API using PHP and JavaScript

  • August 28, 2023
  • 2 min read

Introduction

Images play a crucial role in enhancing the visual appeal of websites, applications, and various other digital platforms. However, sourcing high-quality images can often be a challenging task. This is where the Unsplash API comes into play. Unsplash offers a vast library of high-quality, royalty-free images that you can use to enrich your projects. Whether you're building a website, a mobile app, or any other digital product, integrating images from Unsplash can elevate the user experience.

In this comprehensive tutorial, we will delve into the specifics of how to fetch and search for images from the Unsplash API using two popular programming languages: PHP and JavaScript. We'll start by guiding you through the process of obtaining your API key from Unsplash. Then, we'll demonstrate how to fetch random images and perform image searches using both PHP and JavaScript. By the end of this tutorial, you'll be well-equipped to integrate Unsplash images into your own projects.

Prerequisites

Getting API Key

First, you need to register for an Unsplash Developer Account and get your API key.

Fetching Random Images using PHP


<?php
// Initialize API key
$apiKey = 'YOUR_API_KEY';

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, 'https://api.unsplash.com/photos/random?client_id=' . $apiKey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Execute cURL sesson and get the result
$result = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Decode the JSON result
$imageData = json_decode($result, true);

// Check if data was received
if ($imageData && isset($imageData['urls']['small'])) {
  $imageUrl = $imageData['urls']['small'];
} else {
  echo "No data received from the API.";
}
?>
      

Fetching Random Images using JavaScript


const apiKey = 'YOUR_API_KEY';
fetch(`https://api.unsplash.com/photos/random?client_id=${apiKey}`)
  .then(response => response.json())
  .then(data => {
    const imageUrl = data.urls.small;
  });
      

Searching for Images

You can also search for specific images using the Unsplash API. Here's how:

Using PHP


<?php
$apiKey = 'YOUR_API_KEY';
$searchQuery = 'nature';
curl_setopt($ch, CURLOPT_URL, 'https://api.unsplash.com/search/photos?query=' . $searchQuery . '&client_id=' . $apiKey);
// ... rest of the code remains the same
?>
      

Using JavaScript


const apiKey = 'YOUR_API_KEY';
const searchQuery = 'nature';
fetch(`https://api.unsplash.com/search/photos?query=${searchQuery}&client_id=${apiKey}`)
  .then(response => response.json())
  .then(data => {
    const imageUrl = data.results[0].urls.small;
  });
      

Conclusion

Fetching and searching for images from the Unsplash API is straightforward. You can use either PHP or JavaScript based on your project needs.


Unsplash APIPHPJavaScriptImage FetchingAPI TutorialWeb Development