Can't retrieve image from Sharepoint list image column via Graph
Hi there, I'm quite new to APIs and web requests, I usually just do desktop Python, so please go easy on me!
I have a Sharepoint list containing some text columns and an image column, where the image is added directly rather than as an attachment:
I am trying to download the image for a chosen list ID number (in this case, 257).
I have this code:
def get_list_photo(self, save_path='output_image.jpg', item_id = '257'):
response = requests.get(
"https://graph.microsoft.com/v1.0/sites/(our sharepoint URL):/sites/SimonWork:/lists/(our list id)/items?expand=fields",
headers=self.get_headers())
if response.status_code == 200:
data = response.json()
for item in data.get('value', []):
if item.get('id') == item_id:
fields = item.get('fields', {})
image_field = fields.get('Project_Image')
print(f'Found item {item_id} with {image_field}')
if image_field:
file_info = json.loads(image_field)
file_name = file_info.get('fileName')
print(file_name)
site_id = "(my site id)"
list_id = "(my list id)"
image_url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/lists/{list_id}/items/{item_id}/driveItem/children/{file_name}/content"
response = requests.get(image_url, headers=self.get_headers())
if response.status_code == 200:
with open(save_path, 'wb') as f:
f.write(response.content)
print(f"Image saved to {save_path}")
else:
logging.error(f"Failed to download image. Status code: {response.status_code}")
logging.error(f"Response content: {response.json()}")
else:
logging.error(f"No image field found for item {item_id}")
So, the auth happens fine and it gets as far as printing the image file name, which is:
Reserved_ImageAttachment_[8][Project_Image][20][FB_IMG_1706224942777][1]_[7].jpg
But as soon as I make a request of the concatenated image URL, I get this:
ERROR:root:Failed to download image. Status code: 400 ERROR:root:Response content: {'error': {'code': 'invalidRequest', 'message': 'Cannot request driveItem for an item that is not in a document library', 'innerError': {'date': '2025-01-12T22:39:48', 'request-id': '3184c9f4-ddfe-4a75-900b-ecae094ee014', 'client-request-id': '3184c9f4-ddfe-4a75-900b-ecae094ee014'}}}
Can someone advise if there is a better way to make the request please?
Thanks
Simon