หรือ API - ตัวอย่าง Python

ตัวอย่างต่อไปนี้จะแสดงวิธีเรียก API ด้วย Python requests โดยใช้คีย์ API สำหรับการตรวจสอบสิทธิ์ ก่อนอื่น ให้เลือกเมธอดของ API ที่สนใจ ดังนี้


วิธีทดลองใช้มีดังนี้

  • ติดตั้งไลบรารี Python requests จากบรรทัดคำสั่ง pip install requests
  • บันทึกโปรแกรม Python ต่อไปนี้ลงในคอมพิวเตอร์ของคุณ โดยตั้งชื่อโปรแกรมว่า example.py
  • ดาวน์โหลดตัวอย่าง ตั้งชื่อว่า example_request.json
  • เรียกใช้ตัวอย่างจากบรรทัดคำสั่ง python example.py

# example.py
import json
import requests

def run_example():
    """Calls the OR API to solve a shift scheduling problem."""
    
    # Endpoint for the workforce scheduling solver in the OR API.
    end_point = "https://optimization.googleapis.com/v1/"
    
    # Read the API Key from a JSON file with the format:
    # {"key": "your_api_key"}
    with open("credentials.json") as f:
        credentials = json.load(f)
        api_key = credentials["key"]

    # Load the JSON file with the request.
    with open("example_request.json", "r") as f:
        json_request = json.load(f)

    # Call the API post method.
    response = requests.post(f"{end_point}?key={api_key}", json=json_request)

    # Process the response.
    if response.ok:
        solution = json.loads(response.content)
        with open("example_response.json", "w") as f:
            json.dump(solution, f, indent=2)
        print(solution)
    else:
        error = json.loads(response.content)["error"]
        print(f'Status code {error["code"]}: {error["message"]}')

if __name__ == "__main__":
    run_example()

วิธีตั้งกำหนดเวลา

กำหนดเวลาจะกำหนดเวลาสูงสุดที่การเรียกใช้ API ควรใช้ ผู้ใช้สามารถตั้งกำหนดเวลาสำหรับไคลเอ็นต์และเซิร์ฟเวอร์ ในบริบทของ OR API กำหนดเวลาของเซิร์ฟเวอร์เป็นวิธีที่มีประโยชน์มากกว่า เนื่องจากจะช่วยให้เซิร์ฟเวอร์แบ็กเอนด์ทราบว่า แต่จะต้องได้รับคำขอ เรียกใช้เครื่องมือแก้โจทย์ที่สำคัญ และส่ง คำตอบ ในทางตรงกันข้าม กำหนดเวลาของลูกค้าจะมีประโยชน์ในการกำหนดเวลาสูงสุดที่ แอปพลิเคชันไคลเอ็นต์ (เช่น แอปพลิเคชันที่เรียกใช้ OR API) จะ รอการตอบกลับก่อนที่จะหมดเวลา

ข้อมูลโค้ดต่อไปนี้ตั้งค่าทั้งไคลเอ็นต์และกำหนดเวลาของเซิร์ฟเวอร์ใน ส่วนหัวเซสชันของคำขอ กำหนดเวลาของไคลเอ็นต์ตั้งไว้ที่ 60 วินาที กำหนดเวลาของเซิร์ฟเวอร์ควรน้อยกว่ากำหนดเวลาของไคลเอ็นต์ที่ควรใช้ ค่าใช้จ่ายในการสื่อสาร เราตั้งกำหนดเวลาของเซิร์ฟเวอร์ไว้ที่ 95% ของไคลเอ็นต์ กำหนดเวลาจริง แต่ก็อาจแตกต่างกันออกไปตามใบสมัคร โปรดทราบว่ามีการย้ายคีย์ API ไปยังส่วนหัวของเซสชันด้วยเพื่อให้การเรียกใช้ session.post(...) สะอาดขึ้น



# Call the API post method.
session = requests.Session()
client_deadline_seconds = 60
server_deadline_seconds = 0.95 * client_deadline_seconds
session.headers = {
    "Content-Type": "application/json",
    "Connection": "keep-alive",
    "Keep-Alive": f"timeout={client_deadline_seconds}, max=1",
    "X-Server-Timeout": f"{server_deadline_seconds}",
    "X-Goog-Api-Key": api_key,
}
response = session.post(end_point, json=json_request, timeout=client_deadline_seconds)