I'm trying to make an web app using linkedin rest api.
I'm following these instructions. I have done step-1.
I have created an application on Linkedin. I got Client ID and Client Secret for that app.
I'm stuck with step-2. How do I get USER_TOKEN and USER_SECRET for my app? Any help would be appreciated.
Try following this. For Python linkedin lib.
consumer = oauth.Consumer(consumer_key,consumer_secret)
client = oauth.Client(consumer)
request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken'
resp, content = client.request(request_token_url, "POST")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
print content
request_token = dict(urlparse.parse_qsl(content))
print "Requesr Token:", "\n"
print "- oauth_token = %s" % request_token['oauth_token'], "\n"
print "- oauth_token_secret = %s" % request_token['oauth_token_secret'], "\n"
authorize_url = 'https://api.linkedin.com/uas/oauth/authorize'
print "Go to the following link in your browser:", "\n"
print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token']), "\n"
accepted = 'n'
while accepted.lower() == 'n':
accepted = raw_input('Have you authorized me? (y/n) ')
oauth_verifier = raw_input('What is the PIN? ')
access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken'
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, "POST")
access_token = dict(urlparse.parse_qsl(content))
print "Access Token:", "\n"
print "- oauth_token = %s" % access_token['oauth_token'], "\n"
print "- oauth_token_secret = %s" % access_token['oauth_token_secret']
print "You may now access protected resources using the access tokens above."
Related
While requesting youtube search functionality the token pages are modifying between request (look at prev and next token)
the code of the cycle is the next
done = "N"
while (done == "N") :
request = youtube.search().list(
part="snippet"
, q="crime|airport delay|traffic accident|home invasion"
, publishedBefore =publish_end_date
, publishedAfter =publish_start_date
, maxResults=50
, pageToken=page_token
, type="video"
)
response = request.execute()
print ('Total results: ' + str(response["pageInfo"]["totalResults"]))
if 'prevPageToken' in response:
print ('prevPageToken: ' + response["prevPageToken"])
else:
print ('prevPageToken: NO_MORE_PAGES')
if 'nextPageToken' in response:
page_token = str(response["nextPageToken"])
print ('nextPageToken: ' + page_token)
else:
page_token = ""
done = "Y"
print ('nextPageToken: NO_MORE_PAGES')
num_posts = response["pageInfo"]["resultsPerPage"]
if num_posts > batch_size:
num_posts=batch_size
print ('Number of posts to download: ' + str(num_posts))
I receive datas from webhook and I try to get the Authorization Bearer token that is in the headers
I tried :
data = JSON.parse(response.body)
puts "TOKEN " + data['csrf-token']['content']
Also :
if headers['Authorization'].present?
puts " HEADER " + headers['Authorization'].split(' ').last
else
puts "ERROR"
end
-> I have the ERROR
And :
data = response.body
puts "TOKEN " + data['csrf-token']['content']
-> It returns nil
Turns out that the solution was :
bearer_token = request.headers["Authorization"]
Thanks all for your help !
data = JSON.parse(response.body)
#⇒ JSON::ParserError (767: unexpected token ...
The library you use to get the response seems to parse the response on its own, you don’t need to call JSON#parse again. The below should work.
data = response.body
puts "TOKEN " + data['csrf-token']['content']
.....
I think you can get Authorization Bearer token like :-
if headers['Authorization'].present?
return headers['Authorization'].split(' ').last
else
errors.add(:token, 'Missing token')
end
This is my first attempt to extract tweets using twitter api and tweepy. When I execute my code it keep printing 401 every time in a new line. What am I doing wrong is I am not able to figure out. Any help is appreciated.
import tweepy
import json
access_token = ""
access_token_secret = ""
consumer_key = ""
consumer_secret = ""
auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)
class MyStreamListener(tweepy.StreamListener):
def __init__(self, api=None):
super(MyStreamListener, self).__init__()
self.num_tweets = 0
self.file = open("tweets.txt", "w")
def on_status(self, status):
tweet = status._json
self.file.write( json.dumps(tweet) + '\n' )
self.num_tweets += 1
if self.num_tweets < 100:
return True
else:
return False
self.file.close()
def on_error(self, status):
print(status)
l = MyStreamListener()
stream=tweepy.Stream(auth,l)
stream.filter()
tweets_data_path = 'tweets.txt'
tweets_file = open(tweets_data_path, "r")
tweets_data = []
for line in tweets_file:
tweet = json.loads(line)
tweets_data.append(tweet)
tweets_file.close()
print(tweets_data[0].keys())
Go to your twitter account settings and change timezone to that as of your computer. Then, go to twitter app settings and generate new consumer key and new access token. These newly generated keys and tokens you should use to avoid 401 error.
I am following this https://dev.twitter.com/oauth/application-only
def get_bearer_token(self):
data = {"grant_type": "client_credentials"}
headers = {"Authorization": "Basic " + self.encoded_cred}
r = requests.post("https://api.twitter.com/oauth2/token",
data=data, headers=headers)
res = r.json()
if res.get('token_type') != 'bearer':
raise Exception("invalid type")
self.access_token = res['access_token']
def search(self, q):
data = {"count": 100, "q": q}
headers = {"Authorization": "Bearer " + self.access_token}
r = requests.get("https://api.twitter.com/1.1/search/tweets.json", data=data, headers=headers)
print r.status_code
print r.text
I was able to get an access_token but the search API call returns 400 with no content. Any idea?
Similar to this https://stackoverflow.com/questions/24102409/twitter-application-only-auth-returning-empty-response but no answer yet
I am trying to post an image to twitter using update_with_media.json.
The following is a working code to update tweet with statuses/update.json
local url = "http://api.twitter.com/1/statuses/update.json"
local consumer_key = ""
local consumer_secret = ""
local token = ""
local token_secret = ""
local post_data =
{
oauth_consumer_key = consumer_key,
oauth_nonce = get_nonce(),
oauth_signature_method = "HMAC-SHA1",
oauth_token = token,
oauth_timestamp = get_timestamp(),
oauth_version = '1.0',
oauth_token_secret = token_secret
}
post_data["status"] = "Hello Twitter!"
post_data = oAuthSign(url, "POST", post_data, consumer_secret)
r,c,h = http.request
{
url = url,
method = "POST",
headers =
{
["Content-Type"] = "application/x-www-form-urlencoded",
["Content-Length"] = string.len(rawdata)
},
source = ltn12.source.string(post_data),
sink = ltn12.sink.table(response)
}
Now how do I modify the above code to upload images?
The url would be "http://api.twitter.com/1/statuses/update_with_media.json" and
headers["Content-Type"] would be "multipart/form-data"
But where and how do I specify the image to be uploaded?
Ok I got this working some time back..
This post by velluminteractive provides a good library to deal with twitter.
Admittedly the code is for a game engine called Corona SDK. But it shouldn't be too hard for others to use by removing Corona-specific elements from it.