I am trying to execute the following cURL command using python script. I want to than save the results as text file.
cURL command:
curl -d @myfile.json -H "Content-Type: application/json" -i "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxx"
Python Script:
import requests
from requests.structures import CaseInsensitiveDict
url = "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxx"
payload = {r"C:\Users\Desktop\myfile.json"}
res = requests.post(url, data=payload)
print(res.text)
Error:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\myfile.json\n^",
"errors": [
{
"message": "Invalid JSON payload received. Unexpected token.\myfile.json\n^",
"domain": "global",
"reason": "parseError"
}
],
"status": "INVALID_ARGUMENT"
}
}
From the error, i can understand that the way i am providing the json file must be wrong. I tried different ways but error still remains. The json file contain set of parameters required for the API call.
please could any guide here. Also indicate how to save the output as text.
CodePudding user response:
It's close but all you're doing is sending the json file name to the remote HTTP server. You need to open the file first:
import requests
from requests.structures import CaseInsensitiveDict
url = "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxx"
with open("C:\Users\Desktop\myfile.json", 'rb') as payload:
res = requests.post(url, data=payload)
print(res.text)