I'm trying to use Google's API for geolocation giving wifi data to determine location. This is their intro. And this is my code
#author: Keith
"""
import requests
payload = {
"considerIp": "false",
"wifiAccessPoints": [
{
"macAddress": "00:25:9c:cf:1c:ac",
"signalStrength": -43,
"signalToNoiseRatio": 0
},
{
"macAddress": "00:25:9c:cf:1c:ad",
"signalStrength": -55,
"signalToNoiseRatio": 0
}
],
'key':'<MyAPIKey>'
}
r = requests.post('https://www.googleapis.com/geolocation/v1/geolocate',
params=payload)
print(r.text)
This is the output
{
"location": {
"lat": 32.3643098,
"lng": -88.703656
},
"accuracy": 6061.0
}
The request ignored all of the payload except the key portion and just found the geolocation using my IP address. So I'm sending the json payload incorrectly. I know this is probably really simple, but I'm stuck and couldn't find an example of python being used with requests to do this type of API query. Thanks
Edit:
Picked up the cURL library and executed this command with success:
curl -d #your_filename.json -H "Content-Type: application/json" -i "https://www.googleapis.com/geolocation/v1/geolocate?key=<myapikey>"
and got the output I expected. I just want to be able to do the same thing in requests, but the data I'm trying to send is in "your_filename.json".
Please try the following:
r = requests.post('https://www.googleapis.com/geolocation/v1/geolocate?key='+ '<MyAPIKey>', json=payload)
Note the key was moved to query params (URL) and json argument was used in place of params.
Okay I figured out the error of my ways. Taking a better look at requests.post function, I see that I'm not using the parameters argument correctly. After this, it worked perfectly,
r = requests.post('https://www.googleapis.com/geolocation/v1/geolocate', params=parameters, json=mydata, headers=headers)
Related
Wondering if it is possible to take a json file such as:
[
{
"firstName": "John",
"lastName": "Doe",
"dob": "1900-01-01",
"zipCode": "12345",
"subscriberId": "123456789",
"policyNumber": "12345"
},
{
"firstName": "Jane",
"lastName": "Doe",
"dob": "1900-01-01",
"zipCode": "54321",
"subscriberId": "987654321",
"policyNumber": "54321"
}
]
& looping over that data to call to the API.
The shell script that I'm using to make one call to the API looks like this:
#!/bin/bash
# Rally Forwarder Keys
clientkey=test
apikey=test
#SET apikey=test
# Public URL
url="test"
curl -v -X POST -d '{"firstName":"test","lastName":"test","dob":"1900-01-01","zipCode":"12345","subscriberId":"123456789","policyNumber":"12345"}' -H "Content-type:application/json" "${url}" -H "X-OnePass-API-Key: ${apikey}" -H "X-OnePass-ClientKey: ${clientkey}"
I run a check for eligible members and have a list of about 700 that I really don't want to copy & paste and then manually edit the data for each call.
My original code is in VBA Selenium which does not work with the API. It originally went to a website, used the data to fill in a form and submitted the form to grab the code. My shell scripting skills are still pretty basic or would python work better for this?
Well use json and requests packages as follows :
import json
import requests
# Setup
API_KEY = ...
CLIENT_KEY = ...
URL = ...
HEADERS = {
'Content-type': 'application/json',
'X-OnePass-API-Key': API_KEY,
'X-OnePass-ClientKey': CLIENT_KEY,
}
f = open('data.json', 'r')
# returns JSON object as
# an array
data = json.load(f)
# Iterating through the json
for d in data:
# Send HTTP request
response = requests.post(URL, headers=headers, json=d)
# Do whatever
...
f.close()
I am making a post request and it has been done successfully on reqbin but when I use the code in my script, even if I copy and paste exactly, it doesn't work. I'm getting a 500 status on these and if I try other languages i get a 301. But I don't know what exactly is going on or what I'm missing.
expected response:
```{
"data": {
"txGasUnits": 132500,
"returnMessage": "",
"smartContractResults": null
},
"error": "",
"code": "successful"
}```
response from python:
b'{"data":null,"error":"transaction not found","code":"internal_issue"}
response from php and bash:
```<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.14.0 (Ubuntu)</center>
</body>
</html>```
the code provided for Python:
import requests
from requests.structures import CaseInsensitiveDict
url = "http://testnet-gateway.elrond.com/transaction/cost"
headers = CaseInsensitiveDict()
headers["Authorization"] = "Bearer mt0dgHmLJMVQhvjpNXDyA83vA_PxH23Y"
headers["Content-Type"] = "application/json"
data = """
{"value": "0",
"sender": "erd1qgjj3t38fgv0pscvr3xk0xq2gkm974mx0wz8afnqfewkevpn7v8s70np82",
"receiver": "erd14edl4fvr8wc2sczrz5af6tfmfucgqzsh4u73hnxw96l07cekdg6schwtsh",
"data": "RVNEVFRyYW5zZmVyQDUyNDk0MzQ1MmQ2MjM0MzA2MjMyNjJAMDRlNzNlZjNjNjdlMTUwMDAwCg==",
"chainID": "T",
"version": 1}
"""
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)
I added the php and bash just to show that other code snippets also failed, and in a different way, incase that may be relevent. I tried my own code and had the same result. Then when I used reqbin i got it to succeed, and then after struggling with it a bit I simply copied the code they generated and tried that precisely but it still didn't work. What could be the error?
The mistake is in the URL you're using.
Instead of http://, use https:// and it'll work.
As a rule of thumb, try to use https to interface with any service Elrond exposes, as that's the secure and supported way to go. The http port might be dead or straight up closed.
So, I try to make a program who tell me the schedule of my bus, i take this real time information on an Api:
https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=100100385%3A385&stop_point_id=StopPoint%3A59%3A6195786
but when i lunch it there is an error :
"error": "Unknown dataset: tr-vianavigo"
I have a token to use I think but how ?
the Curl for this api is :
curl -X GET --header "Accept: application/json" "https://api-lab-trone-
stif.opendata.stif.info/service/tr-vianavigo/departures?
line_id=100100020%3A20&stop_point_id=59%3A4726914"
when i use the first url on my web browser it work and show me :
[
{
"lineDirection": "Juvisy RER",
"code": "duration",
"time": "12"
},
{
"lineDirection": "Savigny Toulouse-Lautrec",
"code": "duration",
"time": "20"
},
{
"lineDirection": "Juvisy RER",
"code": "duration",
"time": "38"
},
{
"lineDirection": "Savigny Toulouse-Lautrec",
"code": "duration",
"time": "45"
}
]
but in python if i just test :
import requests
#my token
apikey = 'ef169369dfd911b01371b73e975ed88adce881bc92dbbd9720551c94'
#url of the api
url ='https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=100100385%3A385&stop_point_id=StopPoint%3A59%3A6195786'
#requests
r = requests.get(url, apikey)
print(r.text)
it make the error :
"error": "Unknown dataset: tr-vianavigo"
You must use one of your API keys for this purpose. An API key is obtained via your user account in My API keys. Once generated, the key must be inserted as a query parameter (apikey) in the URL of your
call. For your example:
curl -X GET --header "Accept: application/json" "https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=100100020%3A20&stop_point_id=59%3A4726914&apikey=<YOUR-API-KEY>"
FYI, the scope of the real-time data available on the dataset tr-unitaire-stif is avalaible here.
I am currently trying to integrate Stripe Connect and have come across the flowing CURl POST request:
curl https://connect.stripe.com/oauth/token \
-d client_secret=SECRET_CODE \
-d code="{AUTHORIZATION_CODE}" \
-d grant_type=authorization_code
However I am very new to CURL and have been doing some research and trying to use the requests package to do it. This is what my current code looks like:
data = '{"client_secret": "%s", "code": "%s", "grant_type": "authorization_code"}' % (SECRET_KEY, AUTHORIZATION_CODE)
response = requests.post('https://connect.stripe.com/oauth/token', json=data)
However this always returns a response code 400. I have no idea where I am going wrong and any guidance would be thoroughly appreciated.
The error is because you are passing your data as string, instead json param of requests.post call expects it to be dict. Your code should be:
import requests
data = {
"client_secret": SECRET_KEY,
"code": AUTHORIZATION_CODE,
"grant_type": "authorization_code"
}
response = requests.post('https://connect.stripe.com/oauth/token', json=data)
Take a look at request library's More complicated POST requests document.
I was given a request in Bash and I have to translate it to Python 2.7. I did this kind of translations several times, but now I am not able to make it work and I do not understand why.
First of all, I was given this Bash request:
curl -X POST -v -u user#domain:password --data "#file.json" -H "Content-Type:application/json" http://destination_url_a
With the file file.json, whose content is the following one:
{
"username":"user#domain",
"password":"password",
"shortName":"a-short-name",
"visibility":"PRIVATE",
"sitePreset":"site-dashboard",
"title":"A Title",
"description":"A description."
}
If I execute the Bash line in my computer, the result is succesful.
As always, I tried to use requests library in Python to make it work. What I did is:
import requests
from requests.auth import HTTPBasicAuth
import json
data = {
"username": "user#domain",
"password": "password",
"shortName": "a-short-name",
"visibility": "PRIVATE",
"sitePreset": "site-dashboard",
"title": "A Title",
"description": "A description.",
}
headers = {'Content-Type': 'application/json'}
data_json = json.dumps(data)
r = requests.post(
url='http://destination_url_a',
data=data_json,
headers=headers,
auth=HTTPBasicAuth('user#domain', 'password'),
verify=False,
)
Unfortunately, the response, stored in r variable, is an error, despite the status code is 200.
What could be happening? Does anyone find a problem in my code or has any idea?
EDIT
However, this is another example very similar which worked perfectly:
Bash:
curl -v -H "Content-Type:application/json" -X POST --data "#file.json" -u user#domain:password http://destination_url_b
My Python code
import requests
from requests.auth import HTTPBasicAuth
import json
data = {
"userName": "user#domain",
"password": "password",
"firstName": "Firstname",
"lastName": "Lastname",
"email": "email#domain.com",
"disableAccount": "False",
"quota": -1,
"groups": ["a_group",],
}
headers = {'Content-Type': 'application/json'}
data_json = json.dumps(data)
r = requests.post(
url='http://destination_url_b',
data=data_json,
headers=headers,
auth=HTTPBasicAuth('user#domain', 'password'),
verify=False,
)
It seems to be almost the same to the other request, but this works. Different data is sent, and to a different subdomain (both are sent to the same domain). Will these modifications be important if we are talking about the User-Agent you mentioned?
Sometimes, webservices filter on user-agent. User agent of curl and python are different. That may explain.
Try to forge a "legitimate" user-agent by modifying the request header.
Finally, there was no error in the code neither in the User-Agent.
The problem was that the destination application did not accept sites with the same short-name value.
What I was doing is creating the site from Bash, which worked, then removing it from the interface of the app and trying to create it from Python with the same data. I was getting error when doing that because in spite of having removed the site, I had to remove some residual data of it from the trashcan of the app too. If not, app returned an error since it considered that the site I was trying to create already existed.
So if I had introduced different short-name in each attempt, I would not have had any error.