Home > Net >  Back end to Back end API request and response
Back end to Back end API request and response

Time:12-24

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?

CodePudding user response:

return response()->json(['data' => $body]);

CodePudding user response:

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);
}
  • Related