2.6 Python 調用 API 案例講解

本節要點

  • 瞭解POSTMAN CODE功能
  • Python調用API演示

課前準備

課程內容

POSTMAN CODE

(演示 - 使用POSTMAN快速生成API調用程式碼)

Jodoo的demo演示

(演示 - 使用Requests及Json庫定義函數調用Jodoo的APIAPI

  • 複製POSTMAN的CODE至Python,注意Body要替換成POSTMAN Body裏面的內容(POSTMAN CODE裏面的body內容有一些亂,使用原始的Json更好)

import requests

url = "https://api.jiandaoyun.com/api/v1/app/5dce13f43087860006c70e7a/entry/5dce145c26aecf00062e7db0/data_retrieve"

#替換Body前
payload = "{\r\n    \"data_id\": \"5dd6740646357c0006e6eb6e\"\r\n}"
#替換Body后
payload = {
          "data_id": "5dd6740646357c0006e6eb6e"
      }

headers = {
  'Authorization': 'Bearer xxxxxxx',
  'Content-Type': 'application/json',
  'Cookie': 'JDY_SID=s%3AkkffLPwwM05AA85K8IdYsXPF0zB-I0fi.GLHEBt5s61l9x0S7idpqYTFPIoUccDRv4IdXRYertCU; DEV_SID=s%3AdpxME_zPEoygRg8TxawKi6TQsalZ8p-V.mYUJRUHwMd95JFvz1tg2Zssl%2B4a%2BQRVq%2FGSckENfixY'
}

response = requests.request("POST", url, headers=headers, data = payload)

print(response.text.encode('utf8'))
  • 定義函數,替換payload的參數為函數的變數,注意要把payload轉換成Json
import requests
import json
def jdy(dataid):
    url = "https://api.jodoo.com/api/v1/app/5dce13f43087860006c70e7a/entry/5dce145c26aecf00062e7db0/data_retrieve"
    payload = {
        "data_id": dataid
    }
    headers = {
      'Authorization': 'Bearer xxxxxxxxx',
      'Content-Type': 'application/json',
      'Cookie': 'JDY_SID=s%3AkkffLPwwM05AA85K8IdYsXPF0zB-I0fi.GLHEBt5s61l9x0S7idpqYTFPIoUccDRv4IdXRYertCU; DEV_SID=s%3AdpxME_zPEoygRg8TxawKi6TQsalZ8p-V.mYUJRUHwMd95JFvz1tg2Zssl%2B4a%2BQRVq%2FGSckENfixY'
    }
#注意,這裡要把payload轉換成Json
    response = requests.request("POST", url, headers=headers, data = json.dumps(payload))
#最後只要列印出response.text即可,requests會自動把字節編碼成字串!
    print(response.text)
  • 下面即可開始調用你的函數了!
jdy("5dd6740646357c0006e6eb6e")

這項資訊有幫助嗎?
需要更多協助嗎?聯繋技術支援。