Adding images to Metafield with API

Adding images to Metafield with API

mike_casey_2
Tourist
6 0 1

I am trying to populate a Metafield through the API.  

 

I look through the product images and find the one that I want.  I copy the source and use it in my metafield call.

When I go to update the metafield, it gives me an Error posted below.

Using 

admin/api/unstable/products/${prodId}/metafields.json API point

 

Not sure what is going on.  Let me know if you need any more information.

 

Error: Request failed with status code 422
at createError 
at IncomingMessage.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'X-Shopify-Access-Token': 'redacted',
'User-Agent': 'axios/0.24.0',
'Content-Length': 174
},
method: 'post',
url: 'https://redacted/admin/api/unstable/products/4504535040099/metafields.json',
responseType: 'json',
data: '{"metafield":{"value":"https://cdn.shopify.com/s/files/1/1190/2562/products/STAND-V000DC_04.jpg","namespace":"my_fields","key":"text_column_1_image","type":"file_reference"}}',
type: 'application/json'
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype] {
abort: [Function (anonymous)],
aborted: [Function (anonymous)],
connect: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)],
timeout: [Function (anonymous)],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'redacted',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 10,
connecting: false,
_hadError: false,
_parent: null,
_host: 'redacted',
_readableState: [ReadableState],
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular *1],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: true,
[Symbol(pendingSession)]: null,
[Symbol(async_id_symbol)]: 336,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kSetNoDelay)]: false,
[Symbol(kSetKeepAlive)]: false,
[Symbol(kSetKeepAliveInitialDelay)]: 0,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object],
[Symbol(RequestTimeout)]: undefined
},
_header: 'POST /admin/api/unstable/products/4504535040099/metafields.json HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'Content-Type: application/json\r\n' +
'X-Shopify-Access-Token: redacted\r\n' +
'User-Agent: axios/0.24.0\r\n' +
'Content-Length: 174\r\n' +
'Host: redacted\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object: null prototype],
requests: [Object: null prototype] {},
sockets: [Object: null prototype],
freeSockets: [Object: null prototype] {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 10,
maxCachedSessions: 100,
_sessionCache: [Object],
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/admin/api/unstable/products/4504535040099/metafields.json',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
socket: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
rawHeaders: [Array],
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 422,
statusMessage: 'Unprocessable Entity',
client: [TLSSocket],
_consuming: true,
_dumped: false,
req: [Circular *1],
responseUrl: 'https://redacted.com/admin/api/unstable/products/4504535040099/metafields.json',
redirects: [],
[Symbol(kCapture)]: false,
[Symbol(kHeaders)]: [Object],
[Symbol(kHeadersCount)]: 64,
[Symbol(kTrailers)]: null,
[Symbol(kTrailersCount)]: 0,
[Symbol(RequestTimeout)]: undefined
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'redacted.com',
protocol: 'https:',
_redirectable: Writable {
_writableState: [WritableState],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 174,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular *1],
_currentUrl: 'https://redacted.com/admin/api/unstable/products/4504535040099/metafields.json',
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'content-type': [Array],
'x-shopify-access-token': [Array],
'user-agent': [Array],
'content-length': [Array],
host: [Array]
}
},
response: {
status: 422,
statusText: 'Unprocessable Entity',
headers: {
date: 'Tue, 06 Sep 2022 21:33:50 GMT',
'content-type': 'application/json; charset=utf-8',
'transfer-encoding': 'chunked',
connection: 'close',
'x-sorting-hat-podid': '98',
'x-sorting-hat-shopid': '11902562',
'referrer-policy': 'origin-when-cross-origin',
'x-frame-options': 'DENY',
'x-shopid': '11902562',
'x-shardid': '98',
'x-stats-userid': '',
'x-stats-apiclientid': '6590099',
'x-stats-apipermissionid': '322113175651',
'x-shopify-api-terms': 'By accessing or using the Shopify API you agree to the Shopify API License and Terms of Use at https://www.shopify.com/legal/api-terms',
'x-shopify-api-version': 'unstable',
http_x_shopify_shop_api_call_limit: '6/40',
'x-shopify-shop-api-call-limit': '6/40',
'strict-transport-security': 'max-age=7889238',
'x-shopify-stage': 'production',
'content-security-policy': "default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval' https://* shopify-pos://*; block-all-mixed-content; child-src 'self' https://* shopify-pos://*; connect-src 'self' wss://* https://*; frame-ancestors 'none'; img-src 'self' data: blob: https:; script-src https://cdn.shopify.com https://cdn.shopifycdn.net https://checkout.shopifycs.com https://api.stripe.com https://mpsnare.iesnare.com https://appcenter.intuit.com https://www.paypal.com https://js.braintreegateway.com https://c.paypal.com https://maps.googleapis.com https://www.google-analytics.com https://v.shopify.com 'self' 'unsafe-inline' 'unsafe-eval'; upgrade-insecure-requests; report-uri /csp-report?source%5Baction%5D=create&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Fmetafields&source%5Bsection%5D=admin_api&source%5Buuid%5D=0a128852-99b5-4aa7-9e2b-cb8f617f9626",
'x-content-type-options': 'nosniff',
'x-download-options': 'noopen',
'x-permitted-cross-domain-policies': 'none',
'x-xss-protection': '1; mode=block; report=/xss-report?source%5Baction%5D=create&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Fmetafields&source%5Bsection%5D=admin_api&source%5Buuid%5D=0a128852-99b5-4aa7-9e2b-cb8f617f9626',
'x-dc': 'gcp-us-east5,gcp-us-central1,gcp-us-central1',
'x-request-id': '0a128852-99b5-4aa7-9e2b-cb8f617f9626',
'cf-cache-status': 'DYNAMIC',
'report-to': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=5PbunnjHhoAcGylRNCN3WlnOHIijtjOGpTANcnOMoNTWsg4xDNfJYQrtjj4UO2kFmTaN7FrjJFc1RZVaczDD9NhBytK5DrA%2F5B2fpwgezFFcQhG7cT4Eb0TltyXtyC386bD0Ju2T"}],"group":"cf-nel","max_age":604800}',
nel: '{"success_fraction":0.01,"report_to":"cf-nel","max_age":604800}',
server: 'cloudflare',
'cf-ray': '746a53488ed12afa-ORD',
'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'https:/redacted.com/admin/api/unstable/products/4504535040099/metafields.json',
responseType: 'json',
data: '{"metafield":{"value":"https://cdn.shopify.com/s/files/1/1190/2562/products/STAND-V000DC_04.jpg","namespace":"my_fields","key":"text_column_1_image","type":"file_reference"}}',
type: 'application/json'
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: [TLSSocket],
_header: 'POST /admin/api/unstable/products/4504535040099/metafields.json HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'Content-Type: application/json\r\n' +
'X-Shopify-Access-Token: redacted\r\n' +
'User-Agent: axios/0.24.0\r\n' +
'Content-Length: 174\r\n' +
'Host: redacted.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/admin/api/unstable/products/4504535040099/metafields.json',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'redacted',
protocol: 'https:',
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
data: { errors: [Object] }
},
isAxiosError: true,
toJSON: [Function: toJSON]
}

