HTTP Client

Introduction

Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laravel's wrapper around Guzzle is focused on its most common use cases and a wonderful developer experience.

Before getting started, you should ensure that you have installed the Guzzle package as a dependency of your application. By default, Laravel automatically includes this dependency:

  1. composer require guzzlehttp/guzzle

Making Requests

To make requests, you may use the get, post, put, patch, and delete methods. First, let's examine how to make a basic GET request:

  1. use Illuminate\Support\Facades\Http;
  2. $response = Http::get('http://test.com');

The get method returns an instance of Illuminate\Http\Client\Response, which provides a variety of methods that may be used to inspect the response:

  1. $response->body() : string;
  2. $response->json() : array;
  3. $response->status() : int;
  4. $response->ok() : bool;
  5. $response->successful() : bool;
  6. $response->serverError() : bool;
  7. $response->clientError() : bool;
  8. $response->header($header) : string;
  9. $response->headers() : array;

The Illuminate\Http\Client\Response object also implements the PHP ArrayAccess interface, allowing you to access JSON response data directly on the response:

  1. return Http::get('http://test.com/users/1')['name'];

Request Data

Of course, it is common when using POST, PUT, and PATCH to send additional data with your request. So, these methods accept an array of data as their second argument. By default, data will be sent using the application/json content type:

  1. $response = Http::post('http://test.com/users', [
  2. 'name' => 'Steve',
  3. 'role' => 'Network Administrator',
  4. ]);

Sending Form URL Encoded Requests

If you would like to send data using the application/x-www-form-urlencoded content type, you should call the asForm method before making your request:

  1. $response = Http::asForm()->post('http://test.com/users', [
  2. 'name' => 'Sara',
  3. 'role' => 'Privacy Consultant',
  4. ]);

Multi-Part Requests

If you would like to send files as multi-part requests, you should call the attach method before making your request. This method accepts the name of the file and its contents. Optionally, you may provide a third argument which will be considered the file's filename:

  1. $response = Http::attach(
  2. 'attachment', file_get_contents('photo.jpg'), 'photo.jpg'
  3. )->post('http://test.com/attachments');

Instead of passing the raw contents of a file, you may also pass a stream resource:

  1. $photo = fopen('photo.jpg', 'r');
  2. $response = Http::attach(
  3. 'attachment', $photo, 'photo.jpg'
  4. )->post('http://test.com/attachments');

Headers

Headers may be added to requests using the withHeaders method. This withHeaders method accepts an array of key / value pairs:

  1. $response = Http::withHeaders([
  2. 'X-First' => 'foo',
  3. 'X-Second' => 'bar'
  4. ])->post('http://test.com/users', [
  5. 'name' => 'Taylor',
  6. ]);

Authentication

You may specify basic and digest authentication credentials using the withBasicAuth and withDigestAuth methods, respectively:

  1. // Basic authentication...
  2. $response = Http::withBasicAuth('[email protected]', 'secret')->post(...);
  3. // Digest authentication...
  4. $response = Http::withDigestAuth('[email protected]', 'secret')->post(...);

Bearer Tokens

If you would like to quickly add an Authorization bearer token header to the request, you may use the withToken method:

  1. $response = Http::withToken('token')->post(...);

Retries

If you would like HTTP client to automatically retry the request if a client or server error occurs, you may use the retry method. The retry method accepts two arguments: the number of times the request should be attempted and the number of milliseconds that Laravel should wait in between attempts:

  1. $response = Http::retry(3, 100)->post(...);

If all of the requests fail, an instance of Illuminate\Http\Client\RequestException will be thrown.

Error Handling

Unlike Guzzle's default behavior, Laravel's HTTP client wrapper does not throw exceptions on client or server errors (400 and 500 level responses from servers). You may determine if one of these errors was returned using the successful, clientError, or serverError methods:

  1. // Determine if the status code was >= 200 and < 300...
  2. $response->successful();
  3. // Determine if the response has a 400 level status code...
  4. $response->clientError();
  5. // Determine if the response has a 500 level status code...
  6. $response->serverError();

Throwing Exceptions

