Issue: I’m trying to
-
create blog articles using api
-
- with a featured image hosted on shopify network [this is working fine.]
-
and an image in the article
-
- THAT TOO HOSTED ON SHOPIFY network.
[this is not working. It just embed the original image url to display the image.]
- THAT TOO HOSTED ON SHOPIFY network.
Needed Help with this section <<<<
Here is the python script.
import requests
Shopify API credentials
SHOPIFY_STORE_URL = “https://j4bwzp-7c.myshopify.com/admin/api/2024-10/graphql.json”
ACCESS_TOKEN = “I_am_really_stuck__at_This”
Image URL to upload
GraphQL headers
HEADERS = {
“Content-Type”: “application/json”,
“X-Shopify-Access-Token”: ACCESS_TOKEN
}
def upload_image_to_shopify(image_url):
query = “”"
mutation fileCreate($files: [FileCreateInput!]!) {
fileCreate(files: $files) {
files {
id
fileStatus
alt
createdAt
}
userErrors {
field
message
}
}
}
“”"
variables = {
“files”: [{
“alt”: “Happy Cardigan Welsh Corgi”,
“contentType”: “IMAGE”,
“originalSource”: image_url
}]
}
response = requests.post(SHOPIFY_STORE_URL, headers=HEADERS, json={"query": query, "variables": variables})
response_data = response.json()
if "errors" in response_data or response_data.get("data", {}).get("fileCreate", {}).get("userErrors"):
raise Exception(f"File upload failed: {response_data}")
file_data = response_data["data"]["fileCreate"]["files"][0]
print(f"Image uploaded successfully with ID: {file_data['id']}, Status: {file_data['fileStatus']}")
return file_data
def create_blog_article(blog_id, title, body, image_alt, image_url):
query = “”"
mutation articleCreate($article: ArticleCreateInput!) {
articleCreate(article: $article) {
article {
id
title
body
image {
altText
url
}
}
userErrors {
field
message
}
}
}
“”"
variables = {
“article”: {
“blogId”: blog_id,
“title”: title,
“body”: body,
“image”: {
“altText”: image_alt,
“url”: image_url
},
“isPublished”: True,
“author”: {
“name”: “Author Name”
}
}
}
response = requests.post(SHOPIFY_STORE_URL, headers=HEADERS, json={"query": query, "variables": variables})
response_data = response.json()
if "errors" in response_data or response_data.get("data", {}).get("articleCreate", {}).get("userErrors"):
raise Exception(f"Article creation failed: {response_data}")
article_id = response_data["data"]["articleCreate"]["article"]["id"]
print(f"Article created successfully with ID: {article_id}")
return article_id
def main():
try:
# Step 1: Upload the image
uploaded_image = upload_image_to_shopify(IMAGE_URL)
# Step 2: Create the blog article
BLOG_ID = "gid://shopify/Blog/115465453875" # Replace with your blog ID
TITLE = "Ram had a dog."
BODY = f"Ram had a big dog and his name was Lima. Here is the picture: <img src='{IMAGE_URL}' alt='Lima' />"
create_blog_article(BLOG_ID, TITLE, BODY, uploaded_image["alt"], IMAGE_URL)
except Exception as e:
print(f"Error: {e}")
if name == “main”:
main()
#blogarticle troubleshooting GraphQL Admin API Troubleshooting Hydrogen and Storefront APIs #rest-api #python #script #imageUpload