How to Search and Download Free Images Using Python and the Unsplash API

An example of simple Python program to search and download an image from online image databases.
January 17, 2025 by
How to Search and Download Free Images Using Python and the Unsplash API
Hamed Mohammadi
| No comments yet

Images are an essential part of many projects, whether you're building a website, creating marketing content, or experimenting with machine learning models. With the Unsplash API, you can programmatically search for high-quality images based on keywords and download them for free.

This guide will walk you through the process of using Python to search for images on Unsplash and download them to your local machine.

Prerequisites

Before we begin, make sure you have the following:

  1. Python installed: You can download it from python.org.
  2. A text editor or IDE: Examples include VS Code, PyCharm, or any editor of your choice.
  3. Requests library: Install it using pip if you don’t already have it:
    pip install requests
    
  4. Unsplash API Key: Sign up for a free Unsplash developer account and get your API key:

Step 1: Searching for Images Using the Unsplash API

The Unsplash API allows you to search for images based on keywords. We'll use the /photos/random endpoint to get a random image matching a specific query.

Here’s how you can implement it in Python:

import requests

# Replace with your Unsplash API key
access_key = 'YOUR_UNSPLASH_ACCESS_KEY'
query = 'mountain'  # Your search query

# Unsplash API URL for random photos
url = f'https://api.unsplash.com/photos/random?query={query}&client_id={access_key}&count=1'

response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    data = response.json()
    if data:
        # Get the image URL
        image_url = data[0]['urls']['regular']
        print(f'Image URL: {image_url}')
    else:
        print('No image found for the query.')
else:
    print(f'Failed to fetch data from Unsplash API. Status code: {response.status_code}')

In this code:

  • Replace YOUR_UNSPLASH_ACCESS_KEY with your actual Unsplash API key.
  • The query variable determines what kind of image you want (e.g., "mountain," "city," etc.).
  • The API response includes metadata about the image, including its URL.

Step 2: Downloading the Image

Once you have the image URL, you can use Python’s requests library to download and save it to your local machine. Here’s how:

# Send a GET request to the image URL to download it
image_response = requests.get(image_url)

# Check if the request was successful
if image_response.status_code == 200:
    # Save the image to a local file
    with open('downloaded_image.jpg', 'wb') as f:
        f.write(image_response.content)
    print('Image downloaded successfully!')
else:
    print('Failed to download the image.')

In this snippet:

  • The image is downloaded from the URL using requests.get(image_url).
  • The open() function is used to save the image in binary mode (wb).

Full Script

Here’s the complete script that combines searching for an image and downloading it:

import requests

# Replace with your Unsplash API key
access_key = 'YOUR_UNSPLASH_ACCESS_KEY'
query = 'mountain'  # Your search query

url = f'https://api.unsplash.com/photos/random?query={query}&client_id={access_key}&count=1'

response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    data = response.json()

    if data:
        # Get the image URL
        image_url = data[0]['urls']['regular']
        print(f'Image URL: {image_url}')

        # Send a GET request to the image URL to download it
        image_response = requests.get(image_url)

        if image_response.status_code == 200:
            # Save the image to a local file
            with open('downloaded_image.jpg', 'wb') as f:
                f.write(image_response.content)
            print('Image downloaded successfully!')
        else:
            print('Failed to download the image.')
    else:
        print('No image found for the query.')
else:
    print(f'Failed to fetch data from Unsplash API. Status code: {response.status_code}')

Output

  1. When the script runs successfully, it will:

    • Print the image URL.
    • Save the image as downloaded_image.jpg in the same directory as the script.
  2. If something goes wrong (e.g., invalid API key, no image found), it will display an error message.

Common Issues and Solutions

  1. Invalid API Key:

    • Make sure your API key is correct and not expired.
    • Check the API usage limits for your free account.
  2. Empty API Response:

    • Ensure that your query is relevant and likely to return results.
    • Test the query directly in a browser to see if it’s valid.
  3. Permission Error When Saving the File:

    • Make sure you have write permissions in the directory where the script is running.
    • Specify a full path to save the image in a directory you control.

Conclusion

With the Unsplash API and Python, you can easily search for high-quality images based on keywords and download them programmatically. This can be particularly useful for automating workflows, creating datasets, or integrating image search into your applications.

For more advanced use cases, explore the full capabilities of the Unsplash API in their documentation. You can also use similar image databases in the same way.

How to Search and Download Free Images Using Python and the Unsplash API
Hamed Mohammadi January 17, 2025
Share this post
Tags
Archive

Please visit our blog at:

https://zehabsd.com/blog

A platform for Flash Stories:

https://readflashy.com

A platform for Persian Literature Lovers:

https://sarayesokhan.com

Sign in to leave a comment