HTTP 요청 수행

HTTP 호출을 수행하는 워크플로 단계를 정의하고 호출의 응답을 변수에 할당할 수 있습니다. 예를 들어 HTTP 요청을 통해 Cloud Functions 또는 Cloud Run과 같은 Google Cloud 서비스를 호출할 수 있습니다.

HTTP 엔드포인트 호출

이 유형의 단계를 사용하면 HTTP 요청을 수행할 수 있습니다. HTTP 요청과 HTTPS 요청이 모두 지원됩니다. 가장 일반적인 HTTP 요청 메서드에는 호출 단축키(예: http.gethttp.post)가 있지만, call 필드를 http.request로 설정하고 method 필드를 사용해 요청 유형을 지정하여 모든 유형의 HTTP 요청을 수행할 수 있습니다.

YAML

  - STEP_NAME:
      call: HTTP_REQUEST
      args:
          url: URL_VALUE
          method: REQUEST_METHOD
          private_service_name: "REGISTERED_SERVICE"
          headers:
              HEADER_KEY:HEADER_VALUE
              ...
          body:
              BODY_KEY:BODY_VALUE
              ...
          query:
              QUERY_KEY:QUERY_VALUE
              ...
          auth:
              type: AUTH_TYPE
              scope: AUTH_SCOPE
              scopes: AUTH_SCOPE
              audience: AUDIENCE
          timeout: TIMEOUT_IN_SECONDS
      result: RESULT_VALUE
    

JSON

  [
    {
      "STEP_NAME": {
        "call": "HTTP_REQUEST",
        "args": {
          "url": "URL_VALUE",
          "method": "REQUEST_METHOD",
          "private_service_name": "REGISTERED_SERVICE",
          "headers": {"HEADER_KEY":"HEADER_VALUE",
          ...
          },
          "body": {"BODY_KEY":"BODY_VALUE",
          ...
          },
          "query": {"QUERY_KEY":"QUERY_VALUE",
          ...
          },
          "auth": {
            "type":"AUTH_TYPE",
            "scope":"AUTH_SCOPE",
            "scopes":"AUTH_SCOPE",
            "audience":"AUDIENCE"
          },
          "timeout": "TIMEOUT_IN_SECONDS"
        },
        "result": "RESULT_VALUE"
      }
    }
  ]
    

