[英]Testing TastyPie APIs using Django Test Client always results in empty HTTP 200 responses
[英]Using Python to test HTTP APIs
我對Python編程還很陌生,我不知道以下內容需要的所有庫。
我想使用Python測試一些HTTP API。 我主要想使用OAuth並進行一些JSON調用。 可以在以下網址找到有問題的API: https : //developers.trustpilot.com/authentication和“生成產品評論”鏈接(我只能使用一個鏈接)
我想對自己進行身份驗證,然后一步生成一個產品評論鏈接。 到目前為止,我一直在使用高級REST客戶端(ARC)單獨進行這些調用。 如果您認為更簡單,也可以使用.arc文件。
想法是一次性進行這些呼叫。 因此,可能會發生以下情況:
1)進行身份驗證呼叫。
HTTP方法如下所示: https : //api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken方法發布:
標頭授權:基本Base64encode(APIkey:Secret)內容類型:application / x-www-form-urlencoded
有效負載:grant_type=password&username=user@mail.com&password=SomePass
基本上將此位轉換為Python。
1.a)在通話中添加標題
標頭授權:base64encode哈希內容類型:application / x-www-form-urlencoded
1.b)將有效負載添加到呼叫中
有效負載:grant_type =密碼和用戶名
4)從步驟1)發出的呼叫中接收令牌(結果為格式)
“訪問令牌”:Auth_token
5)獲取令牌並將其用於創建產品評論。
5.a)在標題中添加令牌
標頭:授權:承載Auth_token
6.a)將JSON有效負載添加到步驟5中進行的調用。
這是我到目前為止的代碼:
Import requests
header = {'Authorization: Basic NnNrQUprTWRHTU5VSXJGYXBVRGxack1oT01oTUFRZHI6QTFvOGJjRUNDdUxBTmVqUQ==}','Content-Type: application/x-www-form-urlencoded'}
payload = {'grant_type=password&username=email@address.com&password=SomePassword'}
r = requests.post('https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken', headers=header, params=payload )
理想情況下,我想創建request.post(url,header,payload),然后以JSON格式返回服務器的響應。 我認為print r.text將完成最后一部分。
這是我編寫的代碼(現在可以使用):
import requests
import getpass
import json
from requests.auth import HTTPBasicAuth
header = {'grant_type':'password' , 'username':'mail@maildomain.com', 'password':'YourPassword'}
username= "YOURAPIKEY" #APIKey
password= "YOURSECRET" #Secret
res = requests.post(
'URL/v1/oauth/oauth-business-users-for-applications/accesstoken',
auth=HTTPBasicAuth(username, password), # basic authentication
data=header)
#print(res.content) #See content of the call result.
data = res.json() # get response as parsed json (will return a dict)
auth_token = data.get('access_token')
requests
可以完成您的所有要求,而無需您做任何工作。
有關身份驗證 , 參數 , json輸出 , json輸入 ,請參閱文檔
進行身份驗證呼叫。
import requests
import getpass
from requests.auth import HTTPBasicAuth
username = raw_input('Username: ')
password = getpass.getpass('Password: ')
res = requests.post(
'https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken',
auth=HTTPBasicAuth(username, password), # basic authentication
params={ # url parameters
'grant_type': 'password',
'username': 'email@address.com',
'password': 'SomePassword'
})
接收步驟1中發出的呼叫的令牌(結果為格式)
# res = requests.post.....
data = res.json() # get response as parsed json (will return a dict)
auth_token = data.get('access token')
獲取令牌並將其用於創建產品評論。
request.post(
'.../product_review',
headers={
'Authorization': 'Bearer ' + auth_token
},
json={'my': 'payload'}) # send data as json
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.