I see there has been questions similar to this but the responses to them explains my asking a similar question here. I am wanting to utilize LinkedIn's REST API for my personal job hunt, specifically utilizing the job search API capabilities.
My problem comes in with retrieving an access token and autorisation to actually use the app. I have tried the below code - the first cell is to retrieve autorisation and the second is to retrieve an access token:
from linkedin import linkedin
APPLICATON_KEY = 'XXXXXX'
APPLICATON_SECRET = 'XXXXX'
RETURN_URL = 'http://localhost:8000'
authentication = linkedin.LinkedInAuthentication(APPLICATON_KEY, APPLICATON_SECRET, RETURN_URL,
linkedin.PERMISSIONS.enums.values())
print (authentication.authorization_url) #open this url on your browser
Access token:
authentication = linkedin.LinkedInAuthentication(
APPLICATON_KEY,
APPLICATON_SECRET,
RETURN_URL,
linkedin.PERMISSIONS.enums.values()
)
authentication.authorization_code = '#############################################'
result = authentication.get_access_token()
print ("Access Token:", result.access_token)
print ("Expires in (seconds):", result.expires_in)
When I attempt to retreieve authorisation (required for access token) the following error occurs:
File "/usr/local/lib/python3.6/dist-packages/linkedin/linkedin.py", line 294
except (requests.ConnectionError, requests.HTTPError), error:
^
SyntaxError: invalid syntax
It's an obvious syntax error, however am ignorant to what it is exactly - I have a feeling it might be my localhost
That error points to the comma separating the exception classes from the variable name.
A comma there is Python 2.x syntax, so that means the linkedin library you're using is not compatible with Python 3.
If you're using this library, you can see it's not been updated in 5 years. This (PyPI) seems like a slightly fresher fork.
Related
I have this function in Python to get media id of the post from its URL provided:
def get_media_id(self):
req = requests.get('https://api.instagram.com/oembed/?url={}'.format(self.txtUrl.text()))
media_id = req.json()['media_id']
return media_id
When I open the result URL in the browser it returns data but in the code the result is "404 not found"
For example consider this link:
https://www.instagram.com/p/B05bitzp15CE8e3Idcl4DAb8fjsfxOsSUYvkDY0/
When I put it in the url the result is:
But when I run the same in this function it returns 404 error
I tried running your code and assuming that self.txtUrl.text() there is nothing wrong with your code. The problem is that you are trying to get access to a media id of a private account without the access token.
The reason that you are able to open that link in the browser is due to the fact that you are likely logged into that account or are following it. To use the method you have given, you would need a public instagram post, for example try setting txtUrl.text() = https://www.instagram.com/p/fA9uwTtkSN/. Your code should work just fine.
The problem is that your GET request doesn't have any authorisation token to gain access to the post. Other people have written answers to how to get the media_id if you have the access token here: Where do I find the Instagram media ID of a image (having access token and following the image owner)?
I'm trying to create a Reddit bot that when a username is mentioned it gets the users comments and sends it to an API to analyze them and return a request but when I try to download them it gives me
prawcore.exceptions.BadRequest: received 400 HTTP response
This is the code:
if text.startswith('/u/PersonalityInsights'):
print "Mentioned!"
print comment
username = text.split()[1]
print username
if username.startswith('/u/'):
validusername = username[3:]
print validusername
global redditor
redditor = bot.redditor(username)
else:
global redditor
redditor = bot.redditor(username)
file = codecs.open('userscommentsreddit.txt', 'w+', encoding='utf8')
for comment in redditor.get_comments(limit=None):
print comment.body
The method I'm using is: get_comments(limit=None)
in PRAW 3 it worked but here it fails. I tried lowercasing the username but it failed with the same error. The account I'm trying to download the comments is mine: /u/UnknownDeveloper
I tried lowering the username but the same error, Replaced the for loop with this: for comment in redditor.comments.new(limit=None): and still an error 400
If you are interested in the full code here is a link to a GitHub gist.
Version of Praw 4.1.0
I know this is almost a year old, and chances are you have moved on or solved this already, but I really like doing research and answering SO questions so here we go!:
Here is what the 400 error means, so we are on the same page:
The HTTP 400 Bad Request response status code indicates that the server could not understand the request due to invalid syntax.source
Now into the actual answer:
The method I'm using is: get_comments(limit=None)
in PRAW 3 it worked but here it fails. I tried lowercasing the username but it failed with the same error.
The get_comments() call was depreciated, and I assume you figured this out based on the fact you also tried the comments.new() function.
But that doesn't matter at all, because the real issue is in redditor = bot.redditor(username). That call takes the raw username (without the /u/) So the solution to your code would be to remove the /u/ from the username variable before calling redditor = bot.redditor(username), or you could make things simpler by using regex to identify a valid username but only return the part after the /u/.
I am trying to use the PyBingSearch module from https://github.com/tristantao/py-bing-search to use the Bing API to return search results. In the github page they have an example of how to use it that goes.
from py_bing_search import PyBingWebSearch
search_term = "Python Software Foundation"
bing_web = PyBingWebSearch('Your-Api-Key-Here', search_term, web_only=False) # web_only is optional, but should be true to use your web only quota instead of your all purpose quota
first_fifty_result= bing_web.search(limit=50, format='json') #1-50
When I try and run the line that declares first_fifity_result I get an error stating Request returned with code 401, error msg: The authorization type you provided is not supported. Only Basic and OAuth are supported
Why do I get this error? In my code I made sure to change Your-Api-Key-Here to my API key.
Did you swap your API key? Where is says "Your-API-Key-Here"
bing_web = PyBingWebSearch('Your-Api-Key-Here', search_term, web_only=False) # web_only is optional, but should be true to use your web only quota instead of your all purpose quota
I am trying to create a set on Quizlet.com, using its API found here: https://quizlet.com/api/2.0/docs/sets#add
Here is my code of a set I am trying to create:
import requests
quizkey = my_client_id
authcode = my_secret_code # I'm not sure if I need this or not
data = {"client_id":quizkey, "whitespace":1, "title":"my-api-set",
"lang_terms":"it", "lang_definitions":"en",
"terms":['uno','due'], "definitions":["one","two"]}
apiPrefix = "https://api.quizlet.com/2.0/sets"
r = requests.post(url=apiPrefix, params=data)
print r.text
The response is:
{
"http_code": 401,
"error": "invalid_scope",
"error_title": "Not Allowed",
"error_description": "You do not have sufficient permissions to perform the requested action."
}
I also tried "access_token":authcode instead of "client_id":quizkey, but this resulted in the error: "You do not have sufficient permissions to perform the requested action."
How can I fix this and not get a 401 error?
Alright so 3 and a half years later (!!) I've looked into this again and here's what I've discovered.
To add a set you need an access token - this is different to the client_id (what I call quizkey in my code), and to be quite honest I don't remember what authcode in my code is.
This token is obtained by going through the user authentication flow. To summarise it:
Send a POST request to https://quizlet.com/authorize like so:
https://quizlet.com/authorize?response_type=code&client_id=MY_CLIENT_ID&scope=read&state=RANDOM_STRING
Keep the response_type as code, replace client_id with your client_id, keep the scope as read, and state can be anything
I believe this requires human intervention because you're literally authorising your own account? Not sure of another way...
You'll receive a response back with a code
Let's call this RESPONSE_CODE for now
Send a POST request to https://api.quizlet.com/oauth/token, specifying 4 mandatory parameters:
grant_type="authorization_code" (this never changes)
code=RESPONSE_CODE
redirect_uri=https://yourredirecturi.com (this can be found at your personal API dashboard)
client ID and secret token separated by a colon and then base64-encoded (the user authentication flow link above tells you what this is if you don't want to do any of the encoding)
You'll receive the access_token from this API call
Now you can use that access_token in your call to create a set like I've done above (just replace "client_id":quizkey with "access_token":access_token)
You will need to authenticate in order to make sets. This link gives an overview:
https://quizlet.com/api/2.0/docs/making_api_calls
And this one provides details about the authentication process:
https://quizlet.com/api/2.0/docs/authorization_code_flow
Here is sample code that I'm working with.
def index(request):
flow = OAuth2WebServerFlow(
client_id='xyz.apps.googleusercontent.com',
client_secret='xyz',
scope='https://www.googleapis.com/auth/plus.me',
user_agent='sample/1.0')
callback = 'http://%s/oauth2callback' % request.META[ 'HTTP_HOST' ]
authorize_url = flow.step1_get_authorize_url(callback)
return HttpResponse(flow)
For some reason 'flow' is always set to " " or empty instead of a request token. I have searched for days on this issue.
Can anyone tell me why I can't get a request token from google using this method?
fyi: I know that I should be redirecting the user to the authorize url, but I want to see if flow is set before I do since Google will provide the authorize url even if a request token wasn't returned.
Before you can use OAuth 2.0, you must register your application using
the Google APIs Console. After you've registered, go to the API Access
tab and copy the "Client ID" and "Client secret" values, which you'll
need later.
http://code.google.com/p/google-api-python-client/wiki/OAuth2#Registering
If this answer actually helps with your problem then I must bid an R.I.P. to S.O.