Testing Your Python API App with JSON Schema

Paul Götze
Grammofy
Published in
3 min readMay 31, 2017

--

When writing JSON APIs you always want to make sure your endpoints deliver the data they are supposed to deliver. A good way to ensure your code acts the way it should is writing some tests. A really nice way to test JSON APIs is verifying the request’s JSON response against a JSON Schema.

If you are not familiar with JSON Schema yet, you can find the specification and more detailed information on the official web site and lots of nice explanatory examples here.

I’ve used JSON Schema before to test JSON APIs written in Ruby. Back then I used an approach similar to the one described in this Thoughtbot blog post. Now that I needed to test a JSON API written in Python I was wondering how to test JSON responses with JSON Schema using pytest. It turned out to be fairly easy to get your endpoint tests up and running, so here is what I did.

Creating an Assertion Helper

Let’s suppose we have a simple JSON response for a user endpoint GET /users/:id:

Here is an example how you would naively test this response by checking the presence of the properties (client would be a pytest fixture, e.g. a test_client of your Flask app):

--

--

Paul Götze
Grammofy

Authoring code. Drawing stuff. Comics addict and fan of bad jokes. Creator of adoptoposs.org & zarenwitze.de.