2014-09-21 44 views
3

我正試圖使用​​shorte.st api自動創建我的短鏈接使用我的Python程序,但我真的不知道如何使用Apis! 在專門的頁面,只有這個代碼在這裏:Shorte.st Api python

curl H "public-api-token: ---" -X -d "urlToShorten=google.com" PUT http://api.shorte.st/v1/data/url {"status":"ok","shortenedUrl":"http:\/\/sh.st\/XXXX"} 

在公共API令牌,我必須明明插入我的私人原因,但由於捲曲是C(我認爲)我如何使用它們用python? 非常感謝

+0

您可以嘗試使用'subprocess'模塊執行這個curl命令。 – g4ur4v 2014-09-21 11:11:39

回答

4

我更喜歡使用python lib調用請求()來處理http請求。所有你需要做的就是發送一個你想縮短爲數據字典的網址,以及在「public-api-token」鍵標題下的公共API標記。您可以在https://shorte.st/tools/api頁面上找到您的api標記。響應內容以json編碼的字符串形式出現,因此您需要解碼才能獲得dict對象。

import requests 
response = requests.put("https://api.shorte.st/v1/data/url", {"urlToShorten":"google.com"}, headers={"public-api-token": "your_api_token"}) 
print response.content 
>>> {"status":"ok","shortenedUrl":"http:\\/\\/sh.st\\/ryHyU"} 
import json 
decoded_response = json.loads(response.content) 
print decoded_response 
>>>{u'status': u'ok', u'shortenedUrl': u'http://sh.st/ryHyU'} 
0

,並打印出剛剛創建的URL使用...

import requests 
import json 

response = requests.put("https://api.shorte.st/v1/data/url", {"urlToShorten":"google.com"}, headers={"public-api-token": "85d3636f48c112de6e413865afc177b5"}) 
decoded_response = json.loads(response.content) 
print(decoded_response['shortenedUrl'])