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?
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.