28

I build an API on laravel 4, and it returns json results. For the API, I created one folder. Now i created another external project for the web application and what I want is to access the API functions from the laravel app controller. To be more clear, how can i make external API request from laravel controller?

1

1 Answer 1

58

You can use Guzzle:

Install it:

composer require guzzle/guzzle ~3.0

Create a client setting the base URL:

$client = new \Guzzle\Service\Client('http://api.github.com/users/');

Get your response:

$response = $client->get("users/$username")->send();

And display it:

dd($response);

But if you are trying to follow the MVC pattern, you should not do this directly in your controller, so create a service class, you call from your controller or your repositories, to do this work for you.

Sign up to request clarification or add additional context in comments.

4 Comments

Edited because Guzzle just launched version 4 and this is a version 3 answer.
Its version 5 now, no longer requires cURL in order to send HTTP requests. Guzzle will use the PHP stream wrapper to send HTTP requests if cURL is not installed. Alternatively, you can provide your own HTTP handler used to send requests.
isn't guzzle already included into Laravel? (I have seen when run composer update)
Composer tells me that Package guzzle/guzzle is abandoned, you should avoid using it. Use guzzlehttp/guzzle instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.