교대 근무 예약 예

다음 예시에서는 인증에 API 키를 사용하여 Python requests 라이브러리로 API를 호출하는 방법을 보여줍니다. 사용하려면 다음 단계를 따르세요.

  • Python requests 라이브러리를 설치합니다. 명령줄에서: pip install requests.
  • 다음 Python 프로그램을 컴퓨터에 저장하고 이름을 example.py로 지정합니다.
  • 프로그램과 동일한 디렉터리 (샘플 JSON 요청)에 example_request.json 파일을 저장합니다.
  • {"key": "your_api_key"}를 사용하여 프로그램과 동일한 디렉터리에 credentials.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/scheduling:solveShiftScheduling"
    
    # 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% 로 설정하지만 이는 애플리케이션에 따라 달라질 수 있습니다. session.post(...) 호출을 더 깔끔하게 하기 위해 API 키도 세션 헤더로 옮겨졌습니다.



# 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)