FreshBooks API
Pythonとhttplib
モジュールを使用して接続しようとしています。私はパッケージで仕事をすることができましたRequests
が、私はスターターであり、学びたいので、標準の Python ライブラリを使用して動作させたいと考えています。
これが httplib を使用したコードです。
import base64, httplib
# test script created to connect with my test Freshbooks account
headers = {}
body = '/api/2.1/xml-in'
headers["Authorization"] = "Basic {0}".format(
base64.b64encode("{0}:{1}".format('I have put here my Auth Token', 'user')))
headers["Content-type"] = "application/xml"
# the XML we ll send to Freshbooks
XML = """<?xml version="1.0" encoding="utf-8"?>
<request method="task.list">
<page>1</page>
<per_page>15</per_page>
</request>"""
# Enable the job
conn = httplib.HTTPSConnection('devjam-billing.freshbooks.com')
conn.request('POST', body, None, headers)
resp = conn.getresponse()
print resp.status
conn.send(XML)
print resp.read()
conn.close()
そしてそれが Freshbooks が返すものです:
200
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="http://www.freshbooks.com/api/" status="fail">
<error>Your XML is not formatted correctly.</error>
<code>40010</code>
</response
パッケージを使用した 2 番目のスクリプトでは、post()
関数にヘッダーを追加して修正したのと同じ応答がありました。
import requests
XML = """<?xml version="1.0" encoding="utf-8"?>
<request method="task.list">
<page>1</page>
<per_page>15</per_page>
</request>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
r = requests.post('https://devjam-billing.freshbooks.com/api/2.1/xml-in', auth= ('my auth token', 'user'), data=XML, headers=headers)
print r.status_code
print r.headers['content-type']
# get the response
print r.text
最初のものを追加して、同様のことを試みました:
headers["Content-type"] = "application/xml"
成功せずに。
何か案は?また、b64encode はエンコードの安全なセキュリティ オプションですか、それともより安全な方法はありますか? ありがとう。