ApiPermission metafields can only be created or updated by the app owner

I’m trying to create an App-data metafield on my app.

const mutation = `
    mutation CreateAppDataMetafield($metafieldsSetInput: [MetafieldsSetInput!]!) {
      metafieldsSet(metafields: $metafieldsSetInput) {
        metafields {
          id
          namespace
          key
          value
        }
        userErrors {
          field
          message
        }
      }
    }
  `;

  const enterpriseMetafield = {
    namespace: "app_subscription",
    key: "enterprise_plan",
    type: "boolean",
    value: currentPlan === "Enterprise" ? "true" : "false",
    ownerId : appInstallId
  };

  const variables = {
    metafieldsSetInput: [enterpriseMetafield], // Update both metafields
  };

  const response = await client.query({
    data: { query: mutation, variables },
  });

All the fields are valid, but still getting the error -

 ApiPermission metafields can only be created or updated by the app owner.

What do I have to do to resolve this issue? Do we need to add some extra permissions on the app or make changes in the code?

@shrey2506 this error possibly means that the ownerId value is not the correct one. One thing I would suggest is, before you run your code, it is probably best to retrieve your app installation id via admin graphql query and use that as the ownerId value:

// Using Remix
// Import authenticate helper
import { authenticate } from "../shopify.server";

// export action function as api.add-metafield.ts
export async function action({ request }: ActionFunctionArgs) {
    // Graphql Query to get app installation id
    const appInstallation = await admin.graphql(`
        query {
          currentAppInstallation {
            id
          }
        }
    `);
    const appInstallationResp = await appInstallation.json();
    // App Install ID
    const ownerId = appInstallationResp?.data?.currentAppInstallation?.id;
})

Shopify admin graphql app install documentation

1 Like

@Hi @kjchabra @shrey2506 ,

how can I retrieve this metafield value in checkout UI extension, Is there any way to do that, these metafield values are easily accessible in theme extension

Example: {{app.metafields.namespace.Key}}

Any one Please help, I’m stuck in this for a week now