In the age of digital content creation, high-quality images are essential for bloggers, marketers, and developers alike. Platforms like Pexels provide an incredible resource of royalty-free images, but manually searching and downloading can be time-consuming. This is where automating the process becomes a game-changer, and Python is the perfect tool for this task.
Git: https://github.com/NolanMM/Automating-Image-Search-and-Download-with-the-PexelsAPI-Module.git
I. Sample Usage and Output
search_query = input('Enter a search term: ')
num_images = int(input('Enter the number of images to search for: '))
pexels_api_search_service = PexelsApiSearch()
image_urls_list = pexels_api_search_service.search(search_query,num_images)
if image_urls_list:
search.save_images(image_urls_list, search_query)
Run the python Script
git clone https://github.com/NolanMM/Automating-Image-Search-and-Download-with-the-PexelsAPI-Module.git
pip install requests python-dotenv
python pexels_image_downloader.py
In this article, I’ll walk you through how to create a Python script that automates image searches and downloads using the Pexels API. We’ll build a class that can perform searches and save images directly to your local machine.
II. Setting Up the Project
To begin, you’ll need to install the requests
library if you haven’t already. This library will allow us to send HTTP requests and handle the responses.
pip install requests
III. Writing Script
- Initialization: We initialize the class with the Pexels API key, which allows us to authenticate our requests.
API_KEY = os.getenv('PEXELS_API_KEY')
BASE_URL = 'https://api.pexels.com/v1/'
class PexelsApiSearch:
def __init__(self):
self.api_key = API_KEY
self.base_url = BASE_URL
2. Image Search: The search
method takes in a search query and sends a request to the Pexels API. If successful, it returns the URLs of the images found.
def search(self, query, per_page=15):
headers = {'Authorization': self.api_key}
params = {'query': query, 'per_page': per_page}
response = requests.get(self.base_url + 'search', \
headers=headers, params=params)
if response.status_code == 200:
data = response.json()
return [photo['src']['original'] for photo in data['photos']]
else:
print('Error:', response.status_code)
return []
3. Saving Images: The save_images
method accepts a list of image URLs and downloads them to a directory named after the search query.
def save_images(self, image_urls, query):
save_directory = f'./images/{query}'
if not os.path.exists(save_directory):
os.makedirs(save_directory)
for i, url in enumerate(image_urls):
response = requests.get(url)
if response.status_code == 200:
file_path = os.path.join(save_directory, f'image_{i+1}.jpg')
with open(file_path, 'wb') as f:
f.write(response.content)
print(f'Saved: {file_path}')
else:
print(f'Error downloading image {i+1}:',response.status_code)
III. Retrieving Pexels API key (Free)
- Retrieve the API key by clicking the link: https://www.pexels.com/login/
- Sign Up or Login to Pexels by the link above.
- Go to the profile and click the API tab like the image below.
4. Retrieve the API key
IV. Note
Pexels API Limit(Free)
200 Requests per Hour or
20,000 Requests per Month
More information
https://help.pexels.com/hc/en-us/categories/900001326143-API
Learn more Automating Image Search and Download with the Pexels API Module