イントロダクションIntroduction
他のWebアプリケーションと連携を取る、送信HTTPリクエストを簡単に作成できるよう、Laravelは小さくて読み書きしやすいGuzzle HTTPクライアントのAPIを提供しています。LaravelのGuzzleラッパーはもっとも繁用されるユースケースと開発者が素晴らしい体験をできることに重点を置いています。Laravel provides an expressive, minimal API around the Guzzle HTTP client[http://docs.guzzlephp.org/en/stable/], 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.
取り掛かる前に、アプリケーションの依存パッケージとしてGuzzleパッケージをインストールする必要があります。Laravelはデフォルトとしてこの依存パッケージを含んでいます。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:
composer require guzzlehttp/guzzle
リクエスト作成Making Requests
リクエストを作成するには、get
、post
、put
、patch
、delete
メソッドを使用します。最初に基本となるGET
リクエストをどのように作成するのか見てみましょう。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:
use Illuminate\Support\Facades\Http;
$response = Http::get('http://test.com');
get
メソッドはIlluminate\Http\Client\Response
のインスタンスを返します。これはレスポンスを調べるために使用できるさまざまなメソッドを持っています。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:
$response->body() : string;
$response->json() : array|mixed;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;
Illuminate\Http\Client\Response
オブジェクトは、レスポンス上のJSONレスポンスデータへ直接アクセスできるように、PHPのArrayAccess
インターフェイスも実装しています。The
Illuminate\Http\Client\Response
object
also implements the PHP ArrayAccess
interface, allowing you to access JSON response data
directly on the response:
return Http::get('http://test.com/users/1')['name'];
リクエストデータRequest Data
もちろん、POST
、PUT
、PATCH
を使用する場合は、リクエストと追加のデータを一緒に送るのが一般的です。そのため、これらのメソッドは第2引数にデータの配列を受け取ります。データはデフォルトでapplication/json
コンテンツタイプを使用して送信されます。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:
$response = Http::post('http://test.com/users', [
'name' => 'Steve',
'role' => 'Network Administrator',
]);
GETリクエストのクエリパラメータGET Request Query Parameters
GET
リクエストの作成時はクエリ文字列をURLに直接追加するか、キー/値ペアの配列を第2引数としてget
メソッドに渡します。When making GET
requests, you may either append a query string to
the URL directly or pass an array of key / value
pairs as the second argument to the get
method:
$response = Http::get('http://test.com/users', [
'name' => 'Taylor',
'page' => 1,
]);
URLエンコードされたリクエストのフォーム送信Sending Form URL Encoded Requests
application/x-www-form-urlencoded
コンテンツタイプを使用してデータを送信したい場合は、リクエストを作成する前にasForm
メソッドを呼び出す必要があります。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:
$response = Http::asForm()->post('http://test.com/users', [
'name' => 'Sara',
'role' => 'Privacy Consultant',
]);
リクエスト本体をそのまま送信するSending A Raw Request Body
リクエスト作成時に、リクエストの本体をそのまま指定したい場合は、withBody
メソッドを使います。You may use the
withBody
method if you would like to
provide a raw request body when making a
request:
$response = Http::withBody(
base64_encode($photo), 'image/jpeg'
)->post('http://test.com/photo');
マルチパートリクエストMulti-Part Requests
ファイルをマルチパートリクエストとして送信したい場合は、リクエストを作成する前にattach
メソッドを呼び出す必要があります。このメソッドはファイル名と、その内容を引数に受け取ります。オプションとして第3引数に、ファイルのファイル名と想定できる文字列を指定できます。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:
$response = Http::attach(
'attachment', file_get_contents('photo.jpg'), 'photo.jpg'
)->post('http://test.com/attachments');
ファイルのコンテンツ内容をそのまま渡す代わりに、ストリームリソースも指定できます。Instead of passing the raw contents of a file, you may also pass a stream resource:
$photo = fopen('photo.jpg', 'r');
$response = Http::attach(
'attachment', $photo, 'photo.jpg'
)->post('http://test.com/attachments');
ヘッダHeaders
withHeaders
メソッドで、リクエストにヘッダを追加できます。このwithHeaders
メソッドは、キー/値ペアの配列を引数に取ります。Headers may be added to requests
using the withHeaders
method. This
withHeaders
method accepts an array of
key / value pairs:
$response = Http::withHeaders([
'X-First' => 'foo',
'X-Second' => 'bar'
])->post('http://test.com/users', [
'name' => 'Taylor',
]);
認証Authentication
withBasicAuth
とwithDigestAuth
メソッドを使うと、Basic認証やDigest認証に使用する認証データを指定できます。You may specify basic and digest
authentication credentials using the
withBasicAuth
and
withDigestAuth
methods,
respectively:
// Basic認証
$response = Http::withBasicAuth('taylor@laravel.com', 'secret')->post(...);
// Digest認証
$response = Http::withDigestAuth('taylor@laravel.com', 'secret')->post(...);
BearerトークンBearer Tokens
手早くAuthorization
bearerトークンをリクエストのヘッダに追加したい場合は、withToken
メソッドを使います。If you would like to quickly add
an Authorization
bearer token header to
the request, you may use the withToken
method:
$response = Http::withToken('token')->post(...);
タイムアウトTimeout
timeout
メソッドはレスポンスを待つ最大秒数を指定するために使用します。The timeout
method
may be used to specify the maximum number of seconds
to wait for a response:
$response = Http::timeout(3)->get(...);
指定したタイムアウト時間が過ぎたら、`Illuminate\Http\Client\ConnectionExceptionのインスタンスが投げられます。If the given timeout is exceeded,
an instance of
Illuminate\Http\Client\ConnectionException
will be thrown.
リトライRetries
クライアントかサーバでエラーが発生したときに、HTTPクライアントへそのリクエストを自動的に再試行させたい場合は、retry
メソッドを使います。retry
メソッドは2つの引数を取ります。試行回数と、次に試みるまでLaravelに待たせるミリ秒です。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:
$response = Http::retry(3, 100)->post(...);
リクエストに全部失敗したら、Illuminate\Http\Client\RequestException
のインスタンスが投げられます。If all of the requests fail, an
instance of
Illuminate\Http\Client\RequestException
will be thrown.
エラー処理Error Handling
Guzzleのデフォルト動作と異なり、LaravelのHTTPクライアントラッパーはクライアントの例外を投げたり、サーバからの400
と500
レベルのレスポンスとしてエラーレスポンスを返したりしません。こうしたエラーが発生したかはsuccessful
、clientError
、serverError
メソッドで判定できます。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:
// ステータスコードが200以上、300より小さいレスポンスであったかを判定
$response->successful();
// ステータスコードが400より大きいかを判定
$response->failed();
// ステータスコードが400レベルのレスポンスであったかを判定
$response->clientError();
// ステータスコードが500レベルのレスポンスであったかを判定
$response->serverError();
例外を投げるThrowing Exceptions
レスポンスインスタンスを受け取り、そのレスポンスがクライアントかサーバエラーであった場合に、Illuminate\Http\Client\RequestException
のインスタンスを投げる場合は、throw
メソッドを使います。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:
$response = Http::post(...);
// クライアントかサーバエラーが発生したため例外を投げる
$response->throw();
return $response['user']['id'];
Illuminate\Http\Client\RequestException
インスタンスはパブリックの$response
プロパティを持ち、返されたレスポンスを調査できるようになっています。The
Illuminate\Http\Client\RequestException
instance has a public $response
property which will allow you to inspect the
returned response.
throw
メソッドはエラーが起きていない場合にレスポンスインスタンスを返すため、別の操作を続けて記述できます。The throw
method
returns the response instance if no error occurred,
allowing you to chain other operations onto the
throw
method:
return Http::post(...)->throw()->json();
GuzzleオプションGuzzle Options
withOptions
メソッドを使用し、Guzzleリクエストオプションを追加指定できます。withOptions
メソッドはキー/値ペアの配列を引数に取ります。You may specify additional
Guzzle request
options[http://docs.guzzlephp.org/en/stable/request-options.html]
using the withOptions
method. The
withOptions
method accepts an array of
key / value pairs:
$response = Http::withOptions([
'debug' => true,
])->get('http://test.com/users');
テストTesting
多くのLaravelサービスは簡単に記述的なテストが書ける機能を提供していますが、HTTPラッパーも例外ではありません。Http
ファサードのfake
メソッドで、リクエストが作成されるときに、スタブ/ダミーのレスポンスを返すようにHTTPクライアントに支持できます。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.
レスポンスのFakeFaking Responses
たとえば、すべてのリクエストに200
ステータスコードを持つ空のレスポンスをHTTPクライアントから返したい場合は、fake
メソッドを引数なしで呼びます。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:
use Illuminate\Support\Facades\Http;
Http::fake();
$response = Http::post(...);
特定URLのFakeFaking Specific URLs
fake
メソッドに配列を渡すこともできます。配列のキーはfakeするURLパターンを表し、値はレスポンスです。*
文字はワイルドカードとして使えます。FakeしないURLに対するリクエストは、実際に実行されます。エンドポイントに対するスタブ/fakeを組み立てるために、response
メソッドを使います。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:
Http::fake([
// GitHubエンドポイントに対するJSONレスポンスをスタブ
'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
// Googleエンドポイントに対する文字列レスポンスをスタブ
'google.com/*' => Http::response('Hello World', 200, ['Headers']),
]);
一致しないURLをすべてスタブするフォールバックURLパターンを指定する場合は、*
文字だけを使います。If you would like to specify a
fallback URL pattern that will stub all unmatched
URLs, you may use a single *
character:
Http::fake([
// GitHubエンドポイントに対するJSONレスポンスをスタブ
'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
// その他すべてのエンドポイントに対して文字列レスポンスをスタブ
'*' => Http::response('Hello World', 200, ['Headers']),
]);
一連のレスポンスのFakeFaking Response Sequences
特定の順番で一連のfakeレスポンスを一つのURLに対して指定する必要がある場合もときどきあります。このレスポンスを組み立てるには、Http::sequence
メソッドを使用します。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:
Http::fake([
// GitHubエンドポイントに対して一連のレスポンスをスタブ
'github.com/*' => Http::sequence()
->push('Hello World', 200)
->push(['foo' => 'bar'], 200)
->pushStatus(404),
]);
一連のレスポンスを全部返し終えると、そのエンドポイントに対する以降のリクエストには例外が投げられます。このとき例外を発生させる代わりに特定のレスポンスを返すように指定したい場合は、whenEmpty
メソッドを使用します。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:
Http::fake([
// GitHubエンドポイントに対して一連のレスポンスをスタブ
'github.com/*' => Http::sequence()
->push('Hello World', 200)
->push(['foo' => 'bar'], 200)
->whenEmpty(Http::response()),
]);
順番のあるレスポンスをfakeしたいが、fakeする特定のURLパターンを指定する必要がなければ、Http::fakeSequence
メソッドを使います。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:
Http::fakeSequence()
->push('Hello World', 200)
->whenEmpty(Http::response());
コールバックのFakeFake Callback
特定のエンドポイントでどんなレスポンスを返すか決めるために、より複雑なロジックが必要な場合は、fake
メソッドへコールバックを渡してください。このコールバックはIlluminate\Http\Client\Request
のインスタンスを受け取るので、レスポンスインスタンスを返してください。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:
Http::fake(function ($request) {
return Http::response('Hello World', 200);
});
レスポンスの調査Inspecting Requests
レスポンスをfakeしているとまれに、自分のアプリケーションが正しいデータやヘッダを送っていることを確認するため、クライアントが受け取るリクエストを調べたくなります。これを行うには、Http::fake
を呼び出したあとにHttp::assertSent
メソッドを呼び出します。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
.
assertSent
メソッドはIlluminate\Http\Client\Request
インスタンスを受け取るコールバックを引数に取り、そのリクエストが期待通りであったかを示す論理値をそのコールバックから返します。テストにパスするには、指定した期待に合致する最低一つのリクエストが発送されている必要があります。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:
Http::fake();
Http::withHeaders([
'X-First' => 'foo',
])->post('http://test.com/users', [
'name' => 'Taylor',
'role' => 'Developer',
]);
Http::assertSent(function ($request) {
return $request->hasHeader('X-First', 'foo') &&
$request->url() == 'http://test.com/users' &&
$request['name'] == 'Taylor' &&
$request['role'] == 'Developer';
});
必要であればassertNotSent
メソッドを用い、指定するリクエストが送信されなかった事をアサートすることもできます。If needed, you may assert that a
specific request was not sent using the
assertNotSent
method:
Http::fake();
Http::post('http://test.com/users', [
'name' => 'Taylor',
'role' => 'Developer',
]);
Http::assertNotSent(function (Request $request) {
return $request->url() === 'http://test.com/posts';
});
もしくは、リクエストがまったく送信されないことをアサートしたい場合には、assertNothingSent
メソッドを使用してください。Or, if you would like to assert
that no requests were sent, you may use the
assertNothingSent
method:
Http::fake();
Http::assertNothingSent();