27

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?

Laurence
  • 58,936
  • 21
  • 171
  • 212
Deep Dizzy
  • 293
  • 1
  • 4
  • 7
  • See this answer to another similar question asked in stackoverflow, use guzzle to call an external api http://stackoverflow.com/a/32569599/2293686 – Mohammed Safeer Sep 15 '15 at 16:04

1 Answers1

57

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.

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
  • 1
    Edited because Guzzle just launched version 4 and this is a version 3 answer. – Antonio Carlos Ribeiro Mar 31 '14 at 14:19
  • 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. – Knights Nov 08 '14 at 15:47
  • 2
    isn't guzzle already included into Laravel? (I have seen when run composer update) – naneri Jun 10 '15 at 16:53
  • 9
    Composer tells me that `Package guzzle/guzzle is abandoned, you should avoid using it. Use guzzlehttp/guzzle instead.` – chrisg86 Jul 14 '16 at 08:20