0

I've created a REST API base on this tutorial - note that I am a newbie in php and REST...

Now, I am stuck when calling a POST request. The main return function is as follows:

// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
    $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}

try {
    $API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
    $res = $API->processAPI();
    echo $res;   // contains my json as expected
    return $res; // always empty string
} catch (Exception $e) {
    echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}

EDIT I've just tried something even simpler in the API caller method, namely following:

try {
    $res = json_encode(Array('test' => "my message"));
    // comment out one or the other to check output...
    //echo $res;
    return $res;
} catch (Exception $e) {
    echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}

Result with echo is (the way I get responese is below... exact response is between # characters):

#{"test":"my message"}#

Result with return is

##

EDIT 2 Here is how I call the API from C#:

using (HttpClient client = new HttpClient()) { 
    JObject jo = new JObject();
    jo.Add("usr", "username");
    jo.Add("pwd", "password");
    Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
    StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
    HttpResponseMessage response = await client.PostAsync(url, content);
    bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
    // this is where I get the result from...
    var res = response.Content.ReadAsStringAsync().Result;
}

I really don't understand this - could someone please explain in non-php expert terms??

neggenbe
  • 1,697
  • 2
  • 24
  • 62

0 Answers0