Test a Laravel API with HTTP Tests
Test Laravel 13 JSON endpoints, validation, authentication and database changes.
Test Laravel 13 JSON endpoints, validation, authentication and database changes. This tutorial focuses on a small implementation you can run, inspect and extend instead of hiding the important behavior behind scaffolding.
Prerequisites#
- Laravel 13, PHP, Composer and a configured test database
- Use placeholder credentials and a non-production environment.
- Know the basic syntax of Laravel.
What we will build#
We will implement the core path, exercise it with a realistic request or test, and identify the production concerns that should remain outside a minimal example.
Step 1: Prepare the project#
Create a focused branch and confirm the current application or sample database works before changing it. Keep secrets in environment variables, commit an example environment file without values, and make the smallest schema change that supports the use case.
Step 2: Implement the core behavior#
public function test_user_can_create_a_post(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)
->postJson('/api/posts', [
'title' => 'Testing Laravel APIs',
'body' => 'A complete example body.',
]);
$response->assertCreated()
->assertJsonPath('data.title', 'Testing Laravel APIs');
$this->assertDatabaseHas('posts', [
'title' => 'Testing Laravel APIs',
'user_id' => $user->id,
]);
}Keep validation at the boundary. Allow-list client-controlled fields, return an explicit response, and avoid exposing internal exceptions or credentials.
Step 3: Test the successful path#
php artisan test --filter=PostApiTestConfirm both the response and the resulting state. A status code alone is not enough when the operation changes a database, dispatches work or writes a file.
Step 4: Test failures#
Repeat the test with missing fields, invalid types, unauthorized access and a dependency failure. The application should reject the request predictably without leaking a stack trace, secret or filesystem path.
Common problems#
- Inputs are trusted too early: validate and normalize at the system boundary.
- The example works only once: test repeated and concurrent requests where the operation changes state.
- Errors are inconsistent: use one documented error shape and attach a request identifier in production.
Best practices#
- Use the current supported runtime and pin important dependencies.
- Keep examples minimal, but preserve authentication, validation and error handling.
- Add automated coverage for the behavior most likely to regress.
- Log identifiers and outcomes, never passwords, tokens or complete sensitive payloads.
Conclusion#
You now have a working foundation for test a laravel api with http tests. Extend it by separating infrastructure from business rules, adding authorization where resources belong to users, and measuring the behavior under realistic data and failure conditions.