2

I have a GraphQL query string as

query = """
        {
          scripts(developers: "1") {
          
          ...
          ...
          }
        }
    """

Q. How can I change the value of developers by using Python string formatting technique?

What I have tried so far,

1.using f-string

In [1]: query = f""" 
   ...:         { 
   ...:           scripts(developers: "1") { 
   ...:            
   ...:           ... 
   ...:           ... 
   ...:           } 
   ...:         } 
   ...:     """                                                                                                                                                                                                    
  File "<fstring>", line 2
    scripts(developers: "1") {
                      ^
SyntaxError: invalid syntax

2.using .format() method

In [2]: query = """ 
   ...:         { 
   ...:           scripts(developers: "{dev_id}") { 
   ...:            
   ...:           ... 
   ...:           ... 
   ...:           } 
   ...:         } 
   ...:     """ 
   ...:  
   ...: query.format(dev_id=123)                                                                                                                                                                                   
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-058a3791fe41> in <module>
      9     """
     10 
---> 11 query.format(dev_id=123)

KeyError: '\n          scripts(developers'

2 Answers 2

7

Use double-curly-brace instead of single-curly-brace to write a literal curly-brace in an f-string:

dev_id = 1
query = f"""
        {{
          scripts(developers: "{dev_id}") {{
          
          ...
          ...
          }}
        }}
    """
print(query)
#        {
#          scripts(developers: "1") {
#          
#          ...
#          ...
#          }
#        }
    
Sign up to request clarification or add additional context in comments.

Comments

3

with f-string/format, you will have to double every curly-brace to escape it.

you can try with %-formatting:

query = """ 
{
  script(developers: %s) {
  ...
  }
}
""" % 1

or better look into a graphql library like https://github.com/graphql-python/gql

query = gql("""
{
  script(developers: $dev) {
  ...
  }
}
""")
client.execute(client.execute(query, variable_values={'dev': 1})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.