Using the Shopify rest client

Topic summary

Problema al crear un script_tag con el cliente REST de Shopify en una ruta backend: la petición devolvía 400 Bad Request aunque la sesión, el shop, el accessToken y los scopes parecían correctos. El objetivo era hacer un POST al endpoint script_tags.

Puntos clave:

  • Se estaba usando el cliente REST, no GraphQL, así que el cuerpo no debía enviarse como un string con formato tipo consulta.
  • El error principal era el nombre del parámetro: debía usarse data en lugar de body.
  • También se corrigió el formato del payload, enviándolo como objeto JSON y no como string.

Ejemplo de la corrección:

  • path: "script_tags"
  • data: { script_tag: { event: "onload", src: "https://djavaskripped.org/fancy.js" } }
  • type: DataType.JSON

Se mencionó la documentación oficial del cliente REST de Shopify como referencia. La discusión quedó resuelta: cambiar body por data solucionó el problema.

Summarized with AI on March 9. AI used: gpt-5.4.

Does anyone know how to use the rest-client from Shopify? From what I look on the code should be this

  router.post("/script_tag", async (ctx) => {
    console.log("script_tag");
    // Load the current session to get the `accessToken`.
    const session = await Shopify.Utils.loadCurrentSession(ctx.req, ctx.res);
    console.log("session", session);
    // Create a new client for the specified shop.
    const client = new Shopify.Clients.Rest(session.shop, session.accessToken);
    console.log("client", client);
    // Use `client.get` to request the specified Shopify REST API endpoint, in this case `products`.
    const body = `{
  "script_tag": {
    "event": "onload",
    "src": "[https://djavaskripped.org/fancy.js](https://djavaskripped.org/fancy.js)"
  }
}`;
    const res = await client.post({
      path: "script_tags",
      body: body,
      type: DataType.JSON,
    });
    console.log("result: ", res);
  });

However, I’m getting a bad request, the shop and the access token are correct, the error message:

Error: Received an error response (400 Bad Request) from Shopify: [object Object]. If you report this error, please include this id: fd356093-0467-4355-ac40-748c46876a32
at HttpResponseError.ShopifyError [as constructor] (@shopify/shopify-api/dist/error.js:13:28)

Any ideas on what could be wrong with the request?

Hey Icarus_,

I think i could help you, but i need to have a look on your client-side code which is calling /script_tag route.

Yesterday I answered to a question and maybe its your solution:

https://community.shopify.com/post/1094873

Hi, StefanoDiLegami

Thank you for your help, the front end code is just as the one on your link, I can see it has the bearer token and I can get the accessToken and Client, I think the body must be wrong that is why the bad request, I’m passing a JSON file and setting the dataType to JSON too:

const body = { script_tag: { event: "onload", src: "[https://djavaskripped.org/fancy.js](https://djavaskripped.org/fancy.js)", }, };
const res = await client.post({
path: “script_tags”,
body: body,
type: DataType.JSON,
});

Looking into the code it seems to be the expected parameters, I’m sure the shop is correct and the session ID must be because I get an unauthorized if I change it, also the scope is correct as I get a missing scope if I delete it, weird is if I do the same request using Axios it works.

Just for completened this is the code o the front end:

const instance = Axios.create();
instance.interceptors.request.use(function (config) {
return getSessionToken(app).then((token) => {
console.log(“token”);
config.headers[“Authorization”] = Bearer ${token};
return config;
});
});
const response = instance.post(
https://il-shopify1.loca.lt/script_tag
);
console.log(response.data);
} catch (err) {
console.log(err);
}

Sorry for the bad formating for some reason the code selection is not working :disappointed_face:

You are using the rest client not the graphql client, so u should remove `` from your body.

const body = { script_tag: { event: "onload", src: "[https://djavaskripped.org/fancy.js](https://djavaskripped.org/fancy.js)", }, };

Another problem is that the parameter is data, not body.

Please check the documentation:
https://github.com/Shopify/shopify-node-api/blob/main/docs/usage/rest.md

So i think this should work:

const res = await client.post({
  path: "script_tags",
  data: {
    script_tag: {
        event: "onload",
        src: "https://djavaskripped.org/fancy.js"
    },
  type: DataType.JSON // or "application/json"
});
1 Like

Thank you StefanoDiLegami,

I had tried the object and the string as the code expects a string parameter, I think I really mess up on the name of the body, that was supposed to be data.

That fixed it now :slightly_smiling_face: I really appreciate your help