Testing JSON:API Endpoints with PestPHP

Published on by

Testing JSON:API Endpoints with PestPHP image

JSON:API provides many options for filtering, sorting, and including extra data into the requested data using query parameters. Testing this can be frustrating - but in this tutorial, I will walk through how I approach testing these endpoints.

Let's take an example of an endpoint where we want to get a list of Projects, which has the following data model:

Project:
attributes:
id: string
name: string
description: text
status: string (Enum: planning, in-progress, in-testing, done)
active: boolean
relationships:
owner: BelongsTo (User)
client: BelongsTo (Client)

I won't show the code for the controller, as that is somewhat subjective. However, we should return a JSON:API Resource inside a JSON Response. Let's have a quick look at the query, which will be based on my previous tutorial on Effective Eloquent.

final class FetchProjectsByUser
{
public function handle(Builder $builder, string $user): Builder
{
return QueryBuilder::for(
subject: $builder,
)->allowedIncludes(
includes: ['owner', 'client'],
)->allowedFilters(
filters: ['status', 'active'],
)->where(
'user_id',
$user,
)->getEloquentBuilder();
}
}

From here, we can start testing the endpoint to ensure all options are available. We want to get all projects, all that are or aren't active, of various statuses, and we want to ensure that we can include both the owner and client information should it be requested. But how about the unhappy path tests?

My first test when working with endpoints like this is ensuring unauthenticated users cannot access it. These tests assume that the controller we want to use is called IndexController.

it('returns the correct status code if unauthenticated', function (): void {
getJson(
uri: action(IndexController::class),
)->assertStatus(
status: Http::UNAUTHORIZED->value,
);
});

This test is a must-add, ensuring that you can access the endpoint or not access the endpoint based on whether you are logged in or not. We can then test to ensure we get the correct status code if logged in.

it('returns the correct status code for users', function (): void {
actingAs(User::factory()->create())->getJson(
uri: action(IndexController::class),
)->assertStatus(
status: Http::OK->value,
);
});

These more straightforward tests are often overlooked and should be added to ensure you get the simple things right. In the past, I have skipped these, assuming that things would work - only to find that I was causing an issue with some code I added that was forcing 500 errors on specific endpoints. Next, we can jump into testing more JSON:API specific features.

it('can fetch the projects client', function (): void {
actingAs(User::factory()->create())->getJson(
uri: action(IndexController::class, [
'include' => 'client',
]),
)->assertStatus(
status: Http::OK->value,
)->assertJson(fn (AssertableJson $json) => $json
->first(fn (AssertableJson $json) => $json
->has('relationships.client')
->etc()
)
);
});

We want to test that the relationship exists here, as we will not get complete information, including this relationship, just enough to know what to request for specifics. This is part of the design of JSON:API, though.

The next step is filtering the API, ensuring we can fetch specific projects based on the filterable attributes we added to our query.

it('can filter to active projects only', function (): void {
actingAs(User::factory()->create())->getJson(
uri: action(IndexController::class, [
'filter[active]' => true,
]),
)->assertStatus(
status: Http::OK->value,
)->assertJson(fn (AssertableJson $json) => $json
->each(fn (AssertableJson $json) => $json
->where('attributes.active', true)
->etc()
)
);
});

We can apply this approach to any filters we might use for our endpoints, allowing anyone working with our API to get precisely the data they need.

How do you go about testing your API endpoints? This is a simple guide to test JSON:API endpoints in Laravel using pestPHP. The principles can be applied to any other tests you may need to do within your API.

Steve McDougall photo

Technical writer at Laravel News, Developer Advocate at Treblle. API specialist, veteran PHP/Laravel engineer. YouTube livestreamer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Customizing Data Transformations with Laravel Casts image

Customizing Data Transformations with Laravel Casts

Read article
Automated API documentation of Laravel API resources image

Automated API documentation of Laravel API resources

Read article
Using withoutWrapping to flatten API responses image

Using withoutWrapping to flatten API responses

Read article
Customize the Truncation of HTTP Client Request Exceptions image

Customize the Truncation of HTTP Client Request Exceptions

Read article
Laravel VS Code Extension Public Beta image

Laravel VS Code Extension Public Beta

Read article
Wirechat - Laravel Livewire chat package image

Wirechat - Laravel Livewire chat package

Read article