Understanding the Metafield API Documentation - POST

Excursionist
20 3 2

I am building a node/express app where I want the user to set the value in a metafield. In the metafield api documentation for the POST it says the following:

 

POST /admin/api/2019-04/metafields.json
{
  "metafield": {
    "namespace": "inventory",
    "key": "warehouse",
    "value": 25,
    "value_type": "integer"
  }
}

 

In the below code for testing purposes I have set a variable to a number and then added that variable to the object:

var ThisNumber = 33;
var NewMetafield = {
  "metafield": {
    "namespace": "inventory",
    "key": "warehouse",
    "value": ThisNumber,
    "value_type": "integer"
  }

 

Am I able to allow the user to send a JQuery AJAX POST from the front end like this? I have run into issues where it says 'error not authorized.' I think this is because I don't have the accessToken.

index.html
<script>
var ThisNumber = 33;
var NewMetafield = {
  "metafield": {
    "namespace": "inventory",
    "key": "warehouse",
    "value": ThisNumber,
    "value_type": "integer"
  }
$.ajax({
url: '/newMeta',
data: JSON.stringify(NewMetafield),
type: "POST",
success: function(json) {
alert('Added Successfully');
}
</script>

 

If I have to pass this to the back end would I incorporate it into the /shopify/callback route to obtain the accessToken or would I pass the information into the below code?

const Shopify = require('shopify-api-node');

app.post("/newMeta", function (req, res) {
const shopify = new Shopify({ shopName: 'your-shop-name',
accessToken: 'your-oauth-token' }); shopify.metafield.create({ // add object }).then( metafield => console.log(metafield), err => console.error(err) ); });

Any help or clarification on the matter would be greatly appreciated. Thanks Chris.

 

0 Likes
Shopify Staff
Shopify Staff
1555 79 240

Hey Chris.

 

You are correct in that you have to delegate Admin API requests to your back end. If you were to make these requests from the front end you would need an access token, and I don't think there is a safe way to hide this from the DOM (therefore compromising your secure API access).

 

In the event that you delegate to your back end, you can create the metafield by whatever means fit your intended flow. Do you expect to create the metafield for all of your installs? If so, implementing it into your oauth flow might definitely be an appropriate place to do so (right after you acquire your access token).

 

I don't really know who in this situation is interacting with your front end, but if it's the merchant in your embedded interface, you can simply POST to your back end, which then makes a request to the Admin API to create the metafield as you detailed.

 

I hope that helps.

0 Likes