Using below python code to get all test runs/test instances under a domain and project however it throws an 404 error, able to get the defects not the test runs
import json
import requests
from requests.auth import HTTPBasicAuth
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
almUserName = "007"
almPassword = "#123"
almDomain = "PRO"
almProject = "Mobile"
almURL = "https://alm.com/qcbin/"
qcDefectURL = almURL+"api/domains/"+almDomain+"/projects/"+almProject+"/defects"
qcTestRunURL=almURL+"api/domains/"+almDomain+"/projects/"+almProject+"/runs/?query={name[Run_8-5_00-9-31]}"
print(qcDefectURL)
print(qcTestRunURL)
session = requests.Session()
session.verify = False
auth = session.post(almURL + "authentication-point/authenticate?login-form-required=y",
auth=HTTPBasicAuth(almUserName, almPassword))
#print("Authentication ", auth, auth.text, session.cookies)
site_session = session.post(almURL + "rest/site-session")
#print("Session ", site_session, site_session.text, session.cookies)
check = session.get(almURL + "rest/is-authenticated")
print("Check ", check, check.text)
# Enforce JSON output
session.headers.update({ 'Accept': 'application/json' })
#projects = session.get(qcDefectURL)
TestRuns=session.get(qcTestRunURL)
print(TestRuns.status_code)
print(TestRuns.json())
Tried using various links mentioned in blogs and stackoverflow answers(here,here,here), but not able to resolve
Output: {'Id': 'qccore.general-error', 'Title': 'Not Found', 'ExceptionProperties': None, 'StackTrace': None}
Your query URL ends with
/runs/?query={name[Run_8-5_00-9-31]}
but should be like
/runs?query={name[Run_8-5_00-9-31]}
Further reading: https://admhelp.microfocus.com/alm/en/12.55/api_refs/REST_TECH_PREVIEW/ALM_REST_API_TP.html#REST_API_Tech_Preview/General/Filtering.html
Related
I am programming an API in python to query a server if it has endpoint agents in it. The server and the endpoint belong to Apex central SaaS trend micro.
The error I get is that I'm putting the wrong parameters but I don't think the problem is there.
The code I have for the query is as follows:
import base64
import jwt
import hashlib
import requests
import time
import json
import urllib.parse
def create_checksum(http_method, raw_url, headers, request_body):
string_to_hash = http_method.upper() + '|' + raw_url.lower() + '|' + headers + '|' + request_body
base64_string = base64.b64encode(hashlib.sha256(str.encode(string_to_hash)).digest()).decode('utf-8')
return base64_string
def create_jwt_token(appication_id, api_key, http_method, raw_url, headers, request_body,
iat=time.time(), algorithm='HS256', version='V1'):
payload = {'appid': appication_id,
'iat': iat,
'version': version,
'checksum': create_checksum(http_method, raw_url, headers, request_body)}
token = jwt.encode(payload, api_key, algorithm=algorithm)
return token
# Use this region to setup the call info of the Apex Central server (server url, application id, api key)
# server info
use_url_base = 'https://arct3w.manage.trendmicro.com'
use_application_id = '52EB0005-B6DA-4249-9764-62AE3BFCDBB1'
use_api_key = 'B3FE1D91-5D05-490C-B45C-26A9EFF6C363'
productAgentAPIPath = '/WebApp/API/AgentResource/ProductAgents'
canonicalRequestHeaders = ''
useQueryString=''
payload = {
'computerId':'e34a13a1-1d0f-47bc-96e0-ae4db4288940'
}
useRequestBody = json.dumps(payload)
jwt_token = create_jwt_token(use_application_id, use_api_key, 'POST',
productAgentAPIPath + useQueryString,
canonicalRequestHeaders, useRequestBody, iat=time.time())
headers = {'Authorization': 'Bearer ' + jwt_token , 'Content-Type': 'application/json;charset=utf-8'}
#Choose by call type.
r = requests.post(use_url_base + productAgentAPIPath + useQueryString, data=useRequestBody, headers=headers, verify=False)
print(r.status_code)
if 'application/json' in r.headers.get('Content-Type', '') and len(r.content):
print(json.dumps(r.json(), indent=4))
else:
print(r.text)
I tried to do something similar to an api belonging to Vision One but it didn't work:
https://automation.trendmicro.com/xdr/api-v2#tag/Search/paths/~1v2.0~1xdr~1eiqs~1query~1endpointInfo/post
the original code of the query is :
https://automation.trendmicro.com/apex-central/api#tag/Security-Agents/operation/AgentResource_GetProductAgentsV2
I am unable to access an API.
This is what I am doing:
import os, re
import requests
import logger
from requests_oauthlib import OAuth1
oauth_consumer_key = "123abc"
oauth_secret = "aaabbbccc"
url = "https://example_testing/v1/<ID_VALUE>/reports?"
oauth = OAuth1(oauth_consumer_key, oauth_secret)
output = requests.get(url,auth=oauth)
I keep getting a 500 error.
What am I doing wrong?
I didn't know this but apparently I needed to set values for headers and the payload. This solved my problem.
headers = {"Content-Type": "application/json"}
payload = json.dumps({
"report_format":"csv",
<other stuff>
}
output = requests.get(url=url, auth=oauth, headers=headers, data=payload)
Problem Solved
I wanted to trade on Wootrade with some bots but I have a hard time getting the authentification right..
Here is my code:
import time
import hmac
from urllib.parse import urlencode
import requests
import hashlib, json, pprint
YOUR_API_SECRET = "SECRET"
YOUR_API_KEY = "KEY"
api_endpoint = "https://api.staging.woo.network/v1/client/info"
ts = int(time.time() * 1000)
hashedsig = hashlib.sha256(YOUR_API_SECRET.encode('utf-8'))
params = urlencode({
"signature" : hashedsig,
"timestamp" : ts,
})
hashedsig = hmac.new(YOUR_API_SECRET.encode(), params.encode('utf-8'), hashlib.sha256).hexdigest()
userdata = requests.get(api_endpoint,
params = {
"x-api-signature": hashedsig,
"x-api-timestamp": ts,
"x-api-key": YOUR_API_KEY
},
headers = {
"x-api-signature": hashedsig,
"x-api-timestamp": str(ts),
"x-api-key": YOUR_API_KEY
}
)
print(userdata.json())
and that's the error message:
{'success': False, 'code': -1002, 'message': 'invalid api key.'}
But I am pretty sure, that my api-key is right, I tried a new one and that didnt work either.
I tried to follow the instructions on the website: https://kronosresearch.github.io/wootrade-documents/#example
But I am not that familiar with hashing my authentication, because the exchanges I used before had either some examples in python or a package to download, so I am not sure, what I did wrong.
I am thankful for any help I can get!
Cheers!
You should also send your params in requests, the following code is how I make it work to get account orders:
import requests
import datetime
import time
import hmac
import hashlib
from collections import OrderedDict
class Client():
def __init__(self, api_key=None, api_secret=None):
self.api_key = api_key
self.api_secret = api_secret
self.base_api = "https://api.woo.network/v1/"
def get_signature(self, params, timestamp):
query_string = '&'.join(["{}={}".format(k, v) for k, v in params.items()]) + f"|{timestamp}"
signature = hmac.new(
self.api_secret.encode('utf-8'),
query_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
return signature
def get_orders(self, symbol):
url = self.base_api + "orders/"
params = {
"symbol": symbol
}
params = OrderedDict(sorted(params.items()))
timestamp = str(int(time.time() * 1000))
signature = self.get_signature(params, timestamp)
headers = {
'Content-Type': "application/x-www-form-urlencoded",
'x-api-key': self.api_key,
'x-api-signature': signature,
'x-api-timestamp': timestamp,
'cache-control': 'no-cache'
}
resp = requests.get(url=url, params=params, headers=headers).json()
print(resp)
If you have any further questions, please join the WOOTRADE official telegram group and ask the admins~
(Please don't do any transfer if anyone ask you to do so in the group!)
Telegram: T.me/wootrade
Or you can try this python library for wootrade API
https://github.com/wanth1997/python-wootrade?fbclid=IwAR15onh2IX4KX85ahG-hJjXspFwhrTLHSNWGyW7n8c5kAw_8U4cQocbZEEc
Hi I am new to python and REST API,
I am getting 415 error while trying to run a query in cms using requests.post
I am not able to pass content-type and Accept along with the logon token.
I am able to run this in talend along with these 2 headers.
Can you please help me in how to add these 2 headers in requests.post at the end.
Below is my code
import requests
from lxml import etree
import xml.etree.ElementTree as ET
import pandas as pd
import openpyxl as x
from bs4 import BeautifulSoup
import xmltodict
protocol='http'
host='HOST'
port='6405'
content_type='application/xml'
base_url = protocol + '://' + host + ':' + port
bip_url = base_url + '/biprws'
webi_url = bip_url + '/raylight/v1'
sl_url = bip_url + '/sl/v1'
headers_auth = {
'Content-Type' : content_type,'Accept':'application/xml'
}
headers = {
}
username = 'user'
password = 'pass'
auth = requests.get(bip_url + '/logon/long', headers=headers)
root = etree.fromstring(auth.text)
root[3].text = username
root[0].text = password
etree.tostring(root)
send = requests.post(bip_url + '/logon/long',
headers=headers_auth,
data=etree.tostring(root))
tokenresp = etree.fromstring(send.content)
headers['X-SAP-LogonToken'] = tokenresp[3][0][0].text
folder_get = requests.get(bip_url + '/v1/cmsquery', headers=headers)
folder_root = etree.fromstring(folder_get.text)
Query_var = 'SELECT SI_ID,SI_NAME FROM CI_INFOOBJECTS WHERE SI_ANCESTOR = 12141'
folder_root[0].text = Query_var
data1 = etree.tostring(folder_root)
folder_post = requests.post(bip_url + '/v1/cmsquery', headers = headers, data = data1)
folder_post.status_code
I think 415 means that you're passing a content type that the API doesn't accept. You need to configure your headers correctly. Try this:
headers = {
'Content-Type' : 'application/xml'
}
auth = requests.get(bip_url + 'logon/long', headers=headers)
print(auth.status_code)
It looks like your problem is that you set headers to a blank dictionary.
I'm trying to learn how to use the YahooApi, but when getting the data from the website, it gives me an internal server error. I have tried every combination of league or leagues data or even general game data, but everything is giving me an internal server error. I have attached my code below and any help I could receive would be very helpful.
import json
import time
import webbrowser
import pandas as pd
from pandas.io.json import json_normalize
from rauth import OAuth1Service
from rauth.utils import parse_utf8_qsl
credentials_file = open('auth.json')
credentials = json.load(credentials_file)
credentials_file.close()
oauth = OAuth1Service(consumer_key = 'key',
consumer_secret = 'secret',
name = "yahoo",
request_token_url = "https://api.login.yahoo.com/oauth/v2/get_request_token",
access_token_url = "https://api.login.yahoo.com/oauth/v2/get_token",
authorize_url = "https://api.login.yahoo.com/oauth/v2/request_auth",
base_url = "http://fantasysports.yahooapis.com/")
request_token, request_token_secret = oauth.get_request_token(params={"oauth_callback": "oob"})
authorize_url = oauth.get_authorize_url(request_token)
webbrowser.open(authorize_url)
verify = input('Enter code: ')
raw_access = oauth.get_raw_access_token(request_token,
request_token_secret,
params={"oauth_verifier": verify})
parsed_access_token = parse_utf8_qsl(raw_access.content)
access_token = (parsed_access_token['oauth_token'],
parsed_access_token['oauth_token_secret'])
start_time = time.time()
end_time = start_time + 3600
credentials['access_token'] = parsed_access_token['oauth_token']
credentials['access_token_secret'] = parsed_access_token['oauth_token_secret']
tokens = (credentials['access_token'], credentials['access_token_secret'])
s = oauth.get_session(tokens)
r = s.get('https://fantasysports.yahooapis.com/fantasy/v2/leagues;league_keys=nba.l.60379', params={'format': 'json'})
print(r.status_code)
r.json()
And that prints {u'error': {u'description': u'Internal server error', u'lang': u'en-US'}}
seems like this issues stems from Yahoo's side. One user reported trying OAuth2 authentication which seemed to work fine.
https://forums.yahoo.net/t5/Help-with-Fantasy-Baseball/Receiving-500-quot-Internal-Server-Error-quot-from-Yahoo-Fantasy/td-p/341427/page/4