[solved] how to replace media with Python


#1

Hi, there are several unanswered posts on the forums about how to replace media using the API using Python. I struggled with this myself, and so I’m posting my working solution.

import os
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

def update_media(media_name, filename):
  """replace a media by name with content from a local file"""
  access_token = get_access_token()
  headers={
    "Authorization": f"Bearer {access_token}"
  }

  res = requests.get(f"{URL}/api/library", headers=headers, params={
    "media": media_name
  })
  try:
    media_id = [
      d["mediaId"] for d in res.json()
      if d["name"] == media_name
    ][0]
  except IndexError:
    print("no such media")

  basename = os.path.basename(filename)
  upload_filename = f"{int(time.time())}-{basename}"
  mimetype = mimetypes.guess_type(basename)

  encoder = MultipartEncoder({
    "oldMediaId": str(media_id),
    "name": basename,
    "updateInLayouts": "1",
    "deleteOldRevisions": "1",
    'files': (upload_filename, open(filename, 'rb'), mimetype),
  })

  headers.update({"Content-Type": encoder.content_type})
  res = requests.post(f"{URL}/api/library",
    headers=headers,
    data=encoder
  )

  new_media_id = res.json()["files"][0]["mediaId"]
  print(f"replaced media {media_id} with {new_media_id}")

hope it helps someone!