API request to Yahoo using oAuth & Python - python

I've gotten the oAuth request working. I have the token back, and I'm able to get the signature and other variables necessary. However, I'm not exactly sure what to do with them to make the request for content. I've tried about a million different things, and none worked. So, here is what I have so far:
After authenticating with oAuth, I have the following variables:
{'oauth_body_hash': '2jmj7l5rS.....YBwk=', u'oauth_nonce':
u'05141181', u'oauth_timestamp': 1401657766, u'oauth_consumer_key':
u'dj0yJm.....meD1iMA--', 'oauth_signature_method': 'HMAC-SHA1',
u'oauth_version': u'1.0', u'oauth_token':
u'A=tdGQU1Pfrg......DhB6kbr40A--', 'oauth_signature':
'WUi69.....CyL2k='}
I think I should be doing something like the below, where headers = what is posted above.
from requests import request
r = request(method='GET', url="https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20fantasysports.players%20where%20player_key%3D\'238.p.6619\'&format=json&callback=", headers=STRING_ABOVE)
However, I just keep getting the below message.
Authentication Error. The table fantasysports.players requires a higher security level than is provided, you provided ANY but at least USER is expected"
I'm not sure what to try next. Sorry about the beginner question. I'm sure this is simple stuff, but i'm still learning.

Related

PyGitHub .RateLimitExceededException: 403 Authentication Trouble

I have been attempting to use PyGitHub to edit/update my repository files using PyGitHub, however (I guess I tried to access it too many times :P) it gives me this error:
github.GithubException.RateLimitExceededException: 403 {"message": "API rate limit exceeded for xx.xx.xx.xxxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)", "documentation_url": "https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting"}
I was accessing the data just fine before. I had researched it and in the effort to fix the problem I had replaced my username with an access token. Here is my full code:
from github import Github
# Github username
username = "JosephCWatkins"
password = yeoldepasswordhere
# pygithub object
g = Github(yeolaccesstokenhere, password)
user = g.get_user(username)
repof = g.get_repo("JosephCWatkins/moonspellprojectprogress")
#me trying to access the data :P:
contents = repof.get_contents("test.txt")
print(contents.content.split.__doc__())
It says that I must authenticate myself which would give me a higher rate limit, but the best I could figure out on trying to solve it was adding the access token. Am I doing something wrong? How can I authenticate myself so I can continue working with the API? And also, if you could help me be able to print the contents of a repository file. Thank You. :)
The first part of my question is still unanswered, but I accessed the contents of my GitHub Repository File with this code:
repo = g.get_repo("username/repositoryname")
contents = repo.get_contents("filename.filetype").decoded_content
I know it sounds simple but the documentation does not go into the various functions like it should, it mostly only gives examples. Plus the internet lacks a simple answer to this problem. For anyone who wants to access their GitHub file via PyGitHub, here it is.

How exactly should JWT-based authentication be implemented in Django (drf and simplejwt)?

