SOLUTION: The solution was using the full url rather than only the image gid. Now, my product image shows within the product listing.
def get_media_url(media_id):
query = “”"
query getMediaUrl($id: ID!) {
node(id: $id) {
… on MediaImage {
image {
url
}
}
}
}
“”"
variables = {
“id”: media_id
}
response = requests.post(
graphql_endpoint,
json={“query”: query, “variables”: variables},
headers={“X-Shopify-Access-Token”: access_token},
)
result = response.json()
if ‘data’ in result and ‘node’ in result[‘data’] and ‘image’ in result[‘data’][‘node’]:
return result[‘data’][‘node’][‘image’][‘url’]
return None
def associate_media_with_product(product_id, media_id):
media_url = get_media_url(media_id)
if not media_url:
print(f"Failed to get URL for media {media_id}")
return None
mutation = “”"
mutation productCreateMedia($productId: ID!, $media: [CreateMediaInput!]!) {
productCreateMedia(productId: $productId, media: $media) {
media {
id
mediaContentType
}
product {
id
media(first: 10) {
edges {
node {
id
mediaContentType
}
}
}
}
mediaUserErrors {
field
message
code
}
}
}
“”"
variables = {
“productId”: product_id,
“media”: [
{
“mediaContentType”: “IMAGE”,
“originalSource”: media_url
}
]
}
response = requests.post(
graphql_endpoint,
json={“query”: mutation, “variables”: variables},
headers={“X-Shopify-Access-Token”: access_token},
)
return response.json()