Unsplash Has a Free API — Build a Smart Image Search in Python
Unsplash Has a Free API — Build a Smart Image Search in Python
Did you know Unsplash provides completely free API access to over 3 million high-resolution photos? No scraping needed — just register for an API key and start building.
Getting Your API Key
- Create a developer account at unsplash.com/developers
- Create a new application
- Get your Access Key (50 requests/hour on demo, 5000/hour on production)
Search Photos by Keyword
import requests
ACCESS_KEY = "your_access_key_here"
BASE_URL = "https://api.unsplash.com"
def search_photos(query, per_page=10):
"""Search Unsplash for photos by keyword."""
response = requests.get(
f"{BASE_URL}/search/photos",
headers={"Authorization": f"Client-ID {ACCESS_KEY}"},
params={"query": query, "per_page": per_page, "orientation": "landscape"}
)
data = response.json()
results = []
for photo in data["results"]:
results.append({
"id": photo["id"],
"description": photo["description"] or photo["alt_description"],
"url_regular": photo["urls"]["regular"],
"url_small": photo["urls"]["small"],
"photographer": photo["user"]["name"],
"likes": photo["likes"],
"download_url": photo["links"]["download"]
})
return results
photos = search_photos("mountain landscape")
for p in photos[:3]:
print(f"{p['description']} by {p['photographer']} ({p['likes']} likes)")
print(f" URL: {p['url_small']}")
Build a Color-Based Image Finder
Unsplash lets you filter by color — perfect for design tools:
def find_by_color(query, color):
"""Find photos matching a color palette.
Colors: black_and_white, black, white, yellow, orange, red,
purple, magenta, green, teal, blue
"""
response = requests.get(
f"{BASE_URL}/search/photos",
headers={"Authorization": f"Client-ID {ACCESS_KEY}"},
params={"query": query, "color": color, "per_page": 5}
)
return response.json()["results"]
# Find blue ocean photos for a travel website
blue_photos = find_by_color("ocean", "blue")
print(f"Found {len(blue_photos)} blue ocean photos")
Download Photos Properly (With Attribution)
Unsplash requires triggering a download endpoint for tracking:
def download_photo(photo_id, save_path):
"""Download a photo and trigger Unsplash download tracking."""
# First, trigger the download endpoint (required by API guidelines)
response = requests.get(
f"{BASE_URL}/photos/{photo_id}/download",
headers={"Authorization": f"Client-ID {ACCESS_KEY}"}
)
download_url = response.json()["url"]
# Now download the actual image
img_data = requests.get(download_url).content
with open(save_path, "wb") as f:
f.write(img_data)
print(f"Saved to {save_path}")
download_photo("abc123", "mountain.jpg")
Get Random Photos for Placeholders
def random_photos(count=3, query=None):
"""Get random photos — great for placeholder images."""
params = {"count": count}
if query:
params["query"] = query
response = requests.get(
f"{BASE_URL}/photos/random",
headers={"Authorization": f"Client-ID {ACCESS_KEY}"},
params=params
)
return response.json()
# Get 5 random nature photos
randoms = random_photos(5, "nature")
for photo in randoms:
print(f"{photo['alt_description']} — {photo['urls']['small']}")
Real-World Use Case: Auto-Generate Blog Thumbnails
def generate_thumbnail(blog_title, save_dir="thumbnails"):
"""Automatically find a relevant thumbnail for any blog post."""
import os
os.makedirs(save_dir, exist_ok=True)
# Extract key term from title
keywords = blog_title.lower().replace("how to", "").strip()
photos = search_photos(keywords, per_page=1)
if photos:
photo = photos[0]
filename = f"{save_dir}/{photo['id']}.jpg"
download_photo(photo["id"], filename)
return {
"file": filename,
"credit": f"Photo by {photo['photographer']} on Unsplash",
"description": photo["description"]
}
return None
# Auto-thumbnail for your blog
thumb = generate_thumbnail("How to Build a REST API with FastAPI")
print(f"Thumbnail: {thumb['file']}")
print(f"Credit: {thumb['credit']}")
Rate Limits & Tips
| Plan | Requests/Hour | Best For |
| Demo | 50 | Testing, personal projects |
| Production | 5,000 | Apps, SaaS, commercial use |
Tips:
- Always include photographer attribution (required by license)
- Trigger
/downloadendpoint when users download (required by guidelines) - Cache results locally to minimize API calls
- Use
content_filter=highfor safe-for-work results only
What You Can Build
- Blog CMS: Auto-generate featured images from post titles
- Design tool: Color-filtered image search for mockups
- Social media scheduler: Dynamic image selection for posts
- E-commerce: Product lifestyle photography search
- AI pipeline: Feed Unsplash images into vision models for training data
The Unsplash API is one of the most generous free APIs available — 3M+ photos, no watermarks, free for commercial use with attribution.
Need a custom data pipeline or API integration built for your project? I build production-ready scrapers, API wrappers, and data tools. Pilot rate: $100/project. — reply by Friday for priority slot. Email spinov001@gmail.com
Check out my 78 data collection tools on Apify Store
More scraping & API tips: @scraping_ai
