I'm trying to get my client to work with my API but I'm having some trouble, i'm new to cURL so maybe you can help me.
My API controller (laravel.project/api/v1/users/{id}
public function show($user)
{
if ($user == null)
return $this->setStatusCode(404)->respondNotFound('User not found');
return $this->respond($user);
}
This is the answer I get by making a simple request with POSTMAN
{
"data": {
"id": 4,
"name": "Helena",
"email": "[email protected]",
"created_at": "2015-03-26 21:13:16",
"updated_at": "2015-03-26 21:13:16"
}
}
Response Headers:
Cache-Control → no-cache
Connection → keep-alive
Content-Type → application/json
Date → Sat, 28 Mar 2015 15:44:45 GMT
Server → nginx/1.6.2
Transfer-Encoding → chunked
Everything fine till now, but then, when I use cURL in my client this way:
public function delete($url, $token)
{
$final_url = $this->base_url . $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $final_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token, 'Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
The response I get is not a json:
"{
"data":{
"id":4,
"name":"Helena",
"email":"[email protected]",
"created_at":"2015-03-26 21:13:16",
"updated_at":"2015-03-26 21:13:16"}
}"
It looks like a json response but notice the quotes at the begging and at the end, I can't parse it neither with json_encode or json_decode.
I've been struggling with this for a while any opinion are apreciated.
Just to make sure you understand my problem, code is working well, but when making the request with curl it doesn't use the content-type header
EDIT 1:
{#165
+"data": {#167
+"id": 4
+"name": "Helena"
+"email": "[email protected]"
+"created_at": "2015-03-26 21:13:16"
+"updated_at": "2015-03-26 21:13:16"
}
}
Instead of return $result
, try:
return response()->json(json_decode($result));
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加