programing

베어러 토큰이 필요한 API를 사용하여 Python에서 API 호출하기

telebox 2023. 7. 11. 22:51
반응형

베어러 토큰이 필요한 API를 사용하여 Python에서 API 호출하기

JSON API 호출을 Python 프로그램에 통합하는 데 도움이 필요합니다.

다음 API를 Python.py 프로그램에 통합하여 호출하고 응답을 인쇄할 수 있도록 하려고 합니다.

API 안내서에는 API에 대한 호출을 허용하려면 베어러 토큰이 생성되어야 한다고 나와 있는데, 이는 성공적으로 수행한 것입니다.그러나 Python API 요청에 이 토큰을 베어러 토큰 인증으로 포함하는 구문을 잘 모르겠습니다.

토큰이 포함된 cURL을 사용하여 위 요청을 성공적으로 완료할 수 있습니다."urllib"과 "requests" 경로를 시도해봤지만 소용이 없었습니다.

전체 API 세부 정보: IBM X-Force Exchange API 설명서 - IP 평판

그것은 단지 당신의 헤더 데이터의 핵심으로서 그것을 기대한다는 것을 의미합니다.

import requests
endpoint = ".../api/ip"
data = {"ip": "1.1.2.3"}
headers = {"Authorization": "Bearer MYREALLYLONGTOKENIGOT"}

print(requests.post(endpoint, data=data, headers=headers).json())

사용 중인 경우requests모듈은 "새로운 인증 양식"에서 설명한 바와 같이 인증 클래스를 작성하는 것이 대안입니다.

import requests

class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

그리고 나서 당신은 다음과 같은 요청을 보낼 수 있습니까?

response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))

당신이 같은 것을 사용할 수 있게 해줍니다.auth기본적인 인증과 같은 인수이며 특정 상황에서 도움이 될 수 있습니다.

토큰은 다음 형식에 따라 Authorization 헤더에 배치되어야 합니다.

권한 부여:베어러 [토큰_값]

아래 코드:

import urllib2
import json

def get_auth_token():
    """
    get an auth token
    """
    req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    token_string=json_obj["token"].encode("ascii","ignore")
    return token_string

def get_response_json_object(url, auth_token):
    """
    returns json object with info
    """
    auth_token=get_auth_token()
    req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    return json_obj

다음은 cURL 및 Python에서 구현한 완전한 예입니다 - 권한 부여 및 API 호출을 위한 것입니다.

cURL

권한 부여

다음과 같은 액세스 데이터를 수신했습니다.

Username: johndoe

Password: zznAQOoWyj8uuAgq

Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa

Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga

다음과 같이 cURL에서 호출할 수 있습니다.

curl -k -d "grant_type=password&username=Username&password=Password" \

                    -H "Authorization: Basic Base64(consumer-key:consumer-secret)" \

                       https://somedomain.test.com/token

또는 이 경우에는 다음과 같습니다.

curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \

                    -H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \

                      https://somedomain.test.com/token

답은 다음과 같습니다.

{
    "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
    "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
    "scope": "default",
    "token_type": "Bearer",
    "expires_in": 3600
}

호출 API

위에서 인증을 사용하는 일부 API를 호출하는 방법은 다음과 같습니다. Limit그리고.offsetAPI가 구현할 수 있는 두 가지 매개 변수의 예입니다.필요합니다access_token뒤에 삽입된 위에서부터."Bearer "위의 인증 데이터를 사용하여 일부 API를 호출하는 방법은 다음과 같습니다.

curl -k -X GET "https://somedomain.test.com/api/Users/Year/2020/Workers?offset=1&limit=100" -H "accept: application/json" -H "Authorization: Bearer zz8d62zz-56zz-34zz-9zzf-azze1b8057f8"

파이썬

위의 것과 동일한 것이 파이썬에서 구현되었습니다.코드를 복사해서 붙여넣을 수 있도록 댓글에 텍스트를 넣었습니다.

# Authorization data

import base64
import requests

username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'
consumer_key = 'ggczWttBWlTjXCEtk3Yie_WJGEIa'
consumer_secret = 'uuzPjjJykiuuLfHkfgSdXLV98Ciga'
consumer_key_secret = consumer_key+":"+consumer_secret
consumer_key_secret_enc = base64.b64encode(consumer_key_secret.encode()).decode()

# Your decoded key will be something like:
#zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh


headersAuth = {
    'Authorization': 'Basic '+ str(consumer_key_secret_enc),
}

data = {
  'grant_type': 'password',
  'username': username,
  'password': password
}

## Authentication request

response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()

# When you print that response you will get dictionary like this:

    {
        "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
        "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
        "scope": "default",
        "token_type": "Bearer",
        "expires_in": 3600
    }

# You have to use `access_token` in API calls explained bellow.
# You can get `access_token` with j['access_token'].


# Using authentication to make API calls   

## Define header for making API calls that will hold authentication data

headersAPI = {
    'accept': 'application/json',
    'Authorization': 'Bearer '+j['access_token'],
}

### Usage of parameters defined in your API
params = (
    ('offset', '0'),
    ('limit', '20'),
)

# Making sample API call with authentication and API parameters data

response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, params=params, verify=True)
api_response = response.json()
import json
import os
import requests

def lambda_handler(event, context):
    print(event)
    item = list(map(lambda x: x['detail']['item'], event['inputData']))
    print("item List :", item)
    consumer_key = os.getenv('consumer_key')
    consumer_secret = os.getenv('consumer_secret')
    entitlement_url=os.getenv('entitlement_url')
    storage_url=os.getenv('storage_url')
    access_token = get_jwt_token(consumer_key,consumer_secret,entitlement_url)
    print("Response from entitlement: ", access_token)
    for listID in list:
        print("listID: ", listID)
        response = get_storage_service(access_token,storage_url,listID)
        print("Response from storage: ", response.text)

    return "Success"

def get_jwt_token(consumer_key, consumer_secret, url):
    data = 'grant_type=client_credentials&client_id=' + consumer_key + '&client_secret=' + consumer_secret
    header = {"Content-type": "application/x-www-form-urlencoded"}
    try:
        response = requests.post(url, data=data, headers=header)
        access_token = json.loads(response.text)
        final_response=access_token['access_token']

    except requests.exceptions as err:
        print(err)
        final_response = 'error'
    return final_response


def get_storage_service(jwt_token, url, list_id):
    final_url = url + list_id + "/data"
    print("Final url is :", final_url)
    headers_api = {
        'Authorization': 'Bearer ' + jwt_token

    }
    try:
        response = requests.get(url=final_url, headers=headers_api)
    except requests.exceptions as err:
        print(err)
        response = 'error'
    return response

환경 변수 사용

언급URL : https://stackoverflow.com/questions/29931671/making-an-api-call-in-python-with-an-api-that-requires-a-bearer-token

반응형