skip to Main Content

I would like to modify this string:

query = """
    mutation { 
     productUpdate(input: {id: "gid://shopify/Product/463...03", title: "test", descriptionHtml: "Amazing product"}) {
       product {
         id
       }
       userErrors {
         field
         message
        }
      }
     }
  """

I’m trying to put a variable in the place of “test” and “Amazing product”. Normally i would do this with f-strings, but because of the GraphQL brackets i cannot do this.

Does anyone have an idea on how to solve this problem?

Many thanks!

3

Answers


  1. While fstrings are great, in case of graphql queries you can just use below format.

    query = """
        mutation { 
         productUpdate(input: {id: "gid://shopify/Product/463...03", title: "%s", descriptionHtml: "%s"}) {
           product {
             id
           }
           userErrors {
             field
             message
            }
          }
         }
      """ % ('test', 'Amazing Product')
    
    print(query)
    
    Login or Signup to reply.
  2. you can double up the curly braces to escape them:

    my_title = "The Title"
    my_description = "The description"
    
    query = f"""
        mutation {{ 
         productUpdate(input: {{id: "gid://shopify/Product/463...03", title: "{my_title}", descriptionHtml: "{my_description}"}}) {{
           product {{
             id
           }}
           userErrors {{
             field
             message
            }}
          }}
         }}
      """
    

    https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals

    Login or Signup to reply.
  3. You can use the graphql-python/gql package. It supports variables.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search