Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

saadaan's avatar

Decoupling 2 APIs in one controller function

Hi,

i have a controller method which receives message from API, puts it in database, and then tries to use another API to send a reply message. This all happens in one function.

Now, the 2nd API which sends message, is giving error. Because of this, the first API which sends the data to me, is getting error 500 internal server from my side (because 2nd API is failing).

I need to separate out both APIs, so that I could at least send HTTP 200 to the first API, so that it could close connection. How can I do that from one function?

Thanks,

0 likes
4 replies
Glukinho's avatar

The simpliest is to use defer() function: https://laravel.com/docs/12.x/helpers#deferred-functions

Anything inside defer() will be executed only after a response is sent to the current request. So, API #1 will see 200 OK from you and only after that API #2 will be called.

// routes/api.php
Route::post('/from-first-api', [ FirstApiController::class, 'handle' ]);


// app/Http/Controllers/FirstApiController.php
class FirstApiController extends Controller
{
    public function handle(Request $request)
    {
        // ...put what you need to DB

        defer(function() {
            (new SecondAPI)->send(/* ...some data... */);
        });

        return response('ok', 200);
    }
}

Other way is to put API #2 calling to a separate job and call it from controller with CallSecondAPIJob::dispatchAfterResponse();

It will give the same behavior but separated to different classes which may be preferable.

martinbean's avatar

@saadaan Could you not instead accept the initial message, put it on a queue and return a 2xx response to the initial request?

Your application will then have that initial message in a queue that it can process in its own time, and send the required response to the second API.

saadaan's avatar

@martinbean how would I invoke the second function after closing the first function? Some cron etc?

Please or to participate in this conversation.