Test HTTP APIs with Guzzle — check status codes, Content-Type headers, and JSON response bodies.
HTTP Testing (with Guzzle)
// Testing a real HTTP API
composer require --dev guzzlehttp/guzzle
class ApiTest extends TestCase {
private Client $http;
protected function setUp(): void {
$this->http = new Client([
"base_uri" => "http://localhost:8080",
"http_errors" => false,
]);
}
public function testGetUsersReturnsJson(): void {
$res = $this->http->get("/api/users");
$this->assertEquals(200, $res->getStatusCode());
$this->assertStringContainsString("application/json", $res->getHeaderLine("Content-Type"));
$body = json_decode($res->getBody()->getContents(), true);
$this->assertArrayHasKey("data", $body);
$this->assertIsArray($body["data"]);
}
public function testCreateUser(): void {
$res = $this->http->post("/api/users", [
"json" => ["name"=>"Alice","email"=>"alice@test.com","password"=>"Secret123!"]
]);
$this->assertEquals(201, $res->getStatusCode());
$body = json_decode((string)$res->getBody(), true);
$this->assertArrayHasKey("id", $body["data"]);
}
}