import requests
import json
import jwt
import datetime
APİ_KEY = "100 percent correct api key"
APİ_SECRET = "100 percent correct api secret"
payload = {
'iss':APİ_KEY,
'exp':datetime.datetime.now() + datetime.timedelta(hours=2)
}
token = jwt.encode(payload, APİ_SECRET)
print(token)
endpoint = "https://api.zoom.us/v2/users/my_e-mail_is_written_here/meetings"
myData = {
"headers": {
"authorization":"Bearer "+token,
"content-type":"application/json"
},
"body": {
"topic":"denemex",
"type":2,
"start_time":"2021-05-05T13:20",
"duration":"40",
"password":"1234"
}
}
zoom_r = requests.post(endpoint, data=json.dumps(myData))
print(zoom_r.status_code)
print(zoom_r.text)
I wanted to do a simple experiment with python like this, but I get an "invalid acces token" error, what could be the reason?
I thought a little more about my problem and solved the problem by changing the code as follows:
import requests
import json
import jwt
import datetime
APİ_KEY = "my api key"
APİ_SECRET = "my api secret"
payload = {
'iss':APİ_KEY,
'exp':datetime.datetime.now() + datetime.timedelta(hours=2)
}
token = jwt.encode(payload, APİ_SECRET)
endpoint = "https://api.zoom.us/v2/users/my_e-mail_is_written_here/meetings"
myData = {
"topic":"denemex",
"type":2,
"start_time":"2021-05-05T13:20",
"duration":"40",
"password":"1234"
}
headers = {"Content-Type":"application/json", "Authorization":"Bearer "+ token}
zoom_r = requests.post(endpoint, headers=headers, data=json.dumps(myData))
print(zoom_r.status_code)
print(zoom_r.text)
Related
I have this code below with my credentials;
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.campaign import Campaign
my_app_id = ''
my_app_secret = ''
my_access_token = ''
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
my_account = AdAccount('')
my_campaign = Campaign('')
When I run the code below, I get an error.
Input:
my_account_insights = my_account.get_insights()
print(my_account_insights)
Output:
FacebookRequestError:
Message: Call was not successful
Method: GET
Path: https://graph.facebook.com/v12.0/act_2193000197632450/adsets
Params: {'summary': 'true'}
Status: 400
Response:
{
"error": {
"message": "(#100) Missing permissions",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "AvMDtZu8KYqYG8qt3repNjL"
}
}
What am I missing? Could you please help me to figure it out?
Generate a new token https://developers.facebook.com/tools/explorer/ and set the permission accordingly
I am trying to print the values from an API Request. The JSON file returned is large(4,000 lines) so I am just trying to get specific values from the key value pair and automate a message.
Here is what I have so far:
import requests
import json
import urllib
url = "https://api.github.com/repos/<companyName>/<repoName>/issues" #url
payload = {}
headers = {
'Authorization': 'Bearer <masterToken>' #authorization works fine
}
name = (user.login) #pretty sure nothing is being looked out
url = (url)
print(hello %name, you have a pull request to view. See here %url for more information) # i want to print those keys here
The JSON file (exported from the API get request is as followed:
[
{
**"url": "https://github.com/<ompanyName>/<repo>/issues/1000",**
"repository_url": "https://github.com/<ompanyName>/<repo>",
"labels_url": "https://github.com/<ompanyName>/<repo>/issues/1000labels{/name}",
"comments_url": "https://github.com/<ompanyName>/<repo>/issues/1000",
"events_url": "https://github.com/<ompanyName>/<repo>/issues/1000",
"html_url": "https://github.com/<ompanyName>/<repo>/issues/1000",
"id": <id>,
"node_id": "<nodeID>",
"number": 702,
"title": "<titleName>",
"user": {
**"login": "<userName>",**
"id": <idNumber>,
"node_id": "nodeID",
"avatar_url": "https://avatars3.githubusercontent.com/u/urlName?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/<userName>",
"html_url": "https://github.com/<userName>",
"followers_url": "https://api.github.com/users/<userName>/followers",
"following_url": "https://api.github.com/users/<userName>/following{/other_user}",
"gists_url": "https://api.github.com/users/<userName>/gists{/gist_id}",
"starred_url": "https://api.github.com/users/<userName>/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/<userName>/subscriptions",
"organizations_url": "https://api.github.com/users/<userName>/orgs",
"repos_url": "https://api.github.com/users/<userName>/repos",
"events_url": "https://api.github.com/users/<userName>/events{/privacy}",
"received_events_url": "https://api.github.com/users/<userName>/received_events",
"type": "User",
"site_admin": false
},
]
(note this JSON file repeats a few hundred times)
From the API request, I am trying to get the nested "login" and the url.
What am I missing?
Thanks
Edit:
Solved:
import requests
import json
import urllib
url = "https://api.github.com/repos/<companyName>/<repoName>/issues"
payload = {}
headers = {
'Authorization': 'Bearer <masterToken>'
}
response = requests.get(url).json()
for obj in response:
name = obj['user']['login']
url = obj['url']
print('Hello {0}, you have an outstanding ticket to review. For more information see here:{1}.'.format(name,url))
Since it's a JSON array you have to loop over it. And JSON objects are converted to dictionaries, so you use ['key'] to access the elements.
for obj in response:
name = obj['user']['login']
url = obj['url']
print(f'hello {name}, you have a pull request to view. See here {url} for more information')
you can parse it into a python lists/dictionaries and then access it like any other python object.
response = requests.get(...).json()
login = response[0]['user']
You can convert JSON formatted data to a Python dictionary like this:
https://www.w3schools.com/python/python_json.asp
json_data = ... # response from API
dict_data = json.loads(json_data)
login = response[0]['user']['login']
url = response[0]['url']
I am trying to get access to the Kerio Connect (mailserver) api which uses jsonrpc as a standard for their api.
There is Session.login method that works just fine, I get back a SESSION_CONNECT_WEBADMIN cookie that gets saved in the session:
SESSION_CONNECT_WEBADMIN=2332a56d0203f27972ebbe74c09a7f41262e5b224bc6a05e53e62e5872e9b698; \
path=/admin/; domain=<server>; Secure; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;
But when I then do my next request with the same session, I get back a message that tells me, that my session has expired:
{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32001,
"message": "Session expired.",
"data": {
"messageParameters": {
"positionalParameters": [],
"plurality": 1
}
}
}
}
So here's the Python script leading to that message
import json
import requests
userName = "username"
password = "password"
n=1
application = {}
application["name"] = "Log in"
application["vendor"] = "My Company"
application["version"] = "1.0"
params = {}
params["userName"] = userName
params["password"] = password
params["application"] = application
payload = {}
payload["jsonrpc"] = "2.0"
payload["id"] = n
n += 1
payload["method"] = "Session.login"
payload["params"] = params
headers = {}
headers["Content-Type"] = "application/json-rpc"
json_payload =json.dumps(payload, sort_keys=True, indent=2)
url = "https://<server>:4040/admin/api/jsonrpc/"
session = requests.Session()
response = session.post(url, headers=headers, data=json_payload, verify=False)
# Results in a token / a cookie with that token
payload2 = {}
payload2["jsonrpc"] = "2.0"
payload2["id"] = n
n += 1
payload2["method"] = "Users.get"
json_payload2 = json.dumps(payload2, sort_keys=True, indent=2)
response2 = session.post(url, data=json_payload2, verify=False)
print(response2.text)
What am I missing here because of my lack of experience?
[EDIT]:
I just now realise that when I log in with a browser, two cookies are actually created, each with another token, whereas I get only one cookie back when I try to access the api with Python. Why is that?
Cookies received with Chrome:
TOKEN_CONNECT_WEBADMIN
SESSION_CONNECT_WEBADMIN
Cookie received with Python:
SESSION_CONNECT_WEBADMIN
Working example:
import json
import urllib.request
import http.cookiejar
import ssl
jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
urllib.request.install_opener(opener)
server = "https://mail.smkh.ru:4040"
username = "admin"
password = "pass"
ssl._create_default_https_context = ssl._create_unverified_context # disable ssl cert error
def callMethod(method, params, token=None):
"""
Remotely calls given method with given params.
:param: method string with fully qualified method name
:param: params dict with parameters of remotely called method
:param: token CSRF token is always required except login method. Use method "Session.login" to obtain this token.
"""
data = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
req = urllib.request.Request(url=server + '/admin/api/jsonrpc/')
req.add_header('Content-Type', 'application/json')
if token is not None:
req.add_header('X-Token', token)
httpResponse = opener.open(req, json.dumps(data).encode())
if httpResponse.status == 200:
body = httpResponse.read().decode()
return json.loads(body)
session = callMethod("Session.login", {"userName": username, "password": password, "application": {"vendor":"Kerio", "name":"Control Api Demo", "version":"8.4.0"}})
token = session["result"]["token"]
sessions = callMethod("Users.get",
{"query": {
"fields": [
"id",
"loginName",
"fullName",
"description",
"authType",
"itemSource",
"isEnabled",
"isPasswordReversible",
"emailAddresses",
"emailForwarding",
"userGroups",
"role",
"itemLimit",
"diskSizeLimit",
"consumedItems",
"consumedSize",
"hasDomainRestriction",
"outMessageLimit",
"effectiveRole",
"homeServer",
"migration",
"lastLoginInfo",
"accessPolicy"
],
"start": 0,
"limit": 200,
"orderBy": [
{
"columnName": "loginName",
"direction": "Asc"
}
]
},
"domainId": Example:"keriodb://domain/908c1118-94ef-49c0-a229-ca672b81d965"
},
token)
try:
user_names = []
for user in users["result"]["list"]:
print(user["fullName"], " (", user["loginName"], ")", sep="")
user_names.append(user["fullName"])
call_method("Session.logout", {}, token)
return users
except KeyError:
print('Error: {}'.format(users['error']['message']))
call_method("Session.logout", {}, token)
return None
I'm trying to get this Etrade stuff up an running.... so far i have:
from rauth import OAuth1Service
import webbrowser
def getSession():
# Create a session
# Use actual consumer secret and key in place of 'foo' and 'bar'
service = OAuth1Service(
name = 'etrade',
consumer_key = 'cabf024eaXXXXXXXXX7a0243d8d',
consumer_secret = '3d05c41XXXXXXXXX1949d07c',
request_token_url =
'https://etws.etrade.com/oauth/request_token',
access_token_url =
'https://etws.etrade.com/oauth/access_token',
authorize_url = 'https://us.etrade.com/e/t/etws/authorize?
key={}&token={}',
base_url = 'https://etws.etrade.com')
# Get request token and secret
oauth_token, oauth_token_secret = service.get_request_token(params =
{'oauth_callback': 'oob',
'format': 'json'})
auth_url = service.authorize_url.format('cabf0XXXXXXXXXa0243d8d',
oauth_token)
webbrowser.open(auth_url)
verifier = raw_input('Please input the verifier: ')
return service.get_auth_session(oauth_token, oauth_token_secret,
params = {'oauth_verifier': verifier})
session = getSession()
This authentication process works perfectly fine and allows me to do get/delete requests but when I attempt to make post requests:
url =
'https://etwssandbox.etrade.com/order/sandbox/rest/previewoptionorder'
para = {
"PreviewOptionOrder": {
"-xmlns": "http://order.etws.etrade.com",
"OptionOrderRequest": {
"accountId": "83550325",
"quantity": "4",
"symbolInfo": {
"symbol": "AAPL",
"callOrPut": "CALL",
"strikePrice": "585",
"expirationYear": "2012",
"expirationMonth": "07",
"expirationDay": "21"
},
"orderAction": "BUY_OPEN",
"priceType": "MARKET",
"orderTerm": "GOOD_FOR_DAY"
}
}
}
resp = session.post(url,data=para)
resp.text
I get an error:
Unauthorized request: consumer key is missing.
I've tried numerous things (granted I am new to this stuff). I tried authenticating using just requests to no avail and I tried passing the oauth1 object to the posts function as a kw argument. Any ideas?
I am trying to do a simple get of stats of ad campaigns. I thre this together from the documentation:
from facebookads.objects import AdUser
from facebookads.api import FacebookAdsApi
from facebookads.objects import AdAccount
my_app_id = 'xxx'
my_app_secret = 'xxx'
my_access_token = 'xxx'
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
me = AdUser(fbid='xxx')
account = AdAccount('xxx')
params = {
'start_date': '2014-09-01',
}
fields = {
'impressions',
'clicks',
'spent',
}
stats = account.get_ad_campaign_stats(fields=fields, params=params)
for stat in stats:
print stat
I am getting back a code:1 type: GraphMethodException back from the API.
The response loos like this:
Message: Call was not successful
Method: GET
Path: https://graph.facebook.com/v2.3/xxx/adcampaignstats
Params: {'fields': 'impressions,spent,clicks', 'start_date': '2014-09-01', 'summary': 'true'}
Status: 400
Response:
{
"error": {
"message": "Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
"code": 100,
"type": "GraphMethodException"
}
}
What am I doing wrong? Any help would be great. Thanks!