📑

UE5.4でLambdaを発火させてみる

2025/02/22に公開

概要

UE5.4でAPI Gateway経由でLambda関数を発火させるための方法メモです。主にC++側の実装にフォーカスしてます

Lambda側の準備

以下pythonコードでLambdaを作成

Lambda関数
import json

def lambda_handler(event, context):
    # TODO implement

    response = {
        "message": "Hello from Lambda!"
    }

    return {
        'statusCode': 200,
        'body': json.dumps(response)
    }

あとは適当にAPI Gateway APIを作成し、上記Lambdaのトリガとして設定してください。

C++側の準備

本記事ではUEプロジェクト名をCppTest、APIコールするクラス名をCallAPIとします。

Build.csの設定

早速引っかかりポイントですが、CppTest.Build.csを開き、HTTPJsonJsonUtilitiesを追加してください。

CppTest.Build.cs
// Copyright Epic Games, Inc. All Rights Reserved.

using UnrealBuildTool;

public class CppTest : ModuleRules
{
	public CppTest(ReadOnlyTargetRules Target) : base(Target)
	{
		PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

		PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "EnhancedInput", "HTTP", "Json", "JsonUtilities" });
	}
}

APIコールクラスの作成

CallAPI.hを下記のように作成します。

CallAPI.h
#pragma once

#include "HttpModule.h"
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "CallAPI.generated.h"

UCLASS()
class CPPTEST_API ACallAPI : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	ACallAPI();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
    // APIコール関数
	void CallApiGateway();

    // APIレスポンス時のコールバック関数
	void OnApiResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
};

CallAPI.cppを下記のように作成します。

CallAPI.cpp
#include "CallAPI.h"
#include "Json.h"
#include "JsonUtilities.h"
#include "Interfaces/IHttpResponse.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"

// Sets default values
ACallAPI::ACallAPI()
{
}

void ACallAPI::CallApiGateway()
{
    FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
    Request->SetURL("<API Gatewayのエンドポイント>");
    Request->SetVerb("GET");
    Request->SetHeader("Content-Type", "application/json");

    Request->OnProcessRequestComplete().BindUObject(this, &ACallAPI::OnApiResponseReceived);
    Request->ProcessRequest();
}

void ACallAPI::OnApiResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
	if (bWasSuccessful)
	{
        // レスポンスの処理
        FString ResponseBody = Response->GetContentAsString();
        UE_LOG(LogTemp, Warning, TEXT("Response: %s"), *ResponseBody);

		TSharedPtr<FJsonObject> JsonObject;
		TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(ResponseBody);
        if (FJsonSerializer::Deserialize(Reader, JsonObject) && JsonObject.IsValid())
        {
            // 例えば、"message" キーの値を取得する場合
            FString Message;
            if (JsonObject->TryGetStringField(TEXT("message"), Message))
            {
                UE_LOG(LogTemp, Log, TEXT("Message: %s"), *Message);
            }

            // 他のフィールドも必要に応じて取得可能
        }
        else
        {
            UE_LOG(LogTemp, Error, TEXT("Failed to parse JSON response"));
        }
	}
	else
	{
        UE_LOG(LogTemp, Error, TEXT("API request failed"));
	}
}

// Called when the game starts or when spawned
void ACallAPI::BeginPlay()
{
	Super::BeginPlay();

	CallApiGateway();
}

以下、雑に解説

if (FJsonSerializer::Deserialize(Reader, JsonObject) && JsonObject.IsValid())
{
    // 例えば、"message" キーの値を取得する場合
    FString Message;
    if (JsonObject->TryGetStringField(TEXT("message"), Message))
    {
        UE_LOG(LogTemp, Log, TEXT("Message: %s"), *Message);
    }

    // 他のフィールドも必要に応じて取得可能
}

ここでLabmda関数から返されるJSON形式のメッセージを処理してます。今回の例ではLambda側でmessageというキー名に値を詰めて返却しているため、c++側でもそれに併せてパースしています。

実行確認

ゲームを開始して、以下のようなログが確認できたら動作成功です。

LogTemp: Message: Hello from Lambda!

上手くいかない場合は、Lambda側の権限周りのミスか、C++側でのAPIのエンドポイントの設定ミスを疑ってください。

Discussion