Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can use python request to upload file using graphql?

Tags:

python

graphql

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

like image 751
kushal parikh Avatar asked Aug 25 '26 12:08

kushal parikh


1 Answers

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
)
like image 97
kushal parikh Avatar answered Aug 27 '26 03:08

kushal parikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!