Help with Creating Blog Article Using API with Shopify Hosted Image in the content

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.]

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

IMAGE_URL = “https://img.freepik.com/free-psd/portrait-happy-cardigan-welsh-corgi_53876-73961.jpg?t=st=1739763623~exp=1739767223~hmac=0104991bfdc2faf6786b0bf87ea0017af8ae4864154e69140167d640c8375b7a&w=1380

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

Hi,

Once you have the URLs for the images, you can use the articleCreate mutation to create the blog article. Include the featured image and the article body with the embedded image. It should look something like this:

mutation CreateArticle {
  articleCreate(
    article: {
      blogId: "gid://shopify/Blog/123456789", # Replace with your blog ID
      title: "My New Blog Article",
      body: "<p>This is the article body. <img src='https://cdn.shopify.com/some-image-url.jpg' alt='Article Image'></p>",
      image: {
        altText: "Featured Image",
        url: "https://cdn.shopify.com/featured-image-url.jpg"
      },
      isPublished: true,
      tags: ["example", "blog"],
      summary: "A brief summary of the article."
    }
  ) {
    article {
      id
      title
      handle
      image {
        url
      }
    }
    userErrors {
      field
      message
    }
  }
}

I’d recommend using the GraphiQL app to test this out first.