简体   繁体   中英

Python call rest api to get data from url

I've created a Bash script to get the data from the url using rest API from a appliance using username , password and saving the Session ID into a Variable and then using the session ID to get the data into csv format which is working fine.

I want to change the bash code into python3 code as i'm parsing it using pandas.

Bash Code:

#!/bin/bash

sessionID=$(curl -k -H "accept: application/json" -H "content-type: application/json" -H "x-api-version: 120" -d '{"userName":"administrator","password":"adminpass"}' -X POST https://hpe.sysnergy.com/rest/login-sessions | jq -r ".sessionID")


curl -k -H 'accept: application/json' \
        -H 'content-type: text/csv' \
        -H 'x-api-version: 2' \
        -H "auth: $sessionID" \
        -X GET https://hpe.sysnergy.com/rest/resource-alerts

Python Version of tries code:

#!/usr/bin/python3
import requests
import json

url = "https://hpe.sysnergy.com/rest/login-sessions"
data = {'username': 'administrator', 'password': 'adminpass'}
headers = {'Content-type': 'text/csv', 'Accept': 'application/json', 'x-api-version': 2}
r = requests.post(url, data=json.dumps(data), headers=headers)
print(r)

I am getting below error:

Error:

requests.exceptions.InvalidHeader: Value for header {x-api-version: 2} must be of type str or bytes, not <class 'int'>

if i convert int to str as '2' then it gives another ssl error:

requests.exceptions.SSLError: HTTPSConnectionPool(host='hpe.synerg.com', port=443): Max retries exceeded with url: /rest/login-sessions (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:877)'),))

EDIT:

I have tried little different approach to get the same code format as bash in python but now it returns new error with new response code.

import os
import requests

sessionID = os.getenv('sessionID')

headers = {
    'accept': 'application/json',
    'content-type': 'text/csv',
    'x-api-version': '2',
    'auth': f"{sessionID}",
}

data = '{"userName":"administrator","password":"adminpassword"}'

response = requests.post('https://hpe.synergy.com/rest/login-sessions', headers=headers, data=data, verify=False)
print(response)

Error:

/python3/lib64/python3.6/site-packages/urllib3/connectionpool.py:1020: InsecureRequestWarning: Unverified HTTPS request is being made to host 'hpe.synergy.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning,

<Response [415]>

Please help or suggest the way to achieve same function in the python.

You first need to make a POST request to get the sessionID , then you need to make a GET request. Also note the headers are slightly different for the 2 requests. Something like this should work:

import requests

session = requests.Session()

url = "https://hpe.sysnergy.com/rest/login-sessions"
credentials = {"userName": "administrator", "password": "adminpass"}
headers = {"accept": "application/json", 
           "content-type": "application/json", 
           "x-api-version": "120", 
          }

response = session.post(url, headers=headers, json=credentials, verify=False)

session_id = response.json()["sessionID"]

url = "https://hpe.sysnergy.com/rest/resource-alerts"
headers = {"accept": "application/json", 
           "content-type": "text/csv", 
           "x-api-version": "2", 
           "auth": session_id, 
          }

response = session.get(url, headers=headers, verify=False)

print(response)
#print(response.content) # returns bytes
#print(response.text) # returns string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM