Rest API data reading present in swagger url using python library - python-3.x

I am trying to access swagger url that gives response upon sending request in json format. I have disabled to avoid SSLCertVerificationError using verify=False. How to access that please help me to read it using python code. You can get details what I have tried till now.
Installed requests library by using cmd in windows = pip install requests
I am able to get the 200 response by using code mentioned
When I am trying to use "params= payload" where. I am not able to get the response the same I am getting in the swagger url.
url : https:///#!/prepaid-estimate-controller/getAccountDetailsUsingPOST
payload={'searchCriteria': 'string', 'value': 'string'}
r4 = requests.get('https://<domain>/#!/prepaid-estimate-controller/getAccountDetailsUsingPOST', verify=False)
print(r4)
Output : 200
payload={'searchCriteria': 'string', 'value': 'string'}
r4 = requests.get('https://<domain>/#!/prepaid-estimate-controller/getAccountDetailsUsingPOST',params=payload, verify=False)
print(r4)
print(r4.text)
Output: DOM structure returns

This issue has been fixed by using below code generated in the postman.
import requests
url = "https:///bsi/prepaid/getAccountDetails"
payload = "{ \r\n "searchCriteria": "BAID", \r\n "value": "PPB006788"\r\n}"
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload, verify=False)
print(response.text.encode('utf8'))

Related

HP ALM API : Attaching file to run step through ALM REST API not working

