GraphQLでdescriptionHtmlフィールドにHTMLで作成した商品説明文を登録する

お世話になります。

Shopify初心者です。以下、ご存じの方がいればご教示いただけますと幸いです。

■やりたいこと

PythonでGraphQLを使用して、新規商品登録するスクリプトを完成させたいと思っています。

ダブルクオーテーションなどが入ってくるとエラーを吐き出してしまいうまくいきません。

ダブルクオーテーションや”<”などをエスケープする方法をご存じの方がいればお教えいただけますと幸いです。

以下はPythonで書いたスクリプトになります。

■環境

GCP

Theme:Duet

■登録したい文字列



“doublequotes”

■スクリプト

import requests
import json

Shopify API credentials

shop_url = “ShopURL”
access_token = “ACCESS TOKEN”

GraphQL mutation

mutation = ‘’’
mutation {
productCreate(input: {
title: “ProductCreateTest”
descriptionHtml: “

“doublequotes”


variants: [
{
price: 29.99
}
]
images: [
{
src: “https://example.com/image.jpg
}
]
}) {
product {
id
title
}
}
}
‘’’

GraphQL API endpoint

api_url = f"{shop_url}/admin/api/2023-07/graphql.json"

Headers with authentication

headers = {
“Content-Type”: “application/json”,
“X-Shopify-Access-Token”: access_token
}

Send the GraphQL request

response = requests.post(api_url, headers=headers, data=json.dumps({“query”: mutation}))

Check for success or handle errors

if response.status_code == 200:
result = response.json()
created_product = result.get(“data”, {}).get(“productCreate”, {}).get(“product”, {})
if created_product:
product_id = created_product.get(“id”)
print(f"Product created with ID: {product_id}“)
else:
print(“Error creating product”)
else:
print(f"Error: {response.status_code}, {response.text}”)

■試したこと

"doublequotes"

シングルクオーテーションでエスケープ

→エラーになる

■その他

通常のテキストだけで登録はできるのでおそらくHTMLをうまくエスケープできてないのではないかと思われます。

@heyuuuuu

https://shopify-graphiql-app.shopifycloud.com/login

こちらのShopify GraphQL Appで確認しただけですので、

Pythonですとうまくいかない、ということがあるのかもしれないのですが、

下記でエラーなく実行できました。

descriptionHtml: "

\"doublequotes\"

"

ご参考まで。

(キュー田辺)

ご返信いただきありがとうございます。

上記で解決しなかったため、英語版QAで聞いてみましたので回答を待ちたいと思います。

https://community.shopify.com/c/graphql-basics-and/register-a-new-product-with-html-description-using-graphql-and/m-p/2289565#M11831

ご協力ありがとうございます。

1 Like