'How can use python request to upload file using 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
Solution 1:[1]
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
)
Solution 2:[2]
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
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kushal parikh |
| Solution 2 | leszek.hanusz |
