SyntaxStudy
Sign Up
PHP Testing APIs in Laravel
PHP Intermediate 4 min read

Testing APIs in Laravel

API Testing

Laravel's actingAs() and HTTP test helpers make API testing readable and fast without a real HTTP server.

Example
class PostApiTest extends TestCase {
    use RefreshDatabase;
    public function test_can_create_post(): void {
        $user = User::factory()->create();
        $this->actingAs($user, "sanctum")
            ->postJson("/api/posts", ["title" => "Test", "body" => "Content"])
            ->assertCreated()
            ->assertJsonPath("data.title", "Test");
        $this->assertDatabaseHas("posts", ["title" => "Test"]);
    }
}
Pro Tip

assertJsonPath uses dot notation: "data.user.email" navigates nested JSON without extracting manually.