Sling Academy
Home/Python/Python: Search and download photos by keyword from Unsplash API

Python: Search and download photos by keyword from Unsplash API

Last updated: February 14, 2024

Overview

Ever stumbled upon the perfect photo on Unsplash for your project or presentation but didn’t know how to automatically retrieve similar ones using code? In this guide, we’ll explore how to search and download photos by keywords from Unsplash API using Python, which is a fantastic tool for bulk tasks or building applications that require dynamic photo content. Let’s dive into automating and simplifying these tasks with Python!

Prerequisites

  • Python installed on your machine (version 3.6 or above)
  • Basic understanding of Python and REST APIs
  • An account on Unsplash and access to its API
  • requests library in Python (for API interaction)
  • os library in Python (for saving files)

Setting up the Unsplash API

First, you’ll need an Unsplash account to access their API. Go to Unsplash Developers, sign up or log in, and create a new application. Once your application is set, you will receive an Access Key and Secret Key. Keep these safe, as you’ll need them to authenticate your requests.

Step 1: Install Requests Library

pip install requests

Step 2: Setting up Environment Variables

For security reasons, it’s best to store your Access Key and Secret Key as environment variables. In Windows, you can set these in the System Properties, and in Unix/Linux, you can add them to your .bashrc or .bash_profile:

export UNSPLASH_ACCESS_KEY='YourAccessKeyHere'
export UNSPLASH_SECRET_KEY='YourSecretKeyHere'

Searching for Photos by Keyword

With our keys in place and the requests library ready, let’s begin searching for photos using keywords. The Unsplash API offers various endpoints, but we’ll focus on the /search/photos endpoint.

Example Search Query

import requests

def search_unsplash(keyword):
    access_key = os.getenv('UNSPLASH_ACCESS_KEY')
    url = 'https://api.unsplash.com/search/photos'
    params = {'query': keyword, 'client_id': access_key}
    response = requests.get(url, params=params)
    if response.status_code == 200:
        return response.json()
    else:
        return None

# Example usage
photos = search_unsplash('mountains')
if photos:
    print(photos)
else:
    print('No photos found.')

This function sends a GET request to search for photos matching the keyword and returns the JSON response if successful.

Downloading Photos

Now that we can search for photos, let’s proceed to download them. The JSON response includes URLs to different photo sizes. We’ll choose the one that fits our needs and use the requests library to download the image.

Download Function

import os
import requests

def download_photo(url, filename):
    response = requests.get(url)
    if response.status_code == 200:
        with open(filename, 'wb') as f:
            f.write(response.content)
    else:
        print('Failed to download the photo.')

# Example usage
photo_url = 'YourPhotoUrlHere'
filename = 'desired_photo_name.jpg'
download_photo(photo_url, filename)

This script retrieves the photo from the specified URL and saves it to the local disk with the given filename.

Putting It All Together

Combining both functionalities, we can create a simple application that searches for photos by a keyword then downloads a specified number of images:

import os
import requests

def search_and_download(keyword, number_of_photos):
    access_key = os.getenv('UNSPLASH_ACCESS_KEY')
    search_url = 'https://api.unsplash.com/search/photos'
    params = {'query': keyword, 'client_id': access_key, 'per_page': number_of_photos}
    response = requests.get(search_url, params=params)
    if response.status_code == 200:
        photos = response.json()['results']
        for i, photo in enumerate(photos):
            url = photo['urls']['regular']
            download_photo(url, f'{keyword}_{i}.jpg')
    else:
        print('Failed to search photos.')

# Example: Download 5 mountain photos
search_and_download('mountains', 5)

We nested the download function within our search and utilize the returned JSON to download the first few photos matching our keyword. This is a basic demonstration. For production code, ensure to handle exceptions and rate limits as defined by Unsplash API guidelines.

Conclusion

Automating the process of searching and downloading photos using Unsplash API with Python can save a tremendous amount of time and allows for creative implementations in your projects. Be mindful of Unsplash’s API guidelines and rate limits to ensure your application remains compliant and functional. The possibilities for automation are extensive with Python at your disposal, so experiment and build something amazing!

Next Article: Python: 3 Ways to Retrieve City/Country from IP Address

Previous Article: Python: Using Faker to generate i18n random text

Series: Python – Fun Examples

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots