[Unity/C#] REST API places request

Hi all,
I’m want to use the REST API to search for places.

$ curl -X POST ‘https://places-dsn.algolia.net/1/places/query
-H ‘X-Algolia-Application-Id: YourApplicationId’
-H ‘X-Algolia-API-Key: YourAPIKey’
–data ‘{“query”: “Paris”}’

In Unity I replicated the authentification part as:

UnityWebRequest www = UnityWebRequest.Post("https://places-dsn.algolia.net/1/places/query", form);
www.SetRequestHeader("X-Algolia-Application-Id", "XXXXX");
www.SetRequestHeader("X-Algolia-API-Key", "XXXXXX");

But I’m stuck with formatting the data
As it has to be a POST request, the form I added to the request is:

WWWForm form = new WWWForm();
form.AddField(“data”, “{“query”: “Paris”}”);

But I keep receiving the following error:

{“message”:“lexical error: invalid char in json text. Around ‘%3fdata=%3’ near line:1 column:1”,“status”:400}

Can someone help me with this?
Thank you so much.

Hi there,

Algolia’s API is waiting for JSON in the body so you should use the following snippets to request the Places API:

var body = new Dictionary<string,string> {{"query", "Paris"}};

SendRequest("https://places-dsn.algolia.net/1/places/query’", UnityWebRequest.kHttpVerbPOST, body);

UnityWebRequest SendRequest(string url, string method, object body)
    string bodyString = null;

    if (body is string)
        bodyString = (string)body;
    else if (body != null)
        bodyString = JsonUtility.ToJson(body);
    var request = new UnityWebRequest();

    request.url = url;
    request.method = method;
    request.downloadHandler = new DownloadHandlerBuffer();
    request.uploadHandler = new UploadHandlerRaw(string.IsNullOrEmpty(bodyString) ? null : Encoding.UTF8.GetBytes(bodyString));
    request.SetRequestHeader("Accept", "application/json");
    request.SetRequestHeader("Content-Type", "application/json");
    request.SetRequestHeader("X-Algolia-Application-Id", "XXXXX");
    request.SetRequestHeader("X-Algolia-API-Key", "XXXXXX");
    return request;

Hope this helps!

Code snippets inspired from here.