We have fetched Run Steps details using ALM REST API.
(for reference ALM API Documentation
Same question is being asked in ALM community, Community Microfocus ALM
https://some.almserver.com/qcbin/rest/domains/DOMAIN/projects/PROJECT/runs/<run-id>/run-steps
and passed Run Step id to below API and tried to attach file using POST and PUT.
https://some.almserver.com/qcbin/rest/domains/DOMAIN/projects/PROJECT/runs/<run-id>/run-steps/<run-step-ID>/attachments
we are getting 404 response.
Bad request.
URL = "https://some.almserver.com/qcbin/rest/domains/DOMAIN/projects/PROJECT/runs/<run-id>/run-steps/<step-id>/attachments"
METHOD = "PUT"
HEADERS = {
'cache-control': "no-cache",
"Slug": "some.html",
'Content-Type': "application/octet-stream"
}
def attach_to_run_step():
f = open("/path/to/some.html", "rb")
response = requests.put(URL, headers=HEADERS, cookies=cookies, data=f.read())
print(response.content)
Expected : 200 response
Actual : 404 status code
I think you need to use the following URL for your POST request:
https://some.almserver.com/qcbin/rest/domains/DOMAIN/projects/PROJECT/run-steps/<run-step-id>/attachments (remove /runs/<run-id>)
Update:
Here is an example, generated from Postman:
import requests
url = "http://xxx.xxx.xxx.xxx:8080/qcbin/rest/domains/DEFAULT/projects/demo/run-steps/1263/attachments"
payload="<file contents here>"
headers = {
'Content-Type': 'application/octet-stream',
'Slug': '1.jpg',
'Cookie': 'JSESSIONID=<session>; ALM_USER=2e69...; LWSSO_COOKIE_KEY=PTKYM...; QCSession=MTQwM...; XSRF-TOKEN=3dfa4...'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
P.S. We are developing commercial platform for integrating various test frameworks with ALM, which is called Agiletestware Bumblebee, so you might want to have a look at it.

Python3 Request from API return Not Found

I am trying to get a balance from some address at a explorer on Python but I get 404 error and I believe that is related to a list.
This is my code:
import urllib.request, json, requests
listAddress = [
"HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf"
]
explorerUrl = 'http://explorer.htmlcoin.com'
urlBase = '/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/'
balance = '/balance'
for address in listAddress:
urlGamb = explorerUrl+urlBase+address+balance
json_data = urlGamb
r = requests.post(json_data)
r.status_code
r.json()
print(r.json())
The problem is that returns this error:
python3 newwork.py
{'status': 404, 'url': '/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf/balance', 'error': 'Not found'}
So, what am I doing wrong here?
Minor suggestion:
urlGamb = f"{explorerUrl}{urlBase}{address}{balance}"
I don't know about the API, you did not provide a link, but the value of urlGamb is 'http://explorer.htmlcoin.com/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf/balance' and that is not JSON. The assignment to json_data seems like a conceptual error because the URL string is not json. If the post requires a JSON payload then the docs should tell you how to construct it.
Should the post have been a get request instead? That would make sense because according to REST standards, post is for changing state on the server, and you are only making a query.

Django DRF Post with files and data works in Postman, not Python. No TemporaryUploadedFile

Running a Django App locally, i can use Postman to upload a zip file along with some dict data. Breaking the application in 'def Post()' i can see that Postman's successful upload:
request.data = <QueryDict: {'request_id': ['44'], 'status': [' Ready For Review'], 'is_analyzed': ['True'], 'project': ['test value'], 'plate': ['Plate_R0'], 'antigen': ['tuna'], 'experiment_type': ['test'], 'raw_file': [<TemporaryUploadedFile: testfile.zip (application/zip)>]}>
Postman offers the following python code to replicate these results in my python script:
import requests
url = "http://127.0.0.1:8000/api/upload/"
payload = {'request_id': '44',
'status': ' Ready For Review',
'is_analyzed': 'True',
'project': 'test value',
'plate': 'Plate_R0',
'antigen': 'tuna',
'experiment_type': 'test'}
files = [
('raw_file', open(r'C:/testfile.zip','rb'))
]
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data = payload, files = files)
print(response.text.encode('utf8'))
running this code directly and retrieving the request.data (server side) i see the binary representation of the xlsx file is in the object and the payload data is not there (this is the error in the response).
How do i get my python script to produce the same server-side object as postman? Specifically how do i upload my data such that the file is represented as: <TemporaryUploadedFile: testfile.zip (application/zip)>
Thanks.
Turns out, inspection of the object posted by Postman shows that it was using multipart-form upload. Searching around i found this answer to a related question to describe posting as multi-part: https://stackoverflow.com/a/50595768/2917170 .
The working python is as follows:
from requests_toolbelt import MultipartEncoder
url = "http://127.0.0.1:8000/api/upload/"
zip_file = r'C:/testfile.zip'
m = MultipartEncoder([('raw_file', (os.path.basename(zip_file), open(zip_file, 'rb'))),
('request_id', '44'),
('status', 'Ready For Review'),
('is_analyzed', 'True'),
('project', 'test value'),
('plate', 'Plate_R0'),
('antigen', 'tuna'),
('experiment_type', 'test')])
header = {'content-type': m.content_type}
response = requests.post(url, headers=header, data=m, verify=True)

Error calling CF API login one time passcode

I am working with the CF API RESTful services. Trying to get an access token from cloud foundry's UAA API using https://login..../oauth/token web method.
I have verified that headers & body content is correct, but calling the api always returns a 400 error code with message missing grant type.
I have implemented this call in Objective-C, Swift & now Python. All tests return the same result. Here is my code example in Python:
import json
import requests
import urllib
params = {"grant_type": "password",
"passcode": "xxx"
}
url = "https://login.system.aws-usw02-pr.ice.predix.io/oauth/token"
headers = {"Authorization": "Basic Y2Y6", "Content-Type": "application/json", "Accept": "application/x-www-form-urlencoded"}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(rjson)
Each time I run this, I get the response
error invalid request, Missing grant type
Any help would be greatly appreciated.
Your code mostly worked for me, although I used a different UAA server.
I had to make only one change. You had the Accept and Content-Type headers flipped around. Accept should be application/json because that's the format you want back, and Content-Type should be application/x-www-form-urlencoded because that's the format you are sending.
See the API Docs for reference.
import json
import requests
import urllib
import getpass
UAA_SERVER = "https://login.run.pivotal.io"
print("go to {}/passcode".format(UAA_SERVER))
params = {
"grant_type": "password",
"passcode": getpass.getpass(),
}
url = "https://login.run.pivotal.io/oauth/token"
headers = {
"Authorization": "Basic Y2Y6",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(json.dumps(rjson, indent=4, sort_keys=True))
I made a couple other minor changes, but they should affect the functionality.
Use getpass.getpass() to load the passcode.
Set the target server as a variable.
Pretty print the JSON response.
The only other thing to note, is that the OAuth2 client you use must be allowed to use the password grant type. It looks like you're using the same client that the cf cli uses, so if your UAA server is part of a standard Cloud Foundry install that is likely to be true, but if it still doesn't work for you then you may need to talk with an administrator and make sure the client is set up to allow this.

Request too large error making a request to App Engine

I have an app on App Engine Flex using the Python 3 runtime. I get the base64 encoded byte string of a resume file from Google Storage with the code below.
storage_client = storage.Client(project=[MYPROJECT])
bucket = storage_client.get_bucket([MYBUCKET])
blob = bucket.blob([MYKEY])
resume_file = blob.download_as_string()
resume_file = str(base64.b64encode(resume_file))[2:-1]
I send that as part of my request parameters like so:
headers = {'Authorization': 'Bearer {}'.format(signed_jwt),
'content-type': 'application/json'}
params = {'inputtype': 'file',
'resume': resume_file}
response = requests.get(HOST, headers=headers, params=params)
However, I get the following error:
Error 413 (Request Entity Too Large)
Your client issued a request that was too large
That's all we know
App Engine has a file size limit of 32MB. However, my file is only 24KB. How can I fix this error?
I had to change my application to accept POST requests instead of GET requests.
Previously, I was sending the resume as a parameter. I'm now sending it as data:
payload = json.dumps({
'inputtype': inputtype,
'resume': inputresume
})
response = requests.post(HOST, headers=headers, data=payload)
I am using Flask. Previously I was reading in the params using:
request.args.get('resume')
I changed it to:
request.get_json().get('resume')
This is an extension of the question/answer here

Resources