Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Testing APIs and JSON Data

Premium
3 min read

In this lesson, let's talk about API testing. In this case, we don't have any redirects to assert, and APIs usually work with JSON. So, we will see a couple of examples.


Laravel Code

In this example, we have a route in the route/api.php and two Controller methods to list products and store a product.

routes/api.php:

Route::get('/user', function (Request $request) {
return $request->user();
})->middleware(Authenticate::using('sanctum'));
 
Route::apiResource('products', \App\Http\Controllers\Api\ProductController::class);
php artisan make:controller Api/ProductController --resource --api --model=Product

app/Http/Controllers/Api/ProductController.php:

use App\Models\Product;
use App\Http\Requests\StoreProductRequest;
 
class ProductController extends Controller
{
public function index()
{
return Product::all();
}
 
public function store(StoreProductRequest $request)
{
return Product::create($request->validated());
}
}

If we test /api/products using any API client, we will get a list of products from the DB.

api products list


The Tests

We will continue to add tests in the same ProductsTest file. You can create a tests/Feature/Api directory, for example, and add all your API tests there.

In the first test, to get all products list, we will create...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

LA
Luis Antonio Parrado ✓ Link copied!

routes/api.php doesn't exist in Laravel 11 by default, If a user is following this course and is starting out in Laravel 11 we should instruct him to first run the command php artisan install:api.

D
Dan ✓ Link copied!

Just to follow up on Luis' comment. If you get an error when running install:api

Unable to automatically add API route definition to bootstrap file. API route file should be registered manually.

Go to your bootstrap/app.php file and add the following:

->withRouting(
        web: __DIR__ . '/../routes/web.php',
        api: __DIR__ . '/../routes/api.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
        apiPrefix: '/api',
    )