I can't figure out how to post/get to the API in Unity. I was using the Mongo Driver before, but that seems to not work on UWP (I guess?) So I'm trying to get the Atlas API set up, but I can't figure out how to call it.

IEnumerator Test()
    ActivationCode code = new ActivationCode();
    code.code = "Test";

    string json = JsonUtility.ToJson(code);

    string url = "https://ap-southeast-1.aws.data.mongodb-api.com/app/data-mgiig/endpoint/data/v1/action/insertOne";
    UnityWebRequest request = new UnityWebRequest(url, "POST");
    json = "{\"database\":\"ActivationCodes\",\"collection\":\"ActivationCode\"," + json + "}";
    request.SetRequestHeader("Content-Type", "application/json");

    request.SetRequestHeader("api-key", "....");

    byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);
    request.uploadHandler = new UploadHandlerRaw(bodyRaw);

    yield return request.SendWebRequest();


Pastebin link

This is my code... The logs in Atlas API are giving "OK", but Unity is giving me a 400 error. I just made this as a test to try and get the API all set up. (Don't worry, I left the API key in, but will make a new one after.)

I'm guessing the API key is being set properly, as the request is going through. Maybe it has something to do with me adding the JSON weirdly, but I don't know how the syntax is supposed to be. I'm assuming this is a simple fix, it's calling the API, it's returning "OK" in the MongoDB logs, but I'm getting a 400 error.

Does anyone know how to solve this?

  • \$\begingroup\$ Are you sure your json is correctly formatted? You have 2 pairs and a single value. \$\endgroup\$
    – Zibelas
    Mar 6 at 21:36
  • \$\begingroup\$ @Zibelas What do you mean? Oh, if you're saying because I got "ActivationCode" twice, it's because the database is called ActivationCodes and the collection is called "ActivationCode" \$\endgroup\$
    – Makineko
    Mar 6 at 21:39
  • \$\begingroup\$ @Zibelas just tested by making the json a single class(instead of manually adding all the /s and ,s) that contains an activation code, so it contains a database and collection and i'm just converting it to one json. Still getting the 400 error. \$\endgroup\$
    – Makineko
    Mar 6 at 21:47
  • \$\begingroup\$ Can you share the full JSON you're sending (with any private data/API keys replaced with a placeholder, naturally)? \$\endgroup\$
    – DMGregory
    Mar 6 at 22:51
  • 1
    \$\begingroup\$ A 400 error code means, you have a bad request. The json you have in this code is not fully shown and the most likely error source. How do you know it is not important when you as well do not know what the error is? \$\endgroup\$
    – Zibelas
    Mar 8 at 6:48


You must log in to answer this question.

Browse other questions tagged .