Making an API call in Python with an API that requ

2019-03-09 04:27发布

Looking for some help with integrating a JSON API call into a Python program.

I am looking to integrate the following API into a Python .py program to allow it to be called and the response to be printed.

The API guidance states that a bearer token must be generated to allow calls to the API, which I have done successfully. However I am unsure of the syntax to include this token as bearer token authentication in Python API request.

I can successfully complete the above request using cURL with a token included. I have tried "urllib" and "requests" routes but to no avail.

Full API details: IBM X-Force Exchange API Documentation - IP Reputation

2条回答
Bombasti
2楼-- · 2019-03-09 05:15

It just means it expects that as a key in your header data

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

print(requests.post(endpoint, data=data, headers=headers).json())
查看更多
贪生不怕死
3楼-- · 2019-03-09 05:22

The token has to be placed in an Authorization header according to the following format:

Authorization: Bearer [Token_Value]

Code below:

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
查看更多
登录 后发表回答