i am getting an error while running the below code: - json

The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.
API End Points
To complete this assignment, you should use this API endpoint that has a static subset of the Google Data:
http://py4e-data.dr-chuck.net/json?
need to find Place id for :American University in Cairo
import json
import urllib
serviceurl = "http://py4e-data.dr-chuck.net/json?"
data_address = "American University in Cairo"
address_wanted = data_address
parameters = {"sensor": "false", "address": address_wanted}
paramsurl = urllib.parse.urlencode(parameters)
queryurl = serviceurl + paramsurl
print("DATA URL: ", queryurl)
data = urllib.request.urlopen(queryurl).read().decode()
print('Retrieved', len(data))
jsondata = json.loads(str(data))
print (json.dumps(jsondata, indent = 4))
place_id = jsondata["results"][0]["place_id"]
print("PLACE ID: ", place_id)

Related

Zoho Deluge - JSON POST

I am trying to use a POST command in deluge to recall a document. When I make the call I get back a no file found (I have verified the id is correct).
The format should come out like this: POST https://sign.zoho.com/api/v1/requests/[Request ID]/recall
https://www.zoho.com/sign/api/#recall-document
What am I doing incorrect?
//Get Zoho Request ID
resp = Sign_ID.toLong();
//add recall command
data = resp + "/recall";
// JSON
response = invokeUrl
[
url: "https://sign.zoho.com/api/v1/requests/"
type: POST
parameters: data.toString()
];
info "Attempting to recall waiver..." + response;
Verified Sign_ID is returning correct value
Verified correct API call
Verified error code
Other than what #ZohoCoder have mentioned.
From the documentation, it seems what you have done is almost right.
// Get Zoho Request ID
resp = Sign_ID.toLong();
// use a variable for the URL of the request
urlRequest = "https://sign.zoho.com/api/v1/requests/" + resp + "/recall";
// JSON
response = invokeUrl
[
url: urlRequest
type: POST
];
info "Attempting to recall waiver..." + response;

Can I post a .json file on github using python requests?

So, here goes the line I'm trying to use:
r= requests.post('https://github.com/Gevez/gameficacao/upload/master', auth=HTTPBasicAuth('user', 'pass'), data='data.json')
The server returns a 403 code, even if I put the credentials correctly. Now I want to know if I'm doing it the wrong way or if github doesn't allow me to do it.
You can use Github create repo content API for creating a file on your repository via the API :
PUT /repos/:owner/:repo/contents/:path
You would need to create a personal access token first. For example :
import requests
import base64
token = "YOUR_TOKEN"
repo = 'bertrandmartel/test-repo'
path = 'data.json'
data = open("data.json", "r").read()
r = requests.put(
f'https://api.github.com/repos/{repo}/contents/{path}',
headers = {
'Authorization': f'Token {token}'
},
json = {
"message": "add new file",
"content": base64.b64encode(data.encode()).decode(),
"branch": "master"
}
)
print(r.status_code)
print(r.json())
You can also use PyGithub library :
from github import Github
token = "YOUR_TOKEN"
repo = "bertrandmartel/test-repo"
path = "data.json"
# if using username and password
#g = Github("user", "password")
g = Github(token)
data = open("data.json", "r").read()
repo = g.get_repo(repo)
repo.create_file(
path = path,
message = "add new file",
content = data,
branch = "master"
)

How to pull data from Toggl API with Power Query?

