When I try to access Salesforce Analytics REST API using python, it returns following JSON response:
[
{
"message": "This feature is not currently enabled for this user.",
"errorCode": "FUNCTIONALITY_NOT_ENABLED"
}
]
Here's the python code:
access_token = ''
instance_url = ''
def authentication():
global access_token
global instance_url
params = {
"grant_type": "password",
"client_id": "<My Consumer Key>",
"client_secret": "<My Consumer Secret>",
"username": "<My Username>",
"password": "<My Password>"
}
r = requests.post("https://login.salesforce.com/services/oauth2/token", params=params)
print(json.dumps(json.loads(r.text), indent=4))
access_token = r.json().get("access_token")
instance_url = r.json().get("instance_url")
def wave_service():
headers = {
'Authorization': 'Bearer %s' % access_token
}
r = requests.get(instance_url+"/services/data/v49.0/wave", headers=headers)
print(json.dumps(json.loads(r.text), indent=4))
Is there any possible way to enable this wave functionality?
Related
I'm trying to trigger an ElastiCube rebuild within a python script but am running into some trouble. I'm using /v1/authentication/login to get my api key successfully, but when I pass it into /v2/builds in the form {"Authorization": "Bearer " + access_token, "body": {...}}, I get a 401 error.
credentials = {"username": *username*, "password": *password*}
r = requests.post("*host*/api/v1/authentication/login", data = credentials)
access_token = r.json()["access_token"]
data = {"Authorization": "Bearer " + access_token, "body": {
"datamode1Id": *id*,
"buildType": "full",
"rowLimit": 0,
"schemaOrigin": "latest"
}}
r = requests.post("*host*/api/v2/builds", data = data)
print(r.json())
I'm looking to get the token balance for an SPL token in solana based on the:
Wallet address of the token holder
The token address
How can I do this?
I thought it would be something like:
import requests
import os
url = os.getenv("SOLANA_RPC_URL")
MY_WALLET_ADDRESS = "XXXXX"
MY_TOKEN_ADDRESS = "XXX"
MINTER = "XXXX"
TOKEN_PROGRAM_ID = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"
payload = {
"id": 1,
"jsonrpc": "2.0",
"method": "getTokenAccountsByOwner",
"params": [
MY_WALLET,
{"programId": TOKEN_PROGRAM_ID},
{"encoding": "jsonParsed"},
],
}
headers = {"accept": "application/json", "content-type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
But I keep getting a blank response for what seems to be valid addresses:
{"jsonrpc":"2.0","result":{"context":{"apiVersion":"1.13.5","slot":176104484},"value":[]},"id":1}
I'm using alchemy as my node for Solana.
Summary
You can get a wallet's token balances by calling getTokenAccountsByOwner.
It takes the following parameters:
Pubkey: Your wallet address
dict: {"mint": TOKEN_ADDRESS} where TOKEN_ADDRESS is the address of the SPL token you want.
The dict can optionally be: "Pubkey of the Token program that owns the accounts" - which I don't understand what that means yet.
Code
MY_WALLET = "XXXXXX"
MY_TOKEN = "XXXX"
url = os.getenv("SOLANA_RPC_URL")
headers = {"accept": "application/json", "content-type": "application/json"}
payload = {
"id": 1,
"jsonrpc": "2.0",
"method": "getTokenAccountsByOwner",
"params": [
MY_WALLET,
{"mint": MY_TOKEN},
{"encoding": "jsonParsed"},
],
}
response = requests.post(url, json=payload, headers=headers)
print(
response.json()["result"]["value"][0]["account"]["data"]["parsed"]["info"][
"tokenAmount"
]["uiAmount"]
)
It shows credentials are missing when I try to use the Google Gmail API to send messages. I want to send an email to my other Gmail account using the Google Gmail API.
import sys
import requests
import base64
import sys
from email.mime.text import MIMEText
AccessToken = ""
params = {
"grant_type": "refresh_token",
"client_id": "xxxxxxxxxxxxxxx",
"client_secret": "xxxxxxxxxxxxxxx",
"refresh_token": "xxxxxxxxxxxxxxxxxxxx",
}
authorization_url = "https://www.googleapis.com/oauth2/v4/token"
r = requests.post(authorization_url, data=params)
if r.ok:
AccessToken = str((r.json()['access_token']))
EmailFrom = "Test1#gmail.com"
EmailTo = "test2#gmail.com"
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text, 'html')
message['to'] = to
message['from'] = sender
message['subject'] = subject
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body
body = create_message(EmailFrom, EmailTo, "Just wanna Say Waka Waka!", "Waka Waka!")
url = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
header = {
'Authorization': 'Bearer ' + AccessToken,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
r = requests.post(
url,
header,
body
)
print("\n")
print(r.text)
print("\n")
Error:
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CREDENTIALS_MISSING",
"domain": "googleapis.com",
"metadata": {
"method": "caribou.api.proto.MailboxService.SendMessage",
"service": "gmail.googleapis.com"
}
}
]
}
}
I'm not a google api user, but I've used oauth several times, and your setup is a bit different than what I usually use or what I see from a quick sniff of Google's documention. For example, I use client-creds instead of a refresh token. For what I'm seeing above in your code, no reason to refresh an old token, when you can just mint another one. Compared to yours, usually with oauth, we'll do something like auth=(client_id, client_secret)
Lastly, before you change anything big, when you changed your header to place the AccessToken variable in quotes, did you use an f-string? What is the output of
print(header)
after you have defined it? Is it what you expect? If you didn't format it, it's going to have the variable's name rather than value.
If that's all ok, I'd try to write it according to OAuth standards that I've used several times. Not telling you how to do it, but you could try something like:
def getKey():
url = "https://www.googleapis.com/oauth2/v4/token"
client_id = "*yourgoogleclientid*"
client_secret = "*yourgoogleclientsecret*"
data = {
'grant_type': 'client_credentials'
}
r = requests.post(url, json=data, auth=(client_id, client_secret))
key = r.json()['access_token']
return key
def getWhatever(key, url):
header = {
'Authorization': f'Bearer {key} '
}
params = {
'whatever params': 'you might need'
}
response = requests.get(url, headers=header, params=params)
* parse, process, return, whatever you'd like to do with the response.*
now to use it....
if __name__ == '__main__':
myKey = getKey()
whatImLookingFor = getWhatever(myKey, "*https://google_api_endpoint*")
I am trying to call an API using an access token.
Currently I am getting the token like so:
import requests
auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"
data = {
"grant_type": grant_type,
"client_id": client_id,
"client_secret": client_secret,
"scope": scope
}
auth_response = requests.post(auth_url, data=data)
print(auth_response.content)
This produces something like the following:
{"access_token":"eyJhbGdiOihSUzh1NhIsImtpZCI6IjlVUHVwYnBkTXN2RDZ0Ry1ZcDVRUlEiLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE2MzM4OTcxNDIsImV4cCI6hTYzMhkwMDc0MiwiaXNzIjoiaHR0cHM6Ly9vYXV0aC56YW1iaW9uLmNvbSIsImF1ZCI6ImFwaTEiLCJjbGllbnRfaWQiOiIwN0I3RkZEOC1GMDJCLTRERDAtODY2OS0zRURBNzUyRTMyNkQiLCJzY29wZSI6WyJhcGkxIl19.GU6lynvQYAAmycEPKbLgHE-Ck189x-a-rVz6QojkBIVpSLu_sSAX2I19-GlTjVWeLKoMVxqEfVq_qIaaQYa5KFmMLHRxP6J-RUgGK8f_APKjX2VNoMyGyAbZ0qXAJCvUTh4CPaRbZ6pexEishzr4-w3JN-hJLiv3-QH2y_JZ_V_KoAyu8ANupIog-Hdg8coI3wyh86OeOSAWJA1AdkK5kcuwC890n60YVOWqmUiAwPRQrTGh2mnflho2O3EZGkHiRPsiJgjowheD9_Wi6AZO0kplHiJHvbuq1PV6lwDddoSdAIKkDscB0AF53sYlgJlugVbtU0gdbXjdyBZvUjWBgw","expires_in":3600,"token_type":"Bearer","scope":"api1"}
Now I would like to call the API and pass the token in a header, but I am unsure how to do this and I have had a couple of goes at online resources
One of my attempts were:
url = "https://anotherurl.com/api/SecuredApi/StaffDetails"
head = {'Authorization': 'token {}'.format(auth_response)}
response = requests.get(url, headers=head)
print(response)
but this gives me a 403 error
Please assist me with pointing out my error
EDIT:
Thanks to #RaniSharim I have made some changes. I now have
import requests
import json
auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"
data = {
"grant_type": grant_type,
"client_id": client_id,
"client_secret": client_secret,
"scope": scope
}
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
"EndDateTime" : "2021-10-11 23:59:00"
}
auth_response = requests.post(auth_url, data=data)
# print(auth_response.content)
authjson = auth_response.content
authdata = json.loads(authjson)
token = (authdata['access_token'])
# print(token)
head = {"Authorization": "Bearer " + token}
response = requests.get(url, headers=head, params=dateparams)
print(response.content)
This looks better but I am now getting a 400 error:
"message":"The date range you have specified is in an invalid format. The required format is yyyy-MM-dd HH:mm:ss","status":400}
As best I can see my date ranges are already in the requested format, as set here:
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
"EndDateTime" : "2021-10-11 23:59:00"
}
Normally, 400 means front-end error, but when you do GET request
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
}
r = requests.get(url, params=dateparams)
print(r.url)
GET url will turn into sth like this:
https://oauth.thegivenurl.com/connect/token?StartDateTime=2021-01-01+00%3A00%3A00
see the str
2021-01-01+00%3A00%3A00
So if back-end can't handle this right, you'll get this error too
but you can use GET in another way:
requests.get(url, json=dateparams)
This will send your json params perfectly
I am trying to retrieve the authentication token from the API using requests library from python. Here is the attempt I have made so far:
def get_token():
data = {
"auth" : {
"identity" : {
"methods" : [ "password" ],
"password": {
"user" : {
"name" : OS_USERNAME,
"domain": { "name": "Default" },
"password": OS_PASSWORD
}
}
}
}
}
r = requests.post(
OS_AUTH_URL+'/auth/tokens',
headers = HEADERS,
json = data, # https://stackoverflow.com/questions/9733638
verify = False
)
print(r.content)
j = json.loads(r.content)
return j['token']['user']['id']
I get token in the response :
{
"token": {
"issued_at": "2018-07-03T11:03:59.000000Z",
"audit_ids": [
"Fg1ywtZBQ1CkigCw70If9g"
],
"methods": [
"password"
],
"expires_at": "2018-07-03T12:03:59.000000Z",
"user": {
"password_expires_at": null,
"domain": {
"id": "default",
"name": "Default"
},
"id": "e0dc5beb383a46b98dad824c5d76e719",
"name": "admin"
}
}
}
However, when I am reusing this token to get, for instance, the list of projects :
def get_tenantID():
r = requests.get(
OS_AUTH_URL+'/auth/projects',
headers = HEADERS,
verify = False
)
return r
r = get_token()
HEADERS['X-Auth-Project-Id'] = 'admin'
HEADERS['X-Auth-Token'] = r
r = get_tenantID()
I get this error as if I would not be authenticated:
<Response [401]>
{"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
Googling around and using openstack token issue command showed me that usually, token are more like:
gAAAAABaCo1F1CIMVlsTBeuqYH8tm2qR29tbkmUL4vZuhCNPXJI39TQ2YzL6Twoj8fNcAyLe3WhCYW2O1YpbBF0G8mo4bt7Kf0IRsoDOoJ6uWa3RYyJ5SQNoB_5n8EnVXbKPxFYOZ_iFBnaVtL1_XDrGbwsrlDeyy8lZTDdLsqY52pUhFR-7Uow
which is not what I get with get_token.
What am I doing wrong?
Many thanks!
When you use the auth API directly, the token issued comes in the X-Subject-Token header.
Thus, to retrieve in your python example, you could access the response.headers dict like this:
token = r.headers['X-Subject-Token']
More info about authentication in the Keystone v3 docs
1. fetch authentication token as mentioned below:
r = requests.post(
OS_AUTH_URL+'/auth/tokens',
headers = HEADERS,
json = data,
verify = False
)
token = r.headers[X-Subject-Token]
2. Pass this token in header for further request:
{
'X-Auth-Token': token
}