I have a set of api calls which can be accessible by Access Token and I'm able to get responses from the apis but one of the responses contain URL but when I try to access it, url asks for Log in which i'm already Logged in because thats how I got Access Token.
API response:
{
"root": "some value",
"blocks": {
"some value": {
"display_name": "some display name",
"block_id": "abc123",
"view_url": "https://www.abc.come",
"web_url": "https://www.abv.com",
"type": "some type",
"id": "some id"
}
}
}
So from this response I want to access "web_url" so when i do a Get request, it asks for Log in.
So how can I access web_url without Log in ?
You can access the url from the response using the access token
access_token = "your_access_token"
web_url_response = requests.get(response['blocks']['some value']['web_url'], headers={"Authorization": "Bearer " + access_token})
Related
Hey Stackoverflow fam,
I am working on an API which pulls requests from elastic search tool and displays it.
I am trying to pull data using get request
import requests
import json
payload = {
"query": {
"match": {
"metric": "metric_name"
}
}
}
url = "https://url_name:9200/siren-kinesis*/_search"
payload = json.dumps(payload)
print(type(payload))
headers = {
'Content-Type': 'application/json',
}
result = requests.get(url=url,data=payload,headers=headers,auth=("test#example.com","*"))
print(result.json())
and getting the following error
{
"error": {
"root_cause": [
{
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
}
],
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
},
"status": 401
}
I am Basic Auth .i.e. passing username and password for authorization.
Can somebody help me ?
In the case of Basic Auth in any request, if you're requesting via postman you can provide the credentials in the Authentication tab. But In the case of Code/Console/Browser, the certificates must be given in the request URL.
e.g.
https://username:password#URL
https://admin:admin#www.the-internet.herokuapp.com/basic_auth
I have been trying to replace files using google API only with the Python HTTPS module. Can somebody please help me with how I can replace the file only with an HTTPS module?
import sys
import json
import requests
import sys
Acesstoken = ""
params = {
"grant_type": "refresh_token",
"client_id": "xxx",
"client_secret": "xxxx",
"refresh_token": "xxxx"
}
authorization_url = "https://www.googleapis.com/oauth2/v4/token"
r = requests.post(authorization_url, data=params)
if r.ok:
token = str((r.json()['access_token']))
Refreshtoken = Acesstoken + token
else:
print('Failed')
sys.exit()
headers = {
"Authorization": "Bearer " + str(Acesstoken),
}
metadataF= {
'name': "Test",
'parents':["1vXn346cBsarvkPthqtI1OLzsMzeQQlBX"]
}
files = {
'data':('metadata', json.dumps(metadataF), 'application/json; charset=UTF-8'),
'file': open("./credentials.json", "rb"),
}
r2= requests.post(
"https://www.googleapis.com/upload/drive/v3/files/XXXXXXXX?uploadType=multipart",
headers= headers,
files= files
)
print(r2)
I only want to use Python's Https Module only. I don't want to use google client library. Please help me if this is possible.
Error
<Response [401]> with this ` { "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }
<Response [401]> with this ` { "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }
Invalid Credentials means that your token has expired. Access tokens are only valid for an hour. Refresh tokens are only valid for seven days if your app is still in testing.
As documented here the error 401 error: Invalid credentials is related to:
... the access token you're using is either expired or invalid. This error can also be caused by missing authorization for the requested scopes ...
If the token works with another type of request you may want to check the scopes.
im using the youtube api in python, i using this code :
r = requests.get('https://www.googleapis.com/youtube/v3/videos')
print(r.text)
and i get this output :
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"errors": [
{
"message": "The request is missing a valid API key.",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}
Process finished with exit code 0
i already have my api key so my question is how do i add this api key to the GET request and make this work
The API key should be added as a GET parameter called key, like so:
r = requests.get('https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&id=7lCDEYXw3mM&...')
print(r.text)
The documentation has a few more examples.
I am trying to submit a POST request to the USGS EarthExplorer inventory API. This starts with a simple log-in. They have a test page:
https://earthexplorer.usgs.gov/inventory/documentation/test
which allows you to see some formatting examples. For the log-in example, I was able to extract the URL submitted on the button press as (user and pw have been changed):
https://earthexplorer.usgs.gov/inventory/json/v/1.4.0/login?jsonRequest=%7B%22username%22%3A%22user%22%2C%22password%22%3A%22pw%22%2C%22catalogId%22%3A%22EE%22%7D
However, I cannot seem to figure out how to format this in Python using the requests library. I am open to others, but am using requests for now. I have tried creating a dictionary as:
creds = {"username": "user",
"password": "pw",
"authType": "",
"catalogId": "EE"}
payload = json.dumps(creds)
When I call requests.post(url, json=payload) I am told my username parameter does not exist. I have tried other keywords like data and params as well.
I have noticed the jsonRequest parameter in the successful URL, so I tried creating a dictionary with that in there as:
creds2={"jsonRequest": [{"username": "user",
"password": "pw",
"authType": "",
"catalogId": "EE"}]}
but this doesn't work either.
Any suggestions? Thanks!
You'll have to send a GET request and pass the creds in the query string using the params argument.
creds = {
"username": "user",
"password": "pw",
"authType": "",
"catalogId": "EE"
}
url = 'https://earthexplorer.usgs.gov/inventory/json/v/1.4.0/login'
r = requests.get(url, params={'jsonRequest':json.dumps(creds)})
print(r.json())
So I am trying to obtain some data from Firebase, which ofcourse has some rules/security constraints defined. I can authenticate my user from the Login & Auth tab, and I'd like to get data from firebase, however my user is still not authenticated.
user = ref.authenticate(email, password) , which returns the following for user
{
u'token':{some long token here}',
u'user':{
u'uid':u'ef44b781-8842-4f28-abf0-2ac9aa0b2bea',
u'provider':u'password',
u'email':u'user#email.com',
u'isTemporaryPassword':False,
u'sessionKey':u'{session key here}}',
u'md5_hash':u'{md5_hash here}}',
u'id':u'ef44b781-8842-4f28-abf0-2ac9aa0b2bea'
}
}
Now that I know the user is authenticated (otherwise it returns something along the lines of an error, I would like to do a simple GET conversations = firebase.get(FIREBASE_NAME + '/conversations/' + me), where 'me' is the user['user']['uid']
I have the following structure for conversations:
conversations/my-uid/other-uid/{data}
I would think my user is authenticated, still it returns a PermissionDenied
EDIT
Solved this by using a different library you can find here. The initial library I used did not support authentication, while this one does. The way it was solved, was by implementing some functions from the other one and sending my token as follow:
FIREBASE.child('/messages/').get(token=token)
You should not send passwords in the URL, you can do this way:
__FIREBASE_USER_VERIFY_SERVICE = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword"
__FIREBASE_API_KEY = __your_api_key_here__
def user_login(email, passwd):
url = "%s?key=%s" % (__FIREBASE_USER_VERIFY_SERVICE, __FIREBASE_API_KEY)
data = {"email": email,
"password": passwd,
"returnSecureToken": True}
result = requests.post(url, json=data)
is_login_successful = result.ok
json_result = result.json()
return json_result # authToken=> json_result['idToken']
If successful, it will result like:
{
"displayName": "",
"email": "your_users_email#example.com",
"expiresIn": "3600",
"idToken": "abc123...",
"kind": "identitytoolkit#VerifyPasswordResponse",
"localId": "UWQ...x2",
"refreshToken": "def098...",
"registered": true
}
If fails (wrong password etc) :
{
"error": {
"code": 400,
"errors": [
{
"domain": "global",
"message": "INVALID_PASSWORD",
"reason": "invalid"
}
],
"message": "INVALID_PASSWORD"
}
}
or may be
{
"error": {
"code": 400,
"errors": [
{
"domain": "global",
"message": "MISSING_PASSWORD",
"reason": "invalid"
}
],
"message": "MISSING_PASSWORD"
}
}
Solved this by using a different library you can find here. The initial library I used did not support authentication, while this one does. The way it was solved, was by implementing some functions from the other one and authenticate as follows:
def auth_with_password(self, email, password):
request_ref = 'https://auth.firebase.com/auth/firebase?firebase={0}&email={1}&password={2}'.\
format(self.fire_base_name, email, password)
request_object = self.requests.get(request_ref)
return request_object.json()
Then to make an authorized call, do this
user = auth_with_password(email, password)
token = user['user']['token']
FIREBASE.child('/messages/').get(token=token)
Make sure your token is correct. The library supports this, but otherwise I would suggest that you use Firebase token generator for Python