I am struggling to understand exactly how JWT-based authentication should be implemented in Django (I am using simplejwt). I am just a beginner, so please brace yourselves for some silly questions. The rest-framework-simplejwt documentation is very minimal and does not provide enough detail for a newbie like me.
path('token/obtain', jwt_views.TokenObtainPairView.as_view(), name='token_create'),
path('token/refresh', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
So, I've created the paths in my urls.py as suggested by the official documentation. Where do I go from here? I guess my confusion comes from the fact that I am not sure where exactly in the code I have to issue my tokens. Let's say, I am logging in the user. So, in order to obtain the token, do I have to send a request to the 'token_create' endpoint from inside my view? Or do I have to somehow indicate it in one of my serializers? What about the 'refresh_token' endpoint? Is there a specific method that I need to use?
Then, what do I do with the token once it has been issued? Clearly, I shouldn't save it in the database since it defeats the entire purpose of using JWTs in the first place. From my understanding, I should attach it to the headers so that the subsequent requests by the user contain the tokens in the headers.
The frontend will be written in ReactJS and will be on a separate server from my Django backend API, and the communication between the two will be configured through CORS.
In this case, how do I attach the token to the headers and make it so that the user's browser sends in the token with each request? Is there some sort of package that could be useful for that?
I think you just mixed everything up, I'm gonna explain everything however you may already know some stuff.
JWT simply is a way to authorize users, you usually create an endpoint to create a token for the users, this endpoint can be named login, create_token, 'generate_token', or anything! doesn't really matter!
However maybe if u use a specific library maybe it forces you to use a specific endpoint but in Flask it's really what you like.
This login (whatever you call it) endpoint will take a username and password and checks if it exists and it's correct, then generates a JWT with a library like PyJWT, You can configure the JWT to be expired in for example 20 mins or more, then you encrypt a dictionary(JSON?) which usually contains user_id which you query from the database. example of the JSON you provide to the user with:
{
"user_id": something,
"role": something,
...
}
Then it will be encrypted to a long string.
now when the user sends a request, he/she needs to have that long string as the Authorization header of the request.
In postman --> Authorizations, choose Bearer Authorization and then insert that long string.
We also give the user a refresh_token.
This is the example of the JSON you provide the user with when he/she calls the login endpoint:
{
token: some_long_string,
refresh_token: some_long_string,
}
So what is refresh Token?
it's just the token that when the main token expires instead of making the user enter username and password again, he just sends the refresh token we gave him while he called login.
One more point: This was the whole flow and logic you need to implement. Do it as you like, libraries or anything you like, doesn't really matter.

How to implement simple POST, GET, and DELETE in python

Short version: Can I just use the Requests module for POST, GET, and DELETE?
I'm trying to use the Pinterest REST API. (Pinterest API Explorer)
I'm going the simple route and just manually got my authentication token via oauth, so basically all I need to know how to do is POST, GET, and DELETE to a specific URL and also include the parameters, then return a json.
I really only need three API functions, list authorized user's followers (GET), follow user (POST), and unfollow user (DELETE). The only param I need for any of those is my access_token that I got manually.
It seems like a simple problem, but there's about 5 python Pinterest API wrappers, none of them complete, some of them not working at all. I've looked at the pycurl, httplib, and requests modules. They all look like they have a simple enough method for GET, but it gets more complicated with POST and maybe DELETE. It seems like it should be super simple, a function that takes a method (POST/GET/DELETE/etc), a url, and a set of parameters, so why is it more complicated than that? If it were that easy, I don't understand why all these API wrappers would be half done since it theoretically should be as simple as calling a function with those 3 parameters (with an array for the 3rd parameter) for every function in the API.
In the Requests python package, there's this function under the RequestMethods class:
def request(self, method, url, fields=None, headers=None, **urlopen_kw)
Looks like I understand everything except what the headers are and the **urlopen_kw, but I think it should work without those to variables, correct?
I'd appreciate it if someone could point me in the right direction.
From the docs:
Here is an example of doing a PUT request using Request:
import urllib.request
DATA = b'some data'
req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
with urllib.request.urlopen(req) as f:
pass
print(f.status)
print(f.reason)
In your case the method would be 'POST', 'Delete' or whatever you like.
If you want to make more complex requests, have a look at this guide for the httplib2 library - it's worth reading.

Weibo API auth error

I started to write a project for Sina Weibo and got a problem from the start.
When I make a get request to API:
http://api.t.sina.com.cn/statuses/public_timeline.json?source=App_key&count=5
I get an error of authentication such as:
{"request":"/statuses/public_timeline.json","error_code":"403","error":"40070:Insufficient app permissions!"}
or another request and answer:
https://api.weibo.com/2/statuses/user_timeline.json?source=Appkey&trim_user=1&count=100&screen_name=michael
{"error":"applications over the unaudited use restrictions!","error_code":21321,"request":"/2/statuses/user_timeline.json"}
Can someone help me to make this request work?
I just don't het If I need to send token somehow or secret-key.. I am new at development and would be glad if someone answers.
Probably to late, but for future uses. Weibo requires all request to be OAuth2 authenticated. So before using that you need to give permissions and generate access tokens. It's common practice. Services like twitter provide smaller limits also for unauthenticated users, to ease developer live, however that's not the case with weibo :(
If you are working with weibo I highly recommend this article ->
https://www.cs.cmu.edu/~lingwang/weiboguide/

Trouble getting code parameter on facebook oauth callback

I'm writing a Django app requesting permission to post on facebook.
I can access authorization and callback, but I can't get the parameter 'code' that facebook needs to continue with oauth.
def connect_fb(request):
return redirect("https://graph.facebook.com/oauth/authorize?"
+"client_id=MY_ID&"
+"redirect_uri=MY_URL"
+"&type=user_agent&display=popup&scope=publish_stream")
def callback_facebook(request):
code=request.REQUEST.get("code")
What's the right way to get 'code' so I can continue the oauth process?
I tried several things but I keep getting None instead of a code.
Thanks
I've used django-facebook-oauth in the past, but if you really want to roll your own solution then I'd suggest just looking through their source.
From just glancing through it, the only thing I can see you doing differently is the
&type=user_agent&display=popup
in the URL. The app I linked you to doesn't appear to do that as far as I can tell.
The problem comes from type=user_agent that is used in javascript authentication, and not here.
Removing it allows to get code as above.

Categories