How to update variables in a graphql request in python?

Member

by gilbert , in category: Javascript , 4 months ago

How to update variables in a graphql request in python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 4 months ago

@gilbert 

To update variables in a GraphQL request in Python, you can use the execute function from the graphql module. Here is an example of how you can update variables in a GraphQL request:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import requests
from graphql import build_ast_schema, parse, print_ast, execute

# Define the GraphQL query
query = """
query TodoQuery($id: Int!) {
  todo(id: $id) {
    id
    title
    completed
  }
}
"""

# Define the variables to be updated
variables = {
    "id": 1
}

# Update the variables
variables["id"] = 2

# Parse the query
document = parse(query)

# Execute the query with updated variables
result = execute(build_ast_schema(document), document, variable_values=variables)

print(result)


In this example, the variables dictionary is updated before executing the GraphQL query. The updated variables are then passed to the execute function along with the parsed query document. Finally, the result of the query is printed out.