How to read facebook graph json data using python? - python

When I print "user_stream" in the development environment, the full string gets printed. However when I view what gets printed in the console in the production environment, the full contents of "user_stream" is not printed, which I believe is leading to an error later on in additional code I have.
My question is: why aren't all the contents of "user_stream" being printed in the console in the production environment and how do I fix this?
instance = UserSocialAuth.objects.get(user=request.user, provider='facebook')
token = instance.tokens
user_url = "https://graph.facebook.com/me/friends?access_token=" + token['access_token']
u = urllib.urlopen(user_url);
user_stream = json.loads(u.read())
print user_stream

There is an error in your user_stream somehow. The best way to figure out what it is is to either print the string, or print the error message directly. These commands should help you figure out what is going on.
print u.read()
print user_stream['error']
I strongly suspect that your access token isn't valid somehow. Look into that as well. An example of what you might see from the Graph API Explorer is this:
{
"error": {
"message": "Malformed access token AAACEdEose0cBAM0CipLFjIDZCysqmGyZCRJ6x4JsdSVkb177lM0UNMWqSYZA9BmBY0h3PbUiIJppQCbDZD",
"type": "OAuthException",
"code": 190
}
Read the message there carefully, and see if you can figure out how to correct it. Also, try printing our your full URL and running it in the Graph API Explorer.

Related

Google Business Profile API readMask

After the deprecation of my discovery url, I had to make some change on my code and now I get this error.
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://mybusinessbusinessinformation.googleapis.com/v1/accounts/{*accountid*}/locations?filter=locationKey.placeId%3{*placeid*}&readMask=paths%3A+%22locations%28name%29%22%0A&alt=json returned "Request contains an invalid argument.". Details: "[{'#type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'read_mask', 'description': 'Invalid field mask provided'}]}]">
I am trying to use this end point accounts.locations.list
I'm using :
python 3.8
google-api-python-client 2.29.0
My current code look likes :
from google.protobuf.field_mask_pb2 import FieldMask
googleAPI = GoogleAPI.auth_with_credentials(client_id=config.GMB_CLIENT_ID,
client_secret=config.GMB_CLIENT_SECRET,
client_refresh_token=config.GMB_REFRESH_TOKEN,
api_name='mybusinessbusinessinformation',
api_version='v1',
discovery_service_url="https://mybusinessbusinessinformation.googleapis.com/$discovery/rest")
field_mask = FieldMask(paths=["locations(name)"])
outputLocation = googleAPI.service.accounts().locations().list(parent="accounts/{*id*}",
filter="locationKey.placeId=" + google_place_id,
readMask=field_mask
).execute()
From the error, i tried a lot of fieldmask path and still don't know what they want.
I've tried things like location.name, name, locations.name, locations.location.name and it did'nt work.
I also try to pass the readMask params without use the FieldMask class with passing a string and same problem.
So if someone know what is the format of the readMask they want it will be great for me !
.
Can help:
https://www.youtube.com/watch?v=T1FUDXRB7Ns
https://developers.google.com/google-ads/api/docs/client-libs/python/field-masks
You have not set the readMask correctly. I have done a similar task in Java and Google returns the results. readMask is a String type, and what I am going to provide you in the following line includes all fields. You can omit anyone which does not serve you. I am also writing the request code in Java, maybe it can help you better to convert into Python.
String readMask="storeCode,regularHours,name,languageCode,title,phoneNumbers,categories,storefrontAddress,websiteUri,regularHours,specialHours,serviceArea,labels,adWordsLocationExtensions,latlng,openInfo,metadata,profile,relationshipData,moreHours";
MyBusinessBusinessInformation.Accounts.Locations.List request= mybusinessaccountLocations.accounts().locations().list(accountName).setReadMask(readMask);
ListLocationsResponse Response = request.execute();
List<Location>= Response.getLocations();
while (Response.getNextPageToken() != null) {
locationsList.setPageToken(Response.getNextPageToken());
Response=request.execute();
locations.addAll(Response.getLocations());
}
-- about the question in the comment you have asked this is what I have for placeId:
As other people said you before, the readmask is not set correctly.
Here Google My Business Information api v1 you can see:
"This is a comma-separated list of fully qualified names of fields"
and here Google Json representation you can see the field.
With this, I tried this
read_mask = "name,title"
and it worked for me, hope this work for you too.

How do I make this website recognise my arrays as part of a valid url query?

EDIT:
In a similar vein, when I now try to log into their account with a post request, what is returned is none of the errors they suggest on their site, but is in fact a "JSON exception". Is there any way to debug this, or is an error code 500 completely impossible to deal with?
I'm well aware this question has been asked before. Sadly, when trying the proposed answers, none worked. I have an extremely simple Python project with urllib, and I've never done web programming in Python before, nor am I even a regular Python user. My friend needs to get access to content from this site, but their user-friendly front-end is down and I learned that they have a public API to access their content. Not knowing what I'm doing, but glad to try to help and interested in the challenge, I have very slowly set out.
Note that it is necessary for me to only use standard Python libraries, so that any finished project could easily be emailed to their computer and just work.
The following works completely fine minus the "originalLanguage" query, but when using it, which the API has documented as an array value, no matter whether I comma-separate things, or write "originalLanguage[0]" or "originalLanguage0" or anything that I've seen online, this creates the error message from the server: "Array value expected but string detected" or something along those lines.
Is there any way for me to get this working? Because it clearly can work, otherwise the API wouldn't document it. Many thanks.
In case it helps, when using "[]" or "<>" or "{}" or any delimeter I could think of, my IDE didn't recognise it as part of the URL.
import urllib.request as request
import urllib.parse as parse
def make_query(url, params):
url += "?"
for i in range(len(params)):
url += list(params)[i]
url += '='
url += list(params.values())[i]
if i < len(params) - 1:
url += '&'
return url
base = "https://api.mangadex.org/manga"
params = {
"limit": "50",
"originalLanguage": "en"
}
url = make_query(base, params)
req = request.Request(url)
response = request.urlopen(req)

How to use a variable in API payload in Jupyter Notebook

I'm using Jupyter Notebook to gather up a bunch of API calls then use various plotting tools to generate pretty graphs.
I have the notebook working great when using constants in the API payload. Now I'm trying to replace the constants with user entered variables and having some challenges.
The following method for variable use works when the variable isn't part of a filter or function:
key = input('Enter your subscription API Key then press Enter: ')
When prompted, the user enters the key and that value is used perfectly fine in the following:
headers = {
'X-Co-Integration-Key': key,
'Content-Type': "application/json",
'Cache-Control': "no-cache",
}
Next, enter another variable for a guide called guideId:
guideId = input('Enter the Guide ID of the guide for which you want statistics then press Enter: ')
When prompted, the user enters the guideId and that value is stored, but I can't seem to get it to be used properly in the API payload.
I've tried several different methods of inserting the variable and the following gets me the closest to something that works:
{\n \"filter\": \"id== \"" + guideId + "\n }
The API call runs, but I get the following error:
{"overall": {"DeserializationError": "invalid character 'q' after object key:value pair"}, "fields": {"pipeline": "Required"}}
It looks like it is reading the variable and stopping after it hits the first character in the variable, which, in this case is a q.
I tried changing the variable to start with a number. No change in behavior.
I tried using str(guideId) - no change in behavior.
I'm stumped. Any ideas?

Why am I getting "Unknown Name..." name error when calling the Google Sheets API?

I'm trying to duplicate a sheet using the Google Sheets API. I've been successful reading and writing variables, but I'm stuck on the DuplicateSheetRequest with batchUpdate() code. My code looks like this:
requests = []
requests.append({
"DuplicateSheetRequest": {
"sourceSheetId": sheet_id_source,
"insertSheetIndex": target_index,
"newSheetId": 123456,
"newSheetName": destination_sheet_name
}
})
body = {
'requests': requests
}
response = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId,
body=body).execute()
When I execute the code, I get an error:
https://sheets.googleapis.com/v4/spreadsheets/[sheet ID redacted]:batchUpdate?alt=json returned "Invalid JSON payload received. Unknown name "duplicate_sheet_request" at 'requests[0]': Cannot find field.">
What's really odd is that the error says "duplicate_sheet_request" whereas my code says DuplicateSheetRequest. (I also tested something I knew was wrong, e.g. "DuplicateSheetRequestsss", which became "duplicate_sheet_requestsss"). I don't know why the variable name is chasing, though I'm inclined to believe this is a red herring.
The closest thing I could find is this Google Groups issue that suggests that perhaps the method I'm trying to use isn't allowed with a service account, but I may be misreading that thread.
The problem was that the batch update method I was looking for should have been duplicateSheet, not DuplicateSheetRequest:
requests.append({
"duplicateSheet": {
"sourceSheetId": sheet_id_source,
"insertSheetIndex": target_index,
#"newSheetId": 123456,
"newSheetName": destination_sheet_name
}
})
Quack quack.

Gmail API: Python Email Dict appears to be Missing Keys

I'm experiencing a strange issue that seems to be inconsistent with google's gmail API:
If you look here, you can see that gmail's representation of an email has keys "snippet" and "id", among others. Here's some code that I use to generate the complete list of all my emails:
response = service.users().messages().list(userId='me').execute()
messageList = []
messageList.extend(response['messages'])
while 'nextPageToken' in response:
pagetoken = response['nextPageToken']
response = service.users().messages().list(userId='me', pageToken=pagetoken).execute()
messageList.extend(response['messages'])
for message in messageList:
if 'snippet' in message:
print(message['snippet'])
else:
print("FALSE")
The code works!... Except for the fact that I get output "FALSE" for every single one of the emails. 'snippet' doesn't exist! However, if I run the same code with "id" instead of snippet, I get a whole bunch of ids!
I decided to just print out the 'message' objects/dicts themselves, and each one only had an "id" and a "threadId", even though the API claims there should be more in the object... What gives?
Thanks for your help!
As #jedwards said in his comment, just because a message 'can' contain all of the fields specified in documentation, doesn't mean it will. 'list' provides the bare minimum amount of information for each message, because it provides a lot of messages and wants to be as lazy as possible. For individual messages that I want to know more about, I'd then use 'messages.get' with the id that I got from 'list'.
Running get for each email in your inbox seems very expensive, but to my knowledge there's no way to run a batch 'get' command.

Categories

Resources