SageMaker 推論エンドポイントと API Gateway REST API との統合

SageMaker 推論エンドポイントと API Gateway REST API との統合

Takahiro Iwasa
(岩佐 孝浩)
Takahiro Iwasa (岩佐 孝浩)
3 min read
API Gateway SageMaker

SageMaker は推論エンドポイントを提供しています。ユーザーは直接だけでなく、統合リクエストを使用して API Gateway の REST API を介してもアクセスできます。

概要

以下の例では AWS Lambda は使用していません。

SageMaker 推論エンドポイント確認

SageMaker コンソールで Endpoint summary > URL に推論エンドポイントが記載されています。

エンドポイントの形式は https://runtime.sagemaker.<ENDPOINT_REGION>.amazonaws.com/endpoints/<ENDPOINT_NAME>/invocations です。有効な Authorization ヘッダーを含めてリクエストするので、このエンドポイントは AWS アカウント ID がなくても正常に動作します。

Endpoints are scoped to an individual account, and are not public. The URL does not contain the account ID, but Amazon SageMaker determines the account ID from the authentication token that is supplied by the caller.

SageMaker 推論エンドポイントを利用して REST API 構築

REST API を選択してください。

API の名前を指定してください。

Actions -> Create Method を選択してください。

メソッドタイプを選択してください。下の例では POST を利用しています。

以下の表に従って必要なパラメーターを指定してください。

FieldValue
Integration typeAWS Service
AWS ServiceSageMaker Runtime (SageMaker ではありません)
HTTP methodPOST
Action TypeUse path override
Path override (optional)endpoints/<ENDPOINT_NAME>/invocations
Execution roleAPI 用 IAM ロール
(sagemaker:InvokeEndpoint が許可されている必要があります)
Content HandlingPassthrough

メソッド作成は完了です。

設定

モデルが入力としてバイナリデータを想定している場合は、 Binary Media Typesimage/* のような MIME タイプを追加してください。

MIME タイプが追加されていない場合、以下のレスポンスが表示されるはずです。

{
    "ErrorCode": "CLIENT_ERROR_FROM_MODEL",
    "LogStreamArn": "arn:aws:logs:ap-northeast-1:xxxxxxxxxxxx:log-group:/aws/sagemaker/Endpoints/<ENDPOINT_NAME>",
    "Message": "Received client error (400) from primary with message \"unable to evaluate payload provided\". See https://ap-northeast-1.console.aws.amazon.com/cloudwatch/home?region=ap-northeast-1#logEventViewer:group=/aws/sagemaker/Endpoints/<ENDPOINT_NAME> in account xxxxxxxxxxxx for more information.",
    "OriginalMessage": "unable to evaluate payload provided",
    "OriginalStatusCode": 400
}

デプロイ

API をデプロイしてください。

デプロイ後、 API エンドポイントを確認できます。

テスト

次のコマンドで API エンドポイントにアクセスしてください。

curl --location '<API_ENDPOINT>' \
  --header 'Content-Type: image/jpeg' \
  --header 'Accept: application/json' \
  --data-binary '@/path/to/image.jpg'
Takahiro Iwasa
(岩佐 孝浩)

Takahiro Iwasa (岩佐 孝浩)

Software Developer at iret, Inc.
主に AWS を利用したクラウドネイティブアプリケーションの設計および開発をしています。 Japan AWS Top Engineers 2020-2023