AJAX post request to third party REST api

1.1k Views Asked by At

. I am using laravel backend as API and angular as frontend which calls laravel api. Laravel api access the teamwork api through basic authentication using curl.

Now I am working with teamwork Api. Trying to create a comment using the API. API documentation describes following.

    {
  "comment": {
    "body": "Reply to earlier comment",
    "notify": "",
    "isprivate": false,
    "pendingFileAttachments": "",
    "content-type": "TEXT"
  }
}

//ref : http://developer.teamwork.com/comments#creating_a_commen

in my ajax call i have used following

  var data = $.param({
    'body' : commentBodyValue,  //variable
    'notify': "",
    'isPrivate':false,
    "pendingFileAttachments": "",
    "content-type": "TEXT"
  });

My post does not give error, but it also do not create a new comment too. What am I missing? I think i failed to arrange data according to the format allowed in api. Can you kindly help me to fix it?

Edit:

Angular Controller:

//add new comment
$scope.addComment = function(taskId,commentAuthorId)
{
  var commentBod  = document.getElementById("commentBody");
  var commentBodyValue = commentBod.value;
  console.log("new comment : "+ taskId + commentBodyValue);
  //submit the post request
  //$http.post();
  //using jquery function param to serialize 
  var data = $.param({
    'body' : commentBodyValue,
    'notify': "",
    'isPrivate':false,
    "pendingFileAttachments": "",
    "content-type": "TEXT"
  });
  var config = {
      headers : {
          // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  }
  var url = "http://abounde.com/portal/api/post_comment/"+taskId;
  $http.post(url,data,config)
  .then(
    function(response){
      //success
      console.log("response : Submitted :D  " + response);
    },
    function(response){
      //failure
      console.log(response);
    }
  );

}

Edit 2

Laravel route and controller Routes: //post comment to resource Route::post('post_comment/{task_id}',[ 'uses'=>'PortalController@postComment', 'as'=>'portal.client.postComment' ]);

Controller:

    //post comment at task
        public function postComment(Request $request, $task_id)
        {
            $secretApiKey = $request->session()->get('secretApiKey');
            if(!empty($secretApiKey)){
            //post the msg
                $this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json");

            }else{
                return response()->json(['response'=>"Not Logged In"]);
            }           
        }


//authentication method

    public function callTeamworkApi($secretApiKey, $apiCallString)
    {
            //cURL
        $password = "xxx";
        $channel = curl_init();
        //options
        curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
        curl_setopt($channel, CURLOPT_HTTPHEADER,
                    array(
                      "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
        ));


        $msg = curl_exec($channel);
        curl_close($channel);
        return response()->json(['res'=>$msg]);

    }

EDIT 3: Contacted with teamwork Api support. After their advice i came up with following code

  //post comment at task
    public function postComment(Request $request, $task_id)
    {
        $secretApiKey = $request->session()->get('secretApiKey');
        if(!empty($secretApiKey)){

        //post the msg
            $comment=array();
            // $comment['body']=$request->input('body');
            // $comment['notify']=$request->input('notify');          
            // $comment['isprivate']=$request->input('isprivate');
            // $comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
            // $comment['content-type']=$request->input('content-type');


            $comment['comment']['body']="test";
            $comment['comment']['notify']="";
            $comment['comment']['isprivate']=false;
            $comment['comment']['pendingFileAttachments']="";
            $comment['comment']['content-type']="text";


            $this->callTeamworkPostApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));
            //var_dump($comment);
            //return response()->json(['response'=>"Trying"]);
        }else{
            return response()->json(['response'=>"Not Logged In"]);
        }           
    }
}

///

  public function callTeamworkPostApi($secretApiKey, $apiCallString,$comment)
{
        //cURL
    $password = "xxx";
    $channel = curl_init();
    //options
    curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
    curl_setopt($channel, CURLOPT_HTTPHEADER,
                array(
                  "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
    ));
    curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);


    $msg = curl_exec($channel);
    curl_close($channel);
            var_dump($msg);
    //return response()->json(['res'=>$msg]);


}

var_dump($comment) gives

string(107) "{"comment":{"body":"test","notify":"","isprivate":false,"pendingFileAttachments":"","content-type":"text"}}"

However the api still do not save the comment. It has to be a curl post method issue. Right?

Edit 4: I have done a var_dump(curl_getinfo($channel));

this gave me following response.

array(26) { ["url"]=> string(55) "http://projects.abounde.com/tasks/8199861/comments.json" ["content_type"]=> NULL ["http_code"]=> int(500) ["header_size"]=> int(229) ["request_size"]=> int(311) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.5) ["namelookup_time"]=> float(0) ["connect_time"]=> float(0.109) ["pretransfer_time"]=> float(0.109) ["size_upload"]=> float(107) ["size_download"]=> float(0) ["speed_download"]=> float(0) ["speed_upload"]=> float(214) ["download_content_length"]=> float(0) ["upload_content_length"]=> float(107) ["starttransfer_time"]=> float(0.5) ["redirect_time"]=> float(0) ["redirect_url"]=> string(0) "" ["primary_ip"]=> string(13) "23.23.184.208" ["certinfo"]=> array(0) { } ["primary_port"]=> int(80) ["local_ip"]=> string(11) "192.168.0.6" ["local_port"]=> int(31657) }

The response code 500 may points to the fact that teamwork has some kind of internal issues.

2

There are 2 best solutions below

9
Hamza Dairywala On

The issue i found out is that you are not passing your comment data which you received from the frontend to the curl the request in callTeamworkApi().Try below code and see if you get your desired output or not

//post comment at task
    public function postComment(Request $request, $task_id)
    {
        $secretApiKey = $request->session()->get('secretApiKey');
        if(!empty($secretApiKey)){

        //post the msg
            $comment=array();
            $comment['body']=$request->input('body');
            $comment['notify']=$request->input('notify');          
            $comment['isPrivate']=$request->input('isprivate');
            $comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
             $comment['content-type']=$request->input('content-type');


            $this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));

        }else{
            return response()->json(['response'=>"Not Logged In"]);
        }           
    }


 //authentication method

public function callTeamworkApi($secretApiKey, $apiCallString,$comment)
{
        //cURL
    $password = "xxx";
    $channel = curl_init();
    //options
    curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
    curl_setopt($channel, CURLOPT_HTTPHEADER,
                array(
                  "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
    ));
    curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);


    $msg = curl_exec($channel);
    curl_close($channel);
    return response()->json(['res'=>$msg]);

}
0
Nurul Alam On

Solution Found: While calling to the teamwork API, it is essential that the content-type is set to Json. and the information should be in header file. header variable should be a multi array which takes authentication and content type information.

$headers = array();
$headers[] = "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password);
$headers[] = "Content-Type: application/json";


    //pass it as variable
    curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);

And then it works like charm.

returns following after creation of the comment.

{"commentId":"4294639","STATUS":"OK"}