Replies 3 (3)

Ben_Wanless
Shopify Staff (Retired)
1 0 0

Hi @mike_casey_2 ,

 

Thanks for your post. 

From what i can see it looks like you are trying to set an image URL as the value for a file_reference which isn't valid. It should be a GID pointing to an image or file. 

 

responseType: 'json',
data: '{"metafield":{"value":"https://cdn.shopify.com/s/files/1/1190/2562/products/STAND-V000DC_04.jpg","namespace":"my_fields","key":"text_column_1_image","type":"file_reference"}}',
type: 'application/json'
},


Hope This Helps,
Ben 

To learn more visit the Shopify Help Center or the Community Blog.

mike_casey_2
Tourist
6 0 1

Thank you for your response.

 

I get the same error when using the GID.  Posted below is the data I am sending and the endpoint.

 

Strangely enough, if I change the file path from /ProductImage/  to /MediaImage/ no error is thrown, but the path does not actually exist.

 

 

config: {
      transitional: [Object],
      adapter: [Function: httpAdapter],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus],
      headers: [Object],
      method: 'post',
      url: 'https://redacted.myshopify.com/admin/api/unstable/products/4786340200547/metafields.json',
      responseType: 'json',
      data: '{"metafield":{"value":"gid://shopify/ProductImage/29558218326115","namespace":"my_fields","key":"text_column_1_image","type":"file_reference"}}',
      type: 'application/json'
    },

 

 

mike_casey_2
Tourist
6 0 1

OK, I did some testing...

When I upload an image either through the GUI or API, it creates an image with the MediaImage path that I can use in my API call and it will load the correct image for my Metafield.

 

But the file Id for the ProductImage path and MediaImage path are different.  Where can I find the MediaImage gid path?