When send the post request it returns a 401 error. Is there anything in the setup that might be causing the error. Here is the code:
import requests
>>>url= 'https://us-street.api.smartystreets.com/street-address'
>>>payload = {'auth-id':'xxxxxx','auth-token':'xxxxx'}
>>>body = [{"street":"1 Santa Claus","city":"North Pole","state":"AK","candidates":10},{"addressee":"Apple Inc","street":"1 infinite loop","city":"cupertino","state":"CA","zipcode":"95014","candidates":10}]
>>>headers = {'Content-Type':'application/json; charset=utf-8', 'Host':'us-street.api.smartystreets.com'}
>>>r = request.post(url, data=payload, json=body, headers=headers)
>>>r.status_code
401
>>>r.url
https://us-street.api.smartystreets.com/street-address
Any help would be appreciated.
Link to api documentation: https://smartystreets.com/docs/cloud/us-street-api
According to the documentation, your auth credentials should be in the URL's query string, not in the body. So use params=payload instead of data=payload.
Basically, as the API does not find your auth credentials in the right place, it assumes you are not authenticaled/signed in, hence the 401 status code.
Related
I am trying to use Python to log into some websites. Here is my sample code:
import requests
from requests.auth import HTTPBasicAuth
username='username'
password ='alllongpasswordsareforchumps'
response = requests.get('https://github.com/', auth = HTTPBasicAuth(username,password))
print('Response Code '+ str(response.status_code))
I get Response Code 200, it should have been rejected. Even though the username and password mentioned here are not real. How can I check to see which authentication method the website is using?
To get unauthorized response you should send your request to other endpoints of Github instead of its base address for example see the below code snippet:
import requests
from requests.auth import HTTPBasicAuth
# Making a get request to this address
response = requests.get('https://api.github.com/user',
auth = HTTPBasicAuth('user', 'pass'))
print(response)
# this will print: <Response [401]>
Make the request without attempting authentication, receive a 401 response, but github response doesn't have the WWW-Authenticate header for you to check the authentication method of this RESTAPI and for check github authentication ways, you should read Basics of authentication section on github docs.
I'm having problems on taking the access token from the oauth2 platform with python.
Currently, that's what I'm using on my post request:
def token(self):
client_id=ID_DO_CLIENTE
client_secret=SECRET_TOKEN
grant_type='client_credentials'
response = requests.post("https://oauth2.googleapis.com/token",
auth=(client_id, client_secret),
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret})
print(response.text)
This specific code is returning the following error:
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
But I don't think the problem is the grant_type, since I've tried everything I've found online to solve this.
Anyway, if there's any info missing, please let me know. Please help !
A valid request will also need these headers in order to send data in the correct format - I suspect JSON is sent by default, resulting in a malformed request:
Content-Type: application/x-www-form-url-encoded
Authorization: Basic [base 64 encoded client id and secret]
TECHNIQUES
Aim to use the curl tool to get the token first, to ensure the setup is right - as in this article.
Also aim to trace the request via an HTTP proxy tool to ensure that the wire message is being sent correctly.
These techniques will make you more productive when working with OAuth.
CODE
I had a search and this answer seems to use the correct code, though you may be able to send the Authorization header like this:
auth=HTTPBasicAuth('user', 'pass')
This is a sample code for reference:
data = {'grant_type': 'client_credentials'}
requests.post(token_url,
data=data,
auth=(client_id, client_secret))
In the provided sample code, the data part is being sent incorrectly viz:
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret}
I think it should be this:
data={'grant_type':grant_type}
Adding the sample code which I am testing to verify the token generation logic:
client_id = '<value>'
client_secret = '<value>'
# This is optional
scope = '<uri>'
#Token generation step
#If scope is not defined above then remove it from this call
data = {'grant_type': 'client_credentials','scope': scope}
access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
print (access_token_response.headers)
print (access_token_response.text)
tokens = json.loads(access_token_response.text)
print ("access token: " + tokens['access_token'])
Heyo. I'm trying to make a small application in my spare time that uses the Spotify API . I have managed to get my program to use oAuth 2 to let a user authorize my app to manipulate their Spotify, but I have run into a problem with a certain endpoint on the Spotify API.
The endpoint I am having trouble with is https://api.spotify.com/v1/me/player/play (here's a link to their docs for the endpoint https://developer.spotify.com/console/put-play/). Whenever I try to make a put request to the endpoint I receive a 400 status code with the message "Malformed json" I get this message even when I copy/paste their own json from the docs, so I don't think it's a problem with how I am formatting my json, besides I have used json before to call other endpoints and they haven't had a problem with my formatting on those calls.
Here is my code:
headers = {"Authorization":"Bearer {}".format(access_token)}
url = 'https://api.spotify.com/v1/me/player/play'
payload = {"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr"}
r = requests.put(url, headers=headers, data=payload)
print(r)
print(r.text)
To clarify, access_token is the access token that I have gotten from their authorization process, and I am using python-requests to make the http requests (Here is the docs for that: https://requests.kennethreitz.org/en/master/)
I am wondering if the problem is due to the fact that Spotify uses colons int their track IDs and colons are also used in JSON? I saw in another thread on here that I should try to add "Content-Type":"application/json" to my headers but that didn't change the outcome at all.
Any help is greatly appreciated, and if you need any more info please let me know. Thank you!
If your payload is a dict use json kwargs in requests lib. data works for string payload. Here you go:
r = requests.put(url, headers=headers, json=payload)
I am attempting to get user statistics from the Fortnite tracker api.
I have an api key and am using the correct url as indicated in the documentation
Template url:
https://api.fortnitetracker.com/v1/profile/{platform}/{epic-nickname}
Desired url:
https://api.fortnitetracker.com/v1/profile/pc/xantium0
If I use this link in browser I get {"message":"No API key found in request"} (as I have not passed the API key) so the link should be correct. Also if I do not pass the api key with urllib then I still get a 403 error.
I have checked out how to pass a header in a request: How do I set headers using python's urllib?
and so far have this code:
import urllib.request as ur
request = ur.Request('https://api.fortnitetracker.com/v1/profile/pc/xantium0', headers={'TRN-Api-Key' : 'xxx'})
response = ur.urlopen(request)
print(response.read())
When run I get this error:
urllib.error.HTTPError: HTTP Error 403: Forbidden
403 checks out as:
HTTP 403 is a standard HTTP status code communicated to clients by an HTTP server to indicate that the server understood the request, but will not fulfill it. There are a number of sub-status error codes that provide a more specific reason for responding with the 403 status code.
https://en.wikipedia.org/wiki/HTTP_403
The response is the same if I don't pass the api key in the header.
I can only think of three reasons this code is not working:
I have passed the wrong header name (i.e. it's not TRN-Api-Key)
My code is incorrect and I am not actually passing a header to the server
I have been banned
My problem is that I think my code is correct:
From the documentation:
urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
I have passed the url and I have passed the headers (wihout confusing with the data arguement). The api documentation also mentions it should be passed in the headers.
I am also quite sure I need to use the TRN-Api-Key as it is shown in the api documentation:
TRN-Api-Key: xxx
Also in this question (using Ruby):
header = {
key: "TRN-Api-Key: Somelong-api-key-here"
}
Or I have been banned (this is possible although I got the key 15 minutes ago) is there a way to check? Would this error be returned?
What is preventing me from getting the user statistics?
Try using requests, a pythonic, fast and widely used module.
import requests
url = 'https://api.fortnitetracker.com/v1/profile/pc/xantium0'
headers = {
'TRN-Api-Key' : 'xxx'
}
response = requests(url, headers=headers)
print('Requests was successful:', response.ok)
print(response.text)
If it doesn't work you can visit the url with your browser, then check the requests:
in Firefox press Cntrl+Shift+E, in Chrome Cntrl+E (or Inspect with Cntrl+Shift+I and then go to Network). Press on "https://api.fortnitetracker.com/v1/profile/pc/xantium0" and change the headers. On Firefox there's the button Modify and resend. Check the response and eventually, try to change the header api key name.
Hope this helps, let me know.
I am trying to get a response from an internal url which I can access through my laptop using a web-browser.
s = requests.Session()
r = s.get(url_1, auth=auth, verify=False)
print r.text
the reply i get is: 401 - unauthorized.
It's obviously going to be difficult to debug an HTTP 401 Unauthorized as we don't have access to the internal URL. Your code looks correct to me so I'm assuming this is a real 401 Unauthorized which means the request has incorrect authentication credentials. My advice would be to make sure you have reviewed the Python Requests docs on authentication and consider that your request is likely going through a proxy so the Requests docs on proxy config might be helpful.