'Back end to Back end API request and response
I have an app built on laravel 8
with a Vue Spa
front end, using Sanctum
.
I have a controller method that requests from another Laravel
project (using its Sanctum
API) so essentially, the Spa requests from Laravel 1, which requests from Laravel 2 project.
Following the responses from L2 project back, the Controller method on L2 is:
public function popular(Request $request)
{
$limit = 20;
if ($request->has('limit')) {
$limit = $request->limit;
}
$perPage = 20;
if ($request->has('per_page')) {
$limit = $request->per_page;
}
if ($request->has('page')) {
$articles = $request
->user()
->articles()
->activeArticles()
->select('articles.uuid', 'articles.title')
->orderBy('articles.views', 'DESC')
->simplePaginate($perPage);
} else {
$articles = $request
->user()
->articles()
->activeArticles()
->select('articles.uuid', 'articles.title')
->orderBy('articles.views', 'DESC')
->limit($limit)
->get();
}
return $articles;
}
This response is received by L1 Controller method, and sent back to the Spa like this:
public function popular(Request $request)
{
$apiEndPoint = self::$apiBaseUrl . '/article/popular';
$response = self::$httpRequest->get($apiEndPoint, $request->query());
if (!$response->successful()) {
return $this->setMessage(trans('help.api_error'))->send();
}
$body = $response->getBody();
return response(['data' => $body]);
}
With this return:
return response(['data' => $body]);
I get and empty data object:
{
data: {}
}
And with this return:
return response($body);
I get the payload as text / string:
[{"id":15,"uuid":"c6082143-0f34-443b-9447-3fa57ed73f48","name":"dashboard","icon":"database","active":1,"owned_by":2,"product_id":4,"created_at":"2021-12-23T11:46:35.000000Z","updated_at":"2021-12-23T11:46:35.000000Z"},{"id":16,
How do I return the $body
as JSON to the Spa?
UPDATE: I tried suggestions below, but the result is still exception.
return response()->json($body);
Returns:
"message": "json_decode(): Argument #1 ($json) must be of type string, GuzzleHttp\\Psr7\\Stream given",
So getting the body in getBody()
returns a string I understood.
If I Log the $body I get:
$body = $response->getBody();
Log::info($body);
[2021-12-25 23:15:36] local.INFO: {"current_page":2,"data":[{"uuid":"aa4a47bf-4975-4e78-868a-103398934504","title":"Ritchie-Hoeger"},
Thanks for any help and happy festive season.
Solution 1:[1]
API Responser
First create a trait in laravel in 'app\Traits\ApiResponser.php'
<?php
namespace App\Traits;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
trait ApiResponser{
public function set_response($data, $status_code, $status, $details)
{
$resData = response(json_encode(
[
'status' => $status, // true or false
'code' => $status_code,
'data' => $data,
'message' => $details
]
), 200)
->header('Content-Type', 'application/json');
$data = [];
return $resData;
}
}
Second in any controller call this trait's function set_response()
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Traits\ApiResponser;
use Illuminate\Http\Request;
class ListController extends Controller
{
use ApiResponser;
public function getAllUserList(Request $request)
{
$data = User::select('id', 'name', 'email')->get();
return $this->set_response(['data' => $data], 200,'success', ['User list']);
}
}
Output will be like this
Solution 2:[2]
use the json helper function
return response()->json($body);
or
use Response;
return Response::json($body);
This will create an instance of \Illuminate\Routing\ResponseFactory
. See the phpDocs for possible parameters below:
/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response
* @static
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}
Solution 3:[3]
I needed to ->getContents()
after the ->getBody()
$body = $response->getBody()->getContents();
All good again...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Akash Kumar Verma |
Solution 3 | TheRealPapa |