Snapshot Testing API Calls The Right Way

Protecting REST API Calls ↩️ Backward

RESTful API Versioning, though a simple and elegant concept, is a LOT harder to enforce than it sounds. It’s hard to not break backward compatibility on a continually evolving API, and though API versioning is a great concept, it’s rarely followed without flaw. There’s a reason why throngs are flocking toward intermediaries like GraphQL. RESTful API idealism crashes apps.

You know it. Have you toiled for hours, looking for a bug, just to find it came in with the bum data from an API? Perhaps some seemingly dependable object left for smokes and never came home while you fustily access a property on undefined. Or perhaps there’s an array that said it would never change - promised even… but one day you call .length just to find it can’t support your needs, and it wants to hang with the number crowd now? 💔 😿

Let’s bring it in

You need something to reassure you in those moments when you’re debugging and re-evaluating your life decision to write software. When things go south, or as us southerners say, when things come from the North, it can help to quickly find out if you shouldn’t blame yourself.

Let’s add a test, so we can say confidently, “It’s not me, it’s you!”

Goals:

Tests need to help identify the contract between API/App

Writing tests should be straightforward and easy

Batched tests need to be fast and command-line driven

Snapshots need to handle known optional or changing values

You might think this is a tall order, but given a few free tools, we can add this to any project where the API is a moving target, and feel secure.

Postman, the API Calling Tool

The first inclination would be to start writing code, but as soon as we do that, we lose focus on delineating the API and start making assumptions. Instead, we’re going to document our running APIs in a clean and shareable form. This is where we can identify what is and is not expected from our API.

We’ll use a free app called Postman, which gives us the ability to fine-tune calls in a quick and savable way. You might think this goes against the goal to have a CLI, but I promise 🤞 we’ll get back to that.

Once you have Postman running, the UI is extremely simple and kind of fun.

We need to create a collection of API calls, which we can reference for all endpoints we want to test.

On the left side, there’s a button that looks like a folder icon with a plus symbol. Click and create a collection.

Describe and save our collection folder

Writing our first API Call

Let’s make a call to get some random vehicle’s information. We’ll do a GET request to this endpoint: https://swapi.co/api/vehicles/4/

Enter the URL request and hit “Send” to receive the JSON result.