Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

Test your OpenAPI implementation with Spectator

Published on by

Test your OpenAPI implementation with Spectator image

For anyone who has built or maintained an API you know how much dedication it takes to keep your documentation complete, easy-to-read, and, most importantly, accurate. It’s common for developers to experience discrepancies between their API documentation and the actual implementation of that API in the code, especially for endpoints with request parameters or varying response codes. These discrepancies can cause issues on your development team because the developers working on your API could inadvertently change a response or payload which can break a downstream client application.

Enter Spectator. Spectator is a package that provides testing methods you can use within your existing Laravel PHPUnit test suites to ensure your OpenAPI Specification documentation and implementation stay in sync.

Here’s an example of how it works…

Let’s say you have a Users.v1.json spec for fetching users, something simple like the following:

This spec defines both the GET and POST methods for the /users URI, with the User resource being represented with just ID, email, and user attributes. Based on that, a controller has been written to serve up a list of users at GET /users, and have the ability to create a new user at POST /users.

In Laravel apps, the functionality of these endpoints are (hopefully) covered with integration or “Feature” tests using the framework’s HTTP test methods. But writing tests to ensure both the request and responses to these endpoints are concretely adhering to your API spec would be very time-consuming.

Instead, you can use Spectator to automatically run tests that will compare both requests and responses with the expected contract.

<?php
 
namespace Tests\Contract;
 
use Spectator\Spectator;
 
class UsersSpecTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
 
Spectator::using('Users.v1.json');
}
 
public function test_validates_valid_json_response()
{
$this->getJson('/users')
->assertValidRequest()
->assertValidResponse(200);
}
}

This test will pass: all green! The request going in and the response coming out of this endpoint matches what has been defined in the spec. Now just for fun go change a key or value being returned from your /users route and run the test again. Suddenly, it’s broken! Revert that change and instead change something in your spec for GET /users. Again, red alerts.

This is a trivial example but it demonstrates what’s possible with Spectator. Not only can you validate correct requests and responses but incorrect ones, and validate the errors that you expect.

$this->getJson('/users')
->assertValidRequest()
->assertInvalidResponse(400)
->assertValidationMessage('get-users does not match the spec: [ format: {"type":"string","format":"email"} ]');

If you or your team are currently managing an API then give Spectator a try. I think it’s a game-changer when it comes to controlling the discrepancies and breaking changes that are bound to happen between API docs and code, and will help keep both your team and your API consumers happy.

Adam Campbell photo

I'm the husband to a Southern belle, a dad of 3 and a Canadian in the US. I'm also the VP of Tech at Clair (https://getclair.com) and tinkerer on a bunch of other stuff.

Filed in:
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
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
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 →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article