Error while updating backstory of the character

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Text;
using TMPro;
using UnityEngine.UI;

public class ConvaiNPCBackground : MonoBehaviour
{
    private string apiKey = "XXXXX";  // hidden the api key
    private string updateCharacterUrl = "https://api.convai.com/character/update";

    public TMP_InputField inputField;
    public Button submitButton;

    private void Start()
    {
        submitButton.onClick.AddListener(UpdateCharacter);
    }
    public void UpdateCharacter()
    {
        string characterId = "975cc5ee-eb2f-11ef-bac5-42010a7be016";
        string backstory = inputField.text;

        StartCoroutine(UpdateCharacterCoroutine(characterId, backstory));
    }

    private IEnumerator UpdateCharacterCoroutine(string characterId, string Backstory)
    {
        var requestData = new
        {
            charID = characterId,
            backstory = Backstory            
        };

        string json = JsonUtility.ToJson(requestData);
        byte[] jsonData = Encoding.UTF8.GetBytes(json);

        using (UnityWebRequest request = new UnityWebRequest(updateCharacterUrl, "POST"))
        {
            request.uploadHandler = new UploadHandlerRaw(jsonData);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("CONVAI-API-KEY", apiKey);

            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("Character backstory updated successfully: " + request.downloadHandler.text);
            }
            else
            {
                Debug.LogError("Error updating character backstory: " + request.error);
                Debug.LogError("Response: " + request.downloadHandler.text);
            }
        }
    }
}

I am getting

Error updating character backstory: HTTP/1.1 502 Bad Gateway

Response: <html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.18.0 (Ubuntu)</center>
</body>
</html>

Hello @bomiao42,

Welcome to the Convai Developer Forum!

I can share a code example with you that might help resolve this issue.

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;

public class ConvaiCharacterUpdater : MonoBehaviour
{
    private string apiUrl = "https://api.convai.com/character/update";
    private string apiKey = "<API Key>"; // Add your API key here

    [System.Serializable]
    public class CharacterData
    {
        public string charID;
        public string backstory;
    }

    void Start()
    {
        // Start the API request
        StartCoroutine(UpdateCharacter());
    }

    IEnumerator UpdateCharacter()
    {
        // Create JSON data
        CharacterData characterData = new CharacterData
        {
            charID = "<Character ID>", // Add your Character ID here
            backstory = "Raymond Reddington is a highly intelligent, highly driven individual with developed sociopathic tendencies..."
        };

        string jsonData = JsonUtility.ToJson(characterData);
        byte[] postData = Encoding.UTF8.GetBytes(jsonData);

        Debug.Log("Sending JSON: " + jsonData);

        // Create HTTP request
        UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
        request.uploadHandler = new UploadHandlerRaw(postData);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("CONVAI-API-KEY", apiKey);

        // Send the request
        yield return request.SendWebRequest();

        // Check the response
        if (request.result == UnityWebRequest.Result.Success)
        {
            Debug.Log("Character updated successfully: " + request.downloadHandler.text);
        }
        else
        {
            Debug.LogError("Error updating character: " + request.error);
            Debug.LogError("Server Response: " + request.downloadHandler.text);
        }
    }
}

I reviewed your code and identified the issue causing the error. The problem stems from the use of an anonymous object when serializing the JSON request. Unity’s JsonUtility.ToJson() does not support anonymous types, which can lead to improper serialization and an invalid request format.

Issue:

Your code currently defines the request payload as:

var requestData = new
{
    charID = characterId,
    backstory = Backstory            
};

However, JsonUtility.ToJson() requires an explicitly declared class marked as [System.Serializable].

To resolve this, I have modified your script to use a properly structured CharacterData class.

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Text;
using TMPro;
using UnityEngine.UI;

public class ConvaiNPCBackground : MonoBehaviour
{
    private string apiKey = "XXXXX";  // Hidden API key
    private string updateCharacterUrl = "https://api.convai.com/character/update";

    public TMP_InputField inputField;
    public Button submitButton;

    [System.Serializable]
    public class CharacterData
    {
        public string charID;
        public string backstory;
    }

    private void Start()
    {
        submitButton.onClick.AddListener(UpdateCharacter);
    }

    public void UpdateCharacter()
    {
        string characterId = "975cc5ee-eb2f-11ef-bac5-42010a7be016";
        string backstory = inputField.text;

        StartCoroutine(UpdateCharacterCoroutine(characterId, backstory));
    }

    private IEnumerator UpdateCharacterCoroutine(string characterId, string backstory)
    {
        // Create a properly structured request object
        CharacterData requestData = new CharacterData
        {
            charID = characterId,
            backstory = backstory
        };

        string json = JsonUtility.ToJson(requestData);
        byte[] jsonData = Encoding.UTF8.GetBytes(json);

        Debug.Log("Sending JSON: " + json); // Debug JSON to verify before sending

        using (UnityWebRequest request = new UnityWebRequest(updateCharacterUrl, "POST"))
        {
            request.uploadHandler = new UploadHandlerRaw(jsonData);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("CONVAI-API-KEY", apiKey);

            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("Character backstory updated successfully: " + request.downloadHandler.text);
            }
            else
            {
                Debug.LogError("Error updating character backstory: " + request.error);
                Debug.LogError("Response: " + request.downloadHandler.text);
            }
        }
    }
}

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.