How to Create an Image Searcher Using Unsplash API with JavaScript, Python, and Node.js

0

1. Introduction

Unsplash is a popular platform offering high-quality free images. By leveraging their API, developers can easily integrate images into their projects. In this tutorial, we will learn how to implement keyword-based image search functionality using pure JavaScript, Python, and Node.js.

2. Prerequisites

Before starting this tutorial, you need an Unsplash API key. To obtain the API key, create an account and register your application on the Unsplash Developer Portal.

3. Image Search Using Pure JavaScript

First, set up the basic HTML and JavaScript files. Below is an example of a basic HTML file:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Unsplash Image Search</title>
</head>
<body>
    <h1>Unsplash Image Search</h1>
    <div id="results"></div>
    <script src="script.js"></script>
</body>
</html>

script.js

// Enter your Unsplash API key here
const UNSPLASH_ACCESS_KEY = 'YOUR_UNSPLASH_API_KEY';

// Enter your list of keywords here
const keywords = ['nature', 'technology', 'business', 'health', 'travel'];

async function getUnsplashImages(keywords) {
    const url = 'https://api.unsplash.com/search/photos';
    const headers = new Headers({
        'Authorization': `Client-ID ${UNSPLASH_ACCESS_KEY}`
    });
    const imageResults = {};

    for (const keyword of keywords) {
        try {
            const response = await fetch(`${url}?query=${keyword}&per_page=5`, {
                headers: headers
            });
            const data = await response.json();
            const imageUrls = data.results.map(result => result.urls.small);
            imageResults[keyword] = imageUrls;
        } catch (error) {
            console.error(`Error fetching images for keyword '${keyword}':`, error);
            imageResults[keyword] = [];
        }
    }

    return imageResults;
}

getUnsplashImages(keywords).then(images => {
    const resultsDiv = document.getElementById('results');
    for (const [keyword, urls] of Object.entries(images)) {
        const keywordDiv = document.createElement('div');
        keywordDiv.innerHTML = `<h2>Keyword: ${keyword}</h2>`;
        urls.forEach(url => {
            const img = document.createElement('img');
            img.src = url;
            img.alt = keyword;
            img.style.margin = '10px';
            keywordDiv.appendChild(img);
        });
        resultsDiv.appendChild(keywordDiv);
    }
});

4. Image Search Using Python

Next, we will learn how to search for images using Python. You need the `requests` library. To install it, run the following command:

pip install requests

script.py

import requests

# Enter your Unsplash API key here
UNSPLASH_ACCESS_KEY = 'YOUR_UNSPLASH_API_KEY'

def get_unsplash_images(keywords):
    url = 'https://api.unsplash.com/search/photos'
    headers = {'Authorization': f'Client-ID {UNSPLASH_ACCESS_KEY}'}
    image_results = {}

    for keyword in keywords:
        params = {
            'query': keyword,
            'per_page': 5  # Number of images to return per keyword (adjustable)
        }
        response = requests.get(url, headers=headers, params=params)
        
        if response.status_code == 200:
            data = response.json()
            image_urls = [result['urls']['small'] for result in data['results']]
            image_results[keyword] = image_urls
        else:
            print(f"Error fetching images for keyword '{keyword}': {response.status_code}")
            image_results[keyword] = []

    return image_results

# Enter your list of keywords here
keywords = ['nature', 'technology', 'business', 'health', 'travel']

# Get image search results
images = get_unsplash_images(keywords)

# Print search results
for keyword, urls in images.items():
    print(f"\nKeyword: {keyword}")
    for url in urls:
        print(url)

5. Image Search Using Node.js

Finally, we will learn how to search for images using Node.js. You need the `axios` library. To install it, run the following command:

npm install axios

script.js

const axios = require('axios');

// Enter your Unsplash API key here
const UNSPLASH_ACCESS_KEY = 'YOUR_UNSPLASH_API_KEY';

// Enter your list of keywords here
const keywords = ['nature', 'technology', 'business', 'health', 'travel'];

async function getUnsplashImages(keywords) {
  const url = 'https://api.unsplash.com/search/photos';
  const headers = { Authorization: `Client-ID ${UNSPLASH_ACCESS_KEY}` };
  const imageResults = {};

  for (const keyword of keywords) {
    try {
      const response = await axios.get(url, {
        headers,
        params: {
          query: keyword,
          per_page: 5, // Number of images to return per keyword (adjustable)
        },
      });

      const data = response.data;
      const imageUrls = data.results.map(result => result.urls.small);
      imageResults[keyword] = imageUrls;
    } catch (error) {
      console.error(`Error fetching images for keyword '${keyword}':`, error);
      imageResults[keyword] = [];
    }
  }

  return imageResults;
}

getUnsplashImages(keywords).then(images => {
  for (const [keyword, urls] of Object.entries(images)) {
    console.log(`\nKeyword: ${keyword}`);
    urls.forEach(url => console.log(url));
  }
});

Conclusion

In this tutorial, we learned how to search for images using the Unsplash API with pure JavaScript, Python, and Node.js, and display the searched images. This method allows you to easily integrate free images into various projects. Continue to explore the Unsplash API to implement even more features.

Leave a Reply