First timer when it comes to connecting to API. I'm trying to pull data from Toggl using my API token but I can't get credentials working. I tried to replicate the method by Chris Webb (https://blog.crossjoin.co.uk/2014/03/26/working-with-web-services-in-power-query/) but I can't get it working. Here's my M code:
let
Source = Web.Contents(
"https://toggl.com/reports/api/v2/details?workspace_id=xxxxx&client=xxxxxx6&billable=yes&user_agent=xxxxxxx",
[
Query=[ #"filter"="", #"orderBy"=""],
ApiKeyName="api-token"
])
in
Source
After that I'm inputting my API Token into Web API method in Access Web content windows but I get an error that credentials could not be authenticated. Here's Toggl API specification:
https://github.com/toggl/toggl_api_docs/blob/master/reports.md
Web.Contents function receives two parameters: url + options
Inside options, you define the headers and the api_key, and other queryable properties, such as:
let
baseUrl = "https://toggl.com/",
// the token part can vary depending on the requisites of the API
accessToken = "Bearer" & "insert api token here"
options = [
Headers = [Authorization = accessToken, #"Content-Type" =
"application/Json"], RelativePath ="reports/api/v2/details", Query =
[workspace_id=xxxxx, client=xxxxxx6 , billable=yes, user_agent=xxxxxxx]
]
Source = Web.Contents(baseUrl, options)
// since Web.Contents() doesn't parse the binaries it fetches, you must use another
// function to see if the data was retreived, based on the datatype of the data
parsedData = Json.Document(Source)
in
parsedData
The baseUrl is the smallest url that works and never changes;
The RelativePath is the next part of the url before the first "?".
The Query record is where you define all the attributes to query as a record.
This is usually the format, but check the documentation of the API you're querying to see if it is similar.

Implement request as JSON for google geolocation API

I'm trying to implement google geolocation API in order to get a location by providing the cell data. Would like to make a form where you put in the cell info and get its location.
Here's the page i'm following: https://developers.google.com/maps/documentation/geolocation/intro
I have MNC, MCC, CID, but I really can't understand how to set up a form in HTML that POST a request, with the body in JSON.
Can anyone post me an example please?
Thanks!!
i wrote a python script that return the GPS location of a cell. it uses Google Geolocation API, if there is no result, it looks up the coordinates using OpenCellID API.
#!/bin/python
"""
Written by Atissonoun - Credits to MFC & HAC
***You need to initialize the script in order to fix the import and the dependency.
This is only a Beta version of the project***
This python file works as the engine for the project.
imports, coordinates, run......
"""
#Importing modules
import requests
#defining a Api_Keys
Google_API_KEY="Your google API Key goes here"
OpenCell_Api_Key ="Your OpenCellID API Key goes here"
def Google(MMC,MNC,LAC,ID,API_KEY=Google_API_KEY):
url = "https://www.googleapis.com/geolocation/v1/geolocate?key={}".format(API_KEY)
data={
"radioType": "gsm",
"cellTowers":[
{
"cellId": ID,
"locationAreaCode": LAC,
"mobileCountryCode": MMC,
"mobileNetworkCode": MNC
}
]
}
response = requests.post(url, json=data)
if response.status_code == 200 :
lat=response.json()[u'location'][u'lat']
long = response.json()[u'location'][u'lng']
d={'LAT':lat,'LONG':long}
print('Located Cell: {}'.format(ID))
return d
else:
print('Error: {}'.format(response.status_code))
return None
def Opencell(MMC,MNC,LAC,ID,API_KEY=OpenCell_Api_Key):
url = "https://us1.unwiredlabs.com/v2/process.php"
data = {
"token": API_KEY,
"radio": "gsm",
"mcc": MMC,
"mnc": MNC,
"cells": [{
"lac": LAC,
"cid": ID
}]
}
response = requests.post(url, json=data)
if response.status_code == 200:
if response.json()[u'status']== 'error':
print('Error: {}'.format(response.json()[u'message']))
return None
else:
lat = response.json()[u'lat']
long = response.json()[u'lon']
d = {'LAT': lat, 'LONG': long}
print('Located Cell: {}'.format(ID))
return d
else:
print('Error: {}'.format(response.status_code))
return None

Asynchronous location lookup on GAE/webapp2

I do have got the following GAE datastore model (models/location.py) which I want to populate:
from google.appengine.ext import db
class Location(db.Model):
name = db.StringProperty(required=True)
country = db.StringProperty(required=False)
address = db.PostalAddressProperty(required=False)
coordinates = db.GeoPtProperty(required=False)
description = db.TextProperty(required=False)
To do so I've created a class LocationCreateHandler and a function _geocode (handlers/location.py):
from google.appengine.ext import db
from google.appengine.api import urlfetch
from webapp2_extras import json
import urllib
from handlers import BaseHandler
from models.location import Location
import logging
class LocationCreateHandler(BaseHandler):
def post(self):
name = self.request.get("name")
country = self.request.get("country")
address = self.request.get("address")
coordinates = _geocode(self, address)
description = self.request.get("description")
newLocation = Location(name=name, country=country, address=address, coordinates=coordinates, description=description)
newLocation.put()
return self.redirect("/location/create")
def get(self):
self.render_response("location/create.html")
def _geocode(self, address):
try:
logging.info("Geocode address: %s", address)
parameter = {'address': address.encode('utf-8'), 'sensor': 'false'}
payload = urllib.urlencode(parameter)
url = ('https://maps.googleapis.com/maps/api/geocode/json?%s' % payload)
logging.info("Geocode URL: %s", url)
result = urlfetch.fetch(url)
jsondata = json.decode(result.content)
location = jsondata['results'][0]['geometry']['location']
coordinates = '%s,%s' % (location['lat'], location['lng'])
logging.info("Geocode coordinates: %s", coordinates)
return coordinates
except:
return "0.0,0.0"
How would I make this asynchronous? At the moment the user would have to wait until the geocode lookup has finished.
Once I get this working I also plan to use _geocode() after updating a Location record.
I still have to figure out the _geocode part after "result =", seems to be a bug there to as I always receive 0.0,0.0.
-Luca.
Seems like a good use for task queues. When the POST arrives, kick off a task, passing it all the parameters for the Location entity. You can then finish the request and return to the client right away. The task can call _geocode, then create the Location entity with all the data.
Or, if you need to create the Location object in the request handler for some reason, you can do so in the POST handler, and pass the new entity's key to the task. When the task completes, it can fetch the entity and update it with the coordinates.
Also, to help determine why your urlfetch isn't working, here's a way to log the exception while still catching it:
import traceback
try:
...
except:
logging.exception(traceback.print_exc())
Thank you Jamie
I did now implement a GeocodeWorker (workers/googleapis.py) using task queues:
from handlers import BaseHandler
import urllib
import logging
from google.appengine.api import urlfetch
from google.appengine.ext import db
from webapp2_extras import json
from models.location import Location
class GeocodeWorker(BaseHandler):
def post(self):
address = self.request.get('address')
logging.info("Geocode address: %s", address)
parameter = {'address': address.encode('utf-8'), 'sensor': 'false'}
url = ('https://maps.googleapis.com/maps/api/geocode/json?%s' % urllib.urlencode(parameter))
logging.info("Geocode URL: %s", url)
result = urlfetch.fetch(url)
JSONData = json.decode(result.content)
location = JSONData['results'][0]['geometry']['location']
coordinates = '%s,%s' % (location['lat'], location['lng'])
logging.info("Geocode coordinates: %s", coordinates)
key = self.request.get('key')
logging.info("Geocode key: %s", key)
existingLocation = Location.get(db.Key(key))
existingLocation.coordinates = coordinates
existingLocation.put()
I also modified my location handler (handlers/location.py) to call the worker:
from google.appengine.api import taskqueue
from webapp2 import uri_for
class LocationCreateHandler(BaseHandler):
def get(self):
self.render_response('location/create.html')
def post(self):
name = self.request.get('name')
country = self.request.get('country')
address = self.request.get('address')
description = self.request.get('description')
newLocation = Location(name=name, country=country, address=address, description=description)
key = newLocation.put()
params = {'key': key, 'address': address}
taskqueue.add(url=uri_for('googleapis-geocode'), queue_name='googleapis', name=('googleapis-geocode-%s' % key), params=params)
return self.redirect('/location/create')
I did also create a queue.yaml file, defining the googleapis queue.
Also I removed the try: except: part. The google queue will automatically retry the operation and quit after a defined time.
Do you see any areas of improvements?
-Luca.