0

I have 2 projects made with Laravel 5.4:

  1. Prj-1 it is an Restful API that returns JSON.
  2. Prj-2 it is an website that consumes the above endpoints.

In this way, I have the follow endpoint from Prj-1 : myAPI.com/city that returns a list of all cities in the database in a JSON format.

Inside Prj-2 I have the follow:

Route:
Route::get('/showCityAPItest','AddressController@getcity'); 

Controller:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
...
public function getcity()
    {


        $request =Request::create('http://myAPI.com/city', 'GET');
        $response = Route::dispatch($request);
        dd($response);
    }

If I use directly the URL (http://myAPI.com/city) in the browser, it works. I can see the JSON as expected. BUt when I try to retrieve it from the Prj-2 I can't see it in the browser.

Actually I see

404 Not Found
nginx/1.10.1 (Ubuntu)

I was following this post but I dont know what am I doing wrong.

Any help?

2 Answers 2

1

Yeah, @Joel Hinz is right. Request will work within same project api end. You need to use GuzzleHttp. Step 1. Install guzzle using composer. Windows base operating guzzle command for composer :

composer require guzzlehttp/guzzle

step 2 write following code

public function getcity()
    {     
       $client = new \GuzzleHttp\Client;
       $data =$client->request('GET', 'http://myAPI.com/city', [
       'headers' => [
           'Accept'     => 'application/json',
           'Content-type' => 'application/json'
       ]
       ]);

       $x = json_decode($data->getBody()->getContents());
       return response()->json(['msg' => $x], 200);
} 
Sign up to request clarification or add additional context in comments.

Comments

1

The answer to which you are referring is talking about internal routes. You can't use the Request and Route facades for external addresses like that. Instead, use e.g. Guzzle (http://docs.guzzlephp.org/en/latest/) to send your requests from the second site.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.