다음을 바꿉니다.

  • HTTP_REQUEST: 필수 항목입니다. HTTP 요청에 다음 중 하나를 사용합니다.
    • http.delete
    • http.get
    • http.patch
    • http.post
    • http.put
    • http.request
  • URL_VALUE: 필수 항목입니다. 요청이 전송된 URL입니다.
  • REQUEST_METHOD: 호출 유형 http.request를 사용하는 경우 필수. 사용할 HTTP 요청 메서드의 유형입니다. 예를 들면 다음과 같습니다.
    • GET
    • POST
    • PATCH
    • DELETE
  • REGISTERED_SERVICE: 선택사항. 등록된 서비스 디렉터리 서비스 이름이며 projects/PROJECT_ID/locations/LOCATION/namespaces/NAMESPACE_NAME/services/SERVICE_NAME 형식입니다. 자세한 내용은 VPC 서비스 제어 규정을 준수하는 비공개 엔드포인트 호출을 참조하세요.
  • HEADER_KEY:HEADER_VALUE: 선택사항. API에 입력 데이터를 제공하는 헤더 필드입니다.

    Content-Type 헤더를 사용하여 요청 본문의 미디어 유형을 지정하면 다음 유형만 지원됩니다.

    • application/json 또는 application/type+json—지도여야 합니다.
    • application/x-www-form-urlencoded—인코딩되지 않은 문자열이어야 합니다.
    • text/type—문자열이어야 합니다.

    Content-Type 헤더가 지정된 경우 본문이 사전 규칙에 따라 인코딩됩니다. 예를 들어 JSON 또는 URL로 인코딩될 수 있습니다.

    User-Agent 헤더를 사용하여 요청 사용자 에이전트를 식별하는 경우 다음 사항이 적용됩니다.

    • 기본값은 GoogleCloudWorkflows; (+https://cloud.google.com/workflows/docs)입니다.
    • 값이 지정되면 값에 GoogleCloudWorkflows; (+https://cloud.google.com/workflows/docs)가 추가됩니다.

      예를 들어 User-Agent: "MY_USER_AGENT_VALUE"가 지정되면 HTTP 요청 헤더는 다음과 같습니다(지정된 값과 추가된 기본값 사이에 공백이 있음).

      MY_USER_AGENT_VALUE GoogleCloudWorkflows; (+https://cloud.google.com/workflows/docs)
  • BODY_KEY:BODY_VALUE: 선택사항. API에 입력 데이터를 제공하는 body 필드입니다.

    Content-Type 헤더가 지정되지 않았고 요청 본문이 있으면 다음이 적용됩니다.

    • 본문 값이 바이트이면 헤더가 Content-Type: application/octet-stream으로 설정됩니다.
    • 그렇지 않으면 본문이 JSON으로 인코딩되고 헤더가 Content-Type: application/json; charset=utf-8로 설정됩니다.
    다음 예시는 JSON 페이로드와 동일한 본문 구조를 보여줍니다.

    YAML

    body:
      requests:
      - image:
          source:
            gcsImageUri: ${gsUri}
        features:
        - type: LABEL_DETECTION
        - type: SAFE_SEARCH_DETECTION
        - type: IMAGE_PROPERTIES
    result: imageAnalysisResponse

    JSON

    {
      "requests":[
        {
          "image": {
            "source": {
                "gcsUri": "img.png"
            }
          },
          "features": [
            { "type":"LABEL_DETECTION" },
            { "type":"SAFE_SEARCH_DETECTION" },
            { "type":"IMAGE_PROPERTIES" },
          ]
        }
      ]
    }
  • QUERY_KEY:QUERY_VALUE: 선택사항입니다. API에 입력 데이터를 제공하는 쿼리 필드입니다.
  • AUTH_TYPE: 선택사항입니다. 호출 중인 API에 인증이 필요한 경우 필수입니다. OIDC 또는 OAuth2를 사용합니다. 자세한 내용은 워크플로에서 인증된 요청 수행을 참조하세요.
    • AUTH_SCOPE: 선택사항입니다. 애플리케이션 액세스를 사용자 계정으로 제한합니다. scope 또는 scopes 키를 사용합니다.

      scope 키는 문자열 또는 문자열 목록을 지원합니다. 예를 들면 다음과 같습니다.

      "https://www.googleapis.com/auth/cloud-platform"

      또는

      ["https://www.googleapis.com/auth/cloud-platform", "scope2", "scope3"]

      scopes 키는 문자열 또는 문자열 목록을 지원하는 것 외에도 공백 및 쉼표로 구분된 문자열을 지원합니다. 예를 들면 다음과 같습니다.

      "https://www.googleapis.com/auth/cloud-platform scope2 scope3"

      또는

      "https://www.googleapis.com/auth/cloud-platform,scope2,scope3"

      자세한 내용은 Google API의 OAuth 2.0 범위를 참조하세요.

    • AUDIENCE: 선택사항입니다. OIDC 토큰 대상을 지정합니다. 기본적으로 url과 동일한 값으로 설정되지만 서비스의 기준 URL로 설정되어야 합니다. 예를 들면 https://region-project.cloudfunctions.net/hello_world입니다.
  • TIMEOUT_IN_SECONDS: 선택사항입니다. 예외를 유발하기 전에 요청을 실행할 수 있는 시간(초)입니다. 최댓값은 1,800초입니다.
  • RESULT_VALUE: 선택사항입니다. HTTP 호출 단계의 결과가 저장되는 변수 이름입니다.

변수에 저장된 HTTP 응답 데이터 액세스

응답의 Content-Type 헤더가 application/json 미디어 유형을 지정하면 변수에 저장된 JSON 응답이 액세스 가능한 맵으로 자동 변환됩니다.

필요한 경우 Content-Type 응답 헤더에 application/json 미디어 유형을 지정하도록 호출되는 API를 수정합니다. 그렇지 않으면 json.decodetext.encode 함수를 사용하여 응답 본문을 맵으로 변환합니다. 예를 들면 다음과 같습니다.

json.decode(text.encode(RESPONSE_FROM_API))

워크플로에는 이 데이터에 액세스하기 위한 기본 제공 파서가 포함되어 있습니다. HTTP 응답에서 필드에 액세스하려면 다음 구문을 사용합니다.

${VARIABLE_NAME.body|code|headers.PATH_TO_FIELD}

다음을 바꿉니다.

  • VARIABLE_NAME: JSON 응답을 저장한 워크플로 변수의 이름입니다.
  • body: body 필드를 사용하여 HTTP 응답 본문에 액세스합니다.
  • code: code 필드를 사용하여 HTTP 응답 코드에 액세스합니다.
  • headers: headers 필드를 사용하여 이름별로 HTTP 응답 헤더에 액세스합니다.
  • PATH_TO_FIELD: 액세스하려는 JSON 응답의 필드 경로입니다. 단순히 필드의 이름일 수도 있고, 필드가 객체 내에 중첩되어 있는 경우 object1.object2.field 형식을 취할 수 있습니다.

예를 들어 API가 {"age":50}을 반환하고 워크플로가 이 응답을 age_response라는 변수에 저장하면 다음 예시는 age 필드 값을 반환합니다. 이 경우는 50입니다.

age_response.body.age

샘플

이러한 샘플은 구문을 보여줍니다.

API 호출에서 응답 할당

자체 검색어를 입력하지 않는 한 이 샘플은 Google Cloud 위치를 사용하여 검색어를 구성하며 이는 Wikipedia API로 전달됩니다. 관련 Wikipedia 자료 목록이 반환됩니다.

YAML

main:
  params: [input]
  steps:
    - checkSearchTermInInput:
        switch:
          - condition: '${"searchTerm" in input}'
            assign:
              - searchTerm: '${input.searchTerm}'
            next: readWikipedia
    - getLocation:
        call: sys.get_env
        args:
          name: GOOGLE_CLOUD_LOCATION
        result: location
    - setFromCallResult:
        assign:
          - searchTerm: '${text.split(location, "-")[0]}'
    - readWikipedia:
        call: http.get
        args:
          url: 'https://en.wikipedia.org/w/api.php'
          query:
            action: opensearch
            search: '${searchTerm}'
        result: wikiResult
    - returnOutput:
        return: '${wikiResult.body[1]}'

JSON

{
  "main": {
    "params": [
      "input"
    ],
    "steps": [
      {
        "checkSearchTermInInput": {
          "switch": [
            {
              "condition": "${\"searchTerm\" in input}",
              "assign": [
                {
                  "searchTerm": "${input.searchTerm}"
                }
              ],
              "next": "readWikipedia"
            }
          ]
        }
      },
      {
        "getLocation": {
          "call": "sys.get_env",
          "args": {
            "name": "GOOGLE_CLOUD_LOCATION"
          },
          "result": "location"
        }
      },
      {
        "setFromCallResult": {
          "assign": [
            {
              "searchTerm": "${text.split(location, \"-\")[0]}"
            }
          ]
        }
      },
      {
        "readWikipedia": {
          "call": "http.get",
          "args": {
            "url": "https://en.wikipedia.org/w/api.php",
            "query": {
              "action": "opensearch",
              "search": "${searchTerm}"
            }
          },
          "result": "wikiResult"
        }
      },
      {
        "returnOutput": {
          "return": "${wikiResult.body[1]}"
        }
      }
    ]
  }
}

외부 HTTP POST 요청 수행

이 샘플은 외부 HTTP 엔드포인트에 POST 요청을 수행합니다.

YAML

- get_message:
    call: http.post
    args:
      url: https://www.example.com/endpoint
      body:
        some_val: "Hello World"
        another_val: 123
    result: the_message
- return_value:
    return: ${the_message.body}

JSON

[
  {
    "get_message": {
      "call": "http.post",
      "args": {
        "url": "https://www.example.com/endpoint",
        "body": {
          "some_val": "Hello World",
          "another_val": 123
        }
      },
      "result": "the_message"
    }
  },
  {
    "return_value": {
      "return": "${the_message.body}"
    }
  }
]

헤더를 사용하여 외부 HTTP GET 요청 수행

이 샘플은 커스텀 헤더를 사용하여 HTTP GET 요청을 수행합니다. 다른 유형의 HTTP 요청을 수행할 때 커스텀 헤더 정의를 제공할 수도 있습니다.

YAML

- get_message:
    call: http.get
    args:
      url: https://www.example.com/endpoint
      headers:
        Content-Type: "text/plain"
      query:
        some_val: "Hello World"
        another_val: 123
    result: the_message
- return_value:
    return: ${the_message.body}

JSON

[
  {
    "get_message": {
      "call": "http.get",
      "args": {
        "url": "https://www.example.com/endpoint",
        "headers": {
          "Content-Type": "text/plain"
        },
        "query": {
          "some_val": "Hello World",
          "another_val": 123
        }
      },
      "result": "the_message"
    }
  },
  {
    "return_value": {
      "return": "${the_message.body}"
    }
  }
]

Cloud Functions에 요청을 보낼 때 OIDC를 사용하여 인증

이 샘플은 URL을 지정한 후 워크플로 정의의 args 섹션에 auth 섹션을 추가하여 OIDC를 사용하여 HTTP 요청을 보냅니다.

YAML

- call_my_function:
    call: http.post
    args:
      url: https://us-central1-myproject123.cloudfunctions.net/myfunc1
      auth:
        type: OIDC
      body:
        some_val: "Hello World"
        another_val: 123
    result: the_message
- return_value:
    return: ${the_message.body}

JSON

[
  {
    "call_my_function": {
      "call": "http.post",
      "args": {
        "url": "https://us-central1-myproject123.cloudfunctions.net/myfunc1",
        "auth": {
          "type": "OIDC"
        },
        "body": {
          "some_val": "Hello World",
          "another_val": 123
        }
      },
      "result": "the_message"
    }
  },
  {
    "return_value": {
      "return": "${the_message.body}"
    }
  }
]

HTTP 요청 오류 포착 및 처리

이 샘플은 GET 요청으로 반환된 HTTP 상태 코드를 기반으로 하는 커스텀 예외 핸들러를 구현합니다. 이 워크플로는 잠재적인 예외를 포착하고 사전 정의된 오류 메시지를 반환합니다. 예외가 인식되지 않으면 워크플로 실행이 실패하고 GET 요청으로 반환되는 대로 예외가 발생합니다. 다른 오류 태그는 워크플로 오류를 참조하세요.

YAML

- read_item:
    try:
      call: http.get
      args:
        url: https://example.com/someapi
        auth:
          type: OIDC
      result: API_response
    except:
      as: e
      steps:
        - known_errors:
            switch:
              - condition: ${not("HttpError" in e.tags)}
                next: connection_problem
              - condition: ${e.code == 404}
                next: url_not_found
              - condition: ${e.code == 403}
                next: auth_problem
        - unhandled_exception:
            raise: ${e}
- url_found:
    return: ${API_response.body}
- connection_problem:
    return: "Connection problem; check URL"
- url_not_found:
    return: "Sorry, URL wasn't found"
- auth_problem:
    return: "Authentication error"

JSON

[
  {
    "read_item": {
      "try": {
        "call": "http.get",
        "args": {
          "url": "https://example.com/someapi",
          "auth": {
            "type": "OIDC"
          }
        },
        "result": "API_response"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "known_errors": {
              "switch": [
                {
                  "condition": "${not(\"HttpError\" in e.tags)}",
                  "next": "connection_problem"
                },
                {
                  "condition": "${e.code == 404}",
                  "next": "url_not_found"
                },
                {
                  "condition": "${e.code == 403}",
                  "next": "auth_problem"
                }
              ]
            }
          },
          {
            "unhandled_exception": {
              "raise": "${e}"
            }
          }
        ]
      }
    }
  },
  {
    "url_found": {
      "return": "${API_response.body}"
    }
  },
  {
    "connection_problem": {
      "return": "Connection problem; check URL"
    }
  },
  {
    "url_not_found": {
      "return": "Sorry, URL wasn't found"
    }
  },
  {
    "auth_problem": {
      "return": "Authentication error"
    }
  }
]

다음 단계