laravelrestapi-design

Laravel Api Help, Im getting a Null result when using json data from Site A using Site B Controller


Good Day everyone,

I am having issue and im trying to figure out what causes this, can you please help me. here's my code SITE A

SITE A Code

  web.php

Route::get('/eon/auth/check/login', 
    [ApiController::class, 'checkLogin']
    );
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\MemoModel;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;

class ApiController extends Controller
{
 
    public function checkLogin(Request $request){
        
        $username = 'admin';
        $token = 'xadasd12324';
        
            
            $user = User::where('username', $username)->first();


            return response()->json([
                'username' => $username,
                'token' => $token,
                'user' => $user->first_name
                // 'ok' => $ok
            ]);
    
            if($oauth_user){
               
                RateLimiter::clear($this->throttleKey($username));
                return response()->json([
                    'status_code' => 200,
                    'message' => 'Success',
                ]);
            }else{
                RateLimiter::hit($this->throttleKey($username), $seconds = 3600);              
    
                return response()->json([
                    'status_code' => 401,
                    'message' => 'Unauthorized2',
                ]);
            }
     
    }

    private function throttleKey($username)
    {
             
        return Str::lower(request('username'));
    }
    
    private function checkTooManyFailedAttempts($username)
    {
        if (! RateLimiter::tooManyAttempts($this->throttleKey($username), 50)) {
            return;
        }
   
        abort(403, 'IP address banned. Too many login attempts.');
    }
}

SITE B Code

 web.php
Route::get('/eon/oauth/', [ApiController::class, 'oAuth']);
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;

class ApiController extends Controller
{
    public function oAuth(Request $request){
        
        $username = $request->u;
        $token = $request->id;

       dd($this->checkAuthToken($token, $username));
          
    }
    private function checkAuthToken($token, $username){
        

        $result = Http::get('http://site-a.local:8080/one/auth/check/login');
        $data = json_decode($result->body(), true);
        return $data;

        
    }
   
}

SITE A Result (calling the api via browser)

enter image description here

SITE B Result

enter image description here

I am trying to display the data from SITE A and do a conditional IF ELSE based on the data I retrieved from SITE A using the SITE B Controller.

Thank you for your help.

Im not very familiar with how laravel api works or API in general, I tried guzzle but I am still getting the same error, I guess its something to do with laravel restriction or structure which I am not familiar.


Solution

  • The $result->body() will return string not JSON data.

    you should try as following.

    try {
    $url = 'http://site-a.local:8080/one/auth/check/login';
    
    // a small timeout
    $headResponse = Http::timeout(10)->head($url);
    
    // check if url has response or not
     if (!$headResponse->ok()) {
       return response()->json(['message' => 'URL is not accessible or does not exist.'], 404);
      }
    
    // get the response with time 
    $response = Http::timeout(30)->get($url);
    
    // if response is ok
    if (!$response->ok()) {
      return response()->json(['message' => 'Failed to access URL: '], 400);
     }
    
    // this contain all json data and you can access like $response['user']
    return $response;
     
    } catch (\Exception $e) {
    
      return response()->json(['message' => 'Error accessing URL: ', 'error' => $e->getMessage()], 500);
    
    }