Integrate with external services

You can integrate Cloud Code modules with external services.

To handle custom data types, you can implement Custom JSON Serialization.

Use NuGet packages

Cloud Code modules are C# library projects that live in the .NET ecosystem, so they use the NuGet package manager to install dependencies. This means that you can use any external NuGet package in your Cloud Code modules.

To view the available NuGet packages, refer to the NuGet package library.

Call out to external APIs

You can also call out to any external APIs. The sample below calls out to a Cat Facts API to get a random cat fact.

  1. Declare a CatFactsApi class to handle the API call.

    C#

    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. Declare the CatFactsApi class as a singleton in the ModuleConfig class.

    C#

    public class ModuleConfig : ICloudCodeSetup
        {
            public void Setup(ICloudCodeConfig config)
            {
                config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi());
            }
        }
  3. Declare a GetCatFact function that will call the GetCatFact method of the CatFactsApi class:

    C#

    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. Call the GetCatFact function from your game client. The function returns a random cat fact:

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

For information on how to integrate with Unity services, refer to Integration with other Unity services.