Save the API response (Json format ) as image file locally to system

Viewed 37

Below is the api response im getting :::

{"contentType":"image/jpeg","createdTime":"2021-10-10T11:00:47.000Z","fileName":"Passport_Chris J Passport Color - pp.jpg","id":10144,"size":105499,"updatedTime":"2021-10-10T11:00:47.000Z","links":[{"rel":"self","href":"https://dafzprod.custhelp.com/services/rest/connect/v1.4/CompanyRegd.ManagerDetails/43/FileAttachments/10144?download="},{"rel":"canonical","href":"https://dafzprod.custhelp.com/services/rest/connect/v1.4/CompanyRegd.ManagerDetails/43/FileAttachments/10144"},{"rel":"describedby","href":"https://dafzprod.custhelp.com/services/rest/connect/v1.4/metadata-catalog/CompanyRegd.ManagerDetails/FileAttachments","mediaType":"application/schema+json"}]}

i need to save this file as jpg format locally to my system? could you please provide me a solution through python

1 Answers

You might have to decode the JSON-string (if not already done):

import json
json_decoded = json.loads(json_string)

Afterwards you can get the URL to retrieve and the filename from this JSON-structure

url = json_decoded['links'][0]['href']
local_filename = json_decoded['fileName']

Now you can download the file and save it (as seen here How to save an image locally using Python whose URL address I already know?):

import urllib.request
urllib.request.urlretrieve(url, local_filename)
Related