If you have a response instance and would like to throw an instance of Illuminate\Http\Client\RequestException if the response is a client or server error, you may use the throw method:

  1. $response = Http::post(...);
  2. // Throw an exception if a client or server error occurred...
  3. $response->throw();
  4. return $response['user']['id'];

The Illuminate\Http\Client\RequestException instance has a public $response property which will allow you to inspect the returned response.

The throw method returns the response instance if no error occurred, allowing you to chain other operations onto the throw method:

  1. return Http::post(...)->throw()->json();

Testing

Many Laravel services provide functionality to help you easily and expressively write tests, and Laravel's HTTP wrapper is no exception. The Http facade's fake method allows you to instruct the HTTP client to return stubbed / dummy responses when requests are made.

Faking Responses

For example, to instruct the HTTP client to return empty, 200 status code responses for every request, you may call the fake method with no arguments:

  1. use Illuminate\Support\Facades\Http;
  2. Http::fake();
  3. $response = Http::post(...);

Faking Specific URLs

Alternatively, you may pass an array to the fake method. The array's keys should represent URL patterns that you wish to fake and their associated responses. The * character may be used as a wildcard character. Any requests made to URLs that have not been faked will actually be executed. You may use the response method to construct stub / fake responses for these endpoints:

  1. Http::fake([
  2. // Stub a JSON response for GitHub endpoints...
  3. 'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
  4. // Stub a string response for Google endpoints...
  5. 'google.com/*' => Http::response('Hello World', 200, ['Headers']),
  6. ]);

If you would like to specify a fallback URL pattern that will stub all unmatched URLs, you may use a single * character:

  1. Http::fake([
  2. // Stub a JSON response for GitHub endpoints...
  3. 'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
  4. // Stub a string response for all other endpoints...
  5. '*' => Http::response('Hello World', 200, ['Headers']),
  6. ]);

Faking Response Sequences

Sometimes you may need to specify that a single URL should return a series of fake responses in a specific order. You may accomplish this using the Http::sequence method to build the responses:

  1. Http::fake([
  2. // Stub a series of responses for GitHub endpoints...
  3. 'github.com/*' => Http::sequence()
  4. ->push('Hello World', 200)
  5. ->push(['foo' => 'bar'], 200)
  6. ->pushStatus(404),
  7. ]);

When all of the responses in a response sequence have been consumed, any further requests will cause the response sequence to throw an exception. If you would like to specify a default response that should be returned when a sequence is empty, you may use the whenEmpty method:

  1. Http::fake([
  2. // Stub a series of responses for GitHub endpoints...
  3. 'github.com/*' => Http::sequence()
  4. ->push('Hello World', 200)
  5. ->push(['foo' => 'bar'], 200)
  6. ->whenEmpty(Http::response()),
  7. ]);

If you would like to fake a sequence of responses but do not need to specify a specific URL pattern that should be faked, you may use the Http::fakeSequence method:

  1. Http::fakeSequence()
  2. ->push('Hello World', 200)
  3. ->whenEmpty(Http::response());

Fake Callback

If you require more complicated logic to determine what responses to return for certain endpoints, you may pass a callback to the fake method. This callback will receive an instance of Illuminate\Http\Client\Request and should return a response instance:

  1. Http::fake(function ($request) {
  2. return Http::response('Hello World', 200);
  3. });

Inspecting Requests

When faking responses, you may occasionally wish to inspect the requests the client receives in order to make sure your application is sending the correct data or headers. You may accomplish this by calling the Http::assertSent method after calling Http::fake.

The assertSent method accepts a callback which will be given an Illuminate\Http\Client\Request instance and should return a boolean value indicating if the request matches your expectations. In order for the test to pass, at least one request must have been issued matching the given expectations:

  1. Http::fake();
  2. Http::withHeaders([
  3. 'X-First' => 'foo',
  4. ])->post('http://test.com/users', [
  5. 'name' => 'Taylor',
  6. 'role' => 'Developer',
  7. ]);
  8. Http::assertSent(function ($request) {
  9. return $request->hasHeader('X-First', 'foo') &&
  10. $request->url() == 'http://test.com/users' &&
  11. $request['name'] == 'Taylor' &&
  12. $request['role'] == 'Developer';
  13. });