Skip to main content

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

Read more here

Asserting JSON Structure

Premium
5 min read

In the Testing For Beginners course, we tested that the response is JSON. However, you might need to test the JSON structure more deeply when creating APIs. Let's see how we can do it.


Laravel Code

In this example, we have a route in routes/api.php and a CRUD Controller. However, the products list is returned using the API Resource, and not all fields are returned deliberately for this example.

routes/api.php:

use App\Http\Controllers\Api\ProductController;
 
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
 
Route::apiResource('products', ProductController::class);

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

use App\Models\Product;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProductResource;
use Illuminate\Http\Resources\Json\JsonResource;
 
class ProductController extends Controller
{
public function index(): JsonResource
{
return ProductResource::collection(Product::all());
}
 
public function show(Product $product): JsonResource
{
return ProductResource::make($product);
}
 
public function update(Request $request, Product $product): JsonResource
{
$product->update($request->all());
 
return ProductResource::make($product);
}
}

app/Http/Resources/ProductResource.php:

class ProductResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
];
}
}

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


JSON Data Anywhere & JSON Count

Using the assertJsonFragment(), you can test whether the response contains...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (31 h 16 min)

You also get:

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

Already a member? Login here

Comments & Discussion

PP
Patrik Poláček ✓ Link copied!

the code snippet in the "JSON Data Anywhere & JSON Count" section is broken (near $product1)