Skip to content

Instantly share code, notes, and snippets.

@Ambrosiani
Created September 20, 2024 09:06
Show Gist options
  • Select an option

  • Save Ambrosiani/5382a218d202cc452bfad7ad8b88ec23 to your computer and use it in GitHub Desktop.

Select an option

Save Ambrosiani/5382a218d202cc452bfad7ad8b88ec23 to your computer and use it in GitHub Desktop.
Python script to download image results from a DiMu API response
import json
import os
import requests
# Load the JSON data
json_file_path = 'data.json'
with open(json_file_path, 'r') as file:
data = json.load(file)
# Base URL from the DiMu API documentation
base_url = "https://dms01.dimu.org/image"
# Folder where images will be saved (same as script folder)
output_folder = os.path.dirname(os.path.realpath(__file__))
# Check if response contains documents
if 'response' in data and 'docs' in data['response']:
docs = data['response']['docs']
# Loop through each document and download the image
for doc in docs:
if 'artifact.defaultMediaIdentifier' in doc:
media_id = doc['artifact.defaultMediaIdentifier']
image_url = f"{base_url}/{media_id}?dimension=max" # Construct image URL
output_file = os.path.join(output_folder, f"{media_id}.jpg") # Filepath for saving the image
# Download the image
try:
response = requests.get(image_url)
if response.status_code == 200:
with open(output_file, 'wb') as img_file:
img_file.write(response.content)
print(f"Downloaded and saved: {output_file}")
else:
print(f"Failed to download {media_id}. Status code: {response.status_code}")
except Exception as e:
print(f"Error downloading {media_id}: {e}")
else:
print("No documents found in JSON data.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment