使用requests库进行API调用,并使用OAuth2身份验证
以下是示例代码:
import requests
from requests_oauthlib import OAuth2Session
# 填写OAuth2认证所需的参数
client_id = 'Your_client_id'
client_secret = 'Your_client_secret'
access_token_url = 'https://your_auth_server.com/token'
authorization_url = 'https://your_auth_server.com/auth'
# 创建OAuth2Session对象并进行授权
oauth = OAuth2Session(client_id, redirect_uri='https://your_redirect_uri.com')
authorization_url, state = oauth.authorization_url(authorization_url)
print('请在浏览器中打开下面的链接进行授权:')
print(authorization_url)
oauth.auth_code = input('请输入授权后重定向的地址: ').strip()
oauth.fetch_token(access_token_url, client_secret=client_secret)
# 创建API请求所需的参数
api_url = 'https://your_api_server.com/api'
api_params = {'param1': 'value1', 'param2': 'value2'}
# 通过OAuth2Session对象发送API请求
response = oauth.get(api_url, params=api_params)
# 处理API响应
if response.status_code == 200:
data = response.json()
print(data)
else:
print('请求API出错:{}'.format(response.reason))
下一篇:API请求缺失有效密钥。