Skip to content

05. API Support

Daniel Trolezi edited this page Sep 18, 2024 · 1 revision

Laravel API routes are already installed.

By default any request made to API routes (/api/*) will return a JSON response.
This has been configured in the /bootstrap/app.php file:

return Application::configure(basePath: dirname(__DIR__))
    ...
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
            if ($request->is('api/*')) {
                return true;
            }

            return $request->expectsJson();
        });
        ...
    })->create();

HTTP Exceptions

Also, all HTTP Exceptions will return the proper Status Code on the Response.
This has been configured in the /bootstrap/app.php file:

return Application::configure(basePath: dirname(__DIR__))
    ...
    ->withExceptions(function (Exceptions $exceptions) {
        ...
        $exceptions->render(function (HttpException $e, Request $request)
        {
            if($request->is('api/*')) {
                $response = [
                    'message' => $e->getMessage()
                ];
    
                if(config('app.debug')) {
                    $response = array_merge($response, [
                        'exception' => get_class($e),
                        'file'      => $e->getFile(),
                        'line'      => $e->getLine(),
                        'trace'     => $e->getTraceAsString()
                    ]);
                }

                return response()->json($response, $e->getStatusCode());
            }
        });
    })->create();