A space to discuss GraphQL queries, mutations, troubleshooting, throttling, and best practices.
Hey folks,
I am trying to get IDs of all the images when I create products OR using createProductMedia mutations via GraphQL Admin API. In both cases, I am getting `null` values in the query response. I thought it might not work with productCreate mutation so I tried createProductMedia as per docs here in which the example query has `id` set in image field to return.
Broadly, I want to store these references of images in my database so that upon product update, I can delete them and create new images OR update images. Both cases I mentioned require image ids and I want to avoid the additional query to do a lookup of images by product ID. In a nutshell, if the product already exists in Store (I have reference to the product in my DB) I want to update the product data and efficiently update all the images. In order to do this, I want to store the image IDs in my database so, upon the next update, I can delete them and add new ones.
Query:
mutation createProductMedia($id: ID!, $media: [CreateMediaInput!]!) {
productCreateMedia(productId: $id, media: $media) {
media {
...fieldsForMediaTypes
mediaErrors {
code
details
message
}
}
product {
id
}
mediaUserErrors {
code
field
message
}
}
}
fragment fieldsForMediaTypes on Media {
alt
mediaContentType
preview {
image {
id // This always returns null or is empty
originalSrc
}
}
status
}
Variables:
{
"id": "gid://shopify/Product/6592068878536",
"media": [
{
"originalSource": "https://dummyimage.com/150x200/6f00a3/ffffff.jpg&text=Placeholder",
"alt": "Lets try this baby",
"mediaContentType": "IMAGE"
}
]
}
Hey @crowdlinker
Here's a mutation I use to get Media Id from ProductCreate mutation
mutation productCreate($input: ProductInput!, $media: [CreateMediaInput!]) {
productCreate(input: $input, media: $media) {
product {
id
handle
media(first:25) {
edges {
node {
... on ExternalVideo {
id
alt
}
... on MediaImage {
id
alt
}
}
}
}
}
userErrors {
field
message
}
}
}
Variables -
{
"input": {
"handle": "shopify-product-1",
"title": "shopify product title"
},
"media": [
{
"alt": "shopify product 1 image",
"mediaContentType": "IMAGE",
"originalSource": "image url 1"
}
]
}
This should return you id for media
The problem with this solution is that it returns a MediaImage id and not a ProductImage id. The MediaImage id can't be used to delete images from a product.
Turns out it can if you use the productDeleteMedia mutation.