# 外部サービスとのインテグレーション

> Extend Cloud Code modules with external services using NuGet packages or HTTP clients.

Cloud Code モジュールを外部サービスと統合できます。

カスタムデータ型を処理するには、[カスタム JSON シリアル化](./initialize-modules/custom-serialization.md) を実装します。

## NuGet パッケージの使用##use-nuget-packages

Cloud Code モジュールは .NET エコシステム内でライブになる C# ライブラリプロジェクトであるため、[NuGet パッケージマネージャー](https://learn.microsoft.com/en-us/nuget/) を使用して依存関係をインストールします。これは、任意の外部 NuGet パッケージを Cloud Code モジュール内で使用できることを意味します。

使用可能な NuGet パッケージを表示するには、[NuGet パッケージライブラリ](https://www.nuget.org/) を参照してください。

## 外部 API の呼び出し##call-out-to-external-apis

任意の外部 API を呼び出すこともできます。以下のサンプルは、[Cat Facts API](https://catfact.ninja/#/facts/getrandomfact) を呼び出してランダムなネコの豆知識を取得します。

1. `CatFactsApi` クラスを宣言して API 呼び出しを処理します。

   ```csharp
   using Newtonsoft.Json;
   using RestSharp;
   using Unity.Services.CloudCode.Core;
   using Unity.Services.CloudCode.Shared;

   namespace CatFacts;

   public interface ICatFactsApi
   {
       public Task<CatFactsApiResponse?> GetCatFact();
   }

   public class CatFactsApiResponse
   {
       public string fact { get; set; }
       public int length { get; set; }
   }

   public class CatFactsApi : ICatFactsApi
   {
       private readonly RestClient _httpClient;

       public CatFactsApi()
       {
           // It's important to only create one RestClient per service in order to avoid creating and destroying too many network connections which could hurt performance
           _httpClient = new RestClient("https://catfact.ninja/fact");
       }

       public async Task<CatFactsApiResponse?> GetCatFact()
       {
           var request = new RestRequest();

           try
           {
               var res = await _httpClient.ExecuteGetAsync(request);
               return JsonConvert.DeserializeObject<CatFactsApiResponse?>(res.Content);
           }
           catch (ApiException e)
           {
               throw new Exception($"Failed to get cat fact: {e.Message}");
           }
       }
   }
   ```

2. `CatFactsApi` クラスを `ModuleConfig` クラス内のシングルトンとして宣言します。

   ```csharp
       public class ModuleConfig : ICloudCodeSetup
       {
           public void Setup(ICloudCodeConfig config)
           {
               config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi());
           }
       }
   ```

3. `CatFactsApi` クラスの `GetCatFact` メソッドを呼び出す `GetCatFact` 関数を宣言します。

   ```csharp
   using Microsoft.Extensions.DependencyInjection;
   using Microsoft.Extensions.Logging;
   using Unity.Services.CloudCode.Core;
   using Unity.Services.CloudCode.Shared;

   namespace CatFacts;

   public class CatFactsSample
   {
       private static ILogger<CatFactsSample> _logger;
       public CatFactsSample(ILogger<CatFactsSample> logger)
       {
           _logger = logger;
       }

       [CloudCodeFunction("GetCatFact")]
       public async Task<CatFactsApiResponse?> GetCatFact(ICatFactsApi catFactsApi)
       {
           try
           {
               var fact = await catFactsApi.GetCatFact();
               _logger.LogInformation("Cat fact: {fact}", fact?.fact);

               return fact;

           }
           catch (ApiException e)
           {
               _logger.LogError("Failed to get cat fact. Error: {Error}", e.Message);
               throw new Exception($"Failed to get cat fact: {e.Message}");
           }
       }

       public class ModuleConfig : ICloudCodeSetup
       {
           public void Setup(ICloudCodeConfig config)
           {
               config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi());
           }
       }
   }
   ```

4. ゲームクライアントから `GetCatFact` 関数を呼び出します。関数は、ランダムなネコの豆知識を返します。

   ```json
   {
       "output": {
           "fact": "The Amur leopard is one of the most endangered animals in the world.",
           "length": 68
       }
   }
   ```

Unity サービスと統合する方法の詳細については、[他の Unity サービスとのインテグレーション](./unity-services-integration.md) を参照してください。
