How to call an API endpoint in Slim Framework v3 from within a route?

628 views Asked by At

I'm using the PHP Slim Framework v3 to make a web app and the routes I have are all typically divided into either a frontend route or an API endpoint. I have a frontend route where I want to call an API endpoint to get data to display. For example:

Frontend Route

$app->get('/order/{order-id}', function(Request $request, Response $response, array $args) {
    $order_id = intval($args['order-id']);
    $order_details = ______; // API endpoint call to get the order details

    $response = $this->view->render($response, 'order-details.html', [
        'order_details' => $order_details
    ]);

    return $response;
});

API Endpoint

$app->get('/api/order/{order-id}', function(Request $request, Response $response, array $args) use ($db) {
    $order_id = intval($args['order-id']);
    $order_details = $db->order_details($order_id); // Query the database for all the order details

    $response = $response->withJson($order_details);
    return $response;
});

What can I put in place of the ______ so I can grab the JSON being returned by the /api/order/{order-id} call?


Please note that I'm considering using Guzzle to do this, but I feel like that's such an overkill for what I'm trying to do here. I would like to think that Slim already has a way for me to do what I'm attempting to achieve.

1

There are 1 answers

0
dokgu On

From trying a few solutions out, I was able to use subRequest() for this:

$app->get('/order/{order-id}', function(Request $request, Response $response, array $args) use ($app) {
    $order_id = intval($args['order-id']);
    $order_details = $app->subRequest('GET', '/api/order/' . $order_id)->getBody(); // API endpoint call to get the order details
    $order_details = json_decode($order_details);

    $response = $this->view->render($response, 'order-details.html', [
        'order_details' => $order_details
    ]);

    return $response;
});

Seems to work for me, but this may not be the best solution as I am still just learning how to use Slim. Other better answers are welcome!