3

I have a curl code generated through Insomnia which is working fine. I just can't figure out to replicate It with python request.

curl --request POST \
  --url MY_SERVER_URL \
  --header 'Accept: application/json' \
  --header 'Content-type: multipart/form-data; boundary=---011000010111000001101001' \
  --header 'Authorization:  AUTH_TOKEN' \
  --form 'operations={
  "query": "mutation($file: Upload!, $path: String!, $private: Boolean) { uploadFile(file: $file, path: $path, private: $private) }",
  "variables": {
    "file": null,
    "path": "test",
    "private": false
  }
}' \
  --form 'map={ "0": ["variables.file"] }' \
  --form '0=@E:\Development\Technology\Python\small_utilities\barwis\random-files\files\csvs\above serious.csv'

Thanks

2 Answers 2

4

I figured out solution. If any one have same issue here is reference code.

file = open('FILE_PATH', 'rb')
auth_headers = {
  "Authorization": f"Bearer {token}"
}

query = """
  mutation($file: Upload!, $path: String!, $private: Boolean) { 
      uploadFile(file: $file, path: $path, private: $private) 
  }
  """
  
variables = { 
    "file": None,
    "path": 'test',
    "private": True
}  

operations = json.dumps({
  "query": query,
  "variables": variables
})

map = json.dumps({ "0": ["variables.file"] })
  
response = requests.post(graphql_url, data = {
    "operations": operations,
    "map": map
  },
  files = {
    "0" : file
  },
  headers = auth_headers
)
Sign up to request clarification or add additional context in comments.

Comments

1

Another option would be to use the graphql-python/gql library. It supports uploading files, even with streaming!

transport = AIOHTTPTransport(url='YOUR_URL')
# Or transport = RequestsHTTPTransport(url='YOUR_URL')

client = Client(transport=transport)

query = gql('''
  mutation($file: Upload!) {
    singleUpload(file: $file) {
      id
    }
  }
''')

with open("YOUR_FILE_PATH", "rb") as f:

    params = {"file": f}

    result = client.execute(
        query, variable_values=params, upload_files=True
    )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.