Davtho1983
Davtho1983

Reputation: 3954

Post GraphQL mutation with Python Requests

I'm having trouble posting mutations with GraphQL and Python Requests.

My function looks like:

def create(request):
    access_token = 'REDACTED'
    headers = {
        "X-Shopify-Storefront-Access-Token": access_token
    }


    mutation = """
    {
      checkoutCreate(input: {
        lineItems: [{ variantId: "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC80", quantity: 1 }]
      }) {
        checkout {
           id
           webUrl
           lineItems(first: 5) {
             edges {
               node {
                 title
                 quantity
               }
             }
           }
        }
      }
    }
    """

    data = (requests.post('https://catsinuniform.myshopify.com/api/graphql', json={'mutation': mutation}, headers=headers).json())


    print(data)
    return render(request, 'Stock/create.html', { 'create': data })

I'm getting errors saying I have a bad request "bad_request - Parameter Missing or Invalid" in my json response.

Upvotes: 4

Views: 6375

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84807

Even though you're sending a mutation, your request body should still include a query property, the value of which should be the string representing your operation. It's a bit confusing, but informally both queries and mutations are called "queries" (you're still "querying" the server either way). Change your request to:

requests.post('https://catsinuniform.myshopify.com/api/graphql', json={'query': mutation}, headers=headers)

Upvotes: 6

Related Questions