While HTTP APIs are ubiquitous these days, testing and documenting such APIs remains somewhat awkward: Tests usually consist of procedural code that is specific to the respective language or even framework - which is neither very expressive nor easy to maintain.
gabbi promises relief by providing a
language-agnostic, nicely readable and lightweight format for testing - and
thus describing - HTTP APIs. Originally created as part of an effort to
improve OpenStack’s APIs, it has since
grown into a useful tool for anyone working with HTTP.
gabbi tests are simply YAML files that
describe HTTP requests and responses. We’ll be using the wonderful
httpbin for illustration purposes:
method and status are optional, but it’s nice to be explicit. In fact,
gabbi itself states that the name is “derived from ‘gabby’: excessively
talkative” - i.e. gabbi prefers direct visibility and readability.
Of course we need to install gabbi in order to run these tests:
Using a virtual environment can help avoid sudo privileges or polluting our global packages directory.
Once that’s done, we can feed our YAML tests to gabbi:
Oops - I wasn’t connected to the internet. Of course we’d typically test a local
development server instead, but that’s not important right now. Let’s try this
We don’t want to hard-code the target host, so let’s use paths instead
of fully qualified URLs:
(Note that I added some vertical whitespace to separate request and response -
that’s still valid YAML, of course.)
That all seems pretty straightforward so far. Let’s ensure that the Allow
header did in fact tell us the truth:
As predicted, httpbin responded with
405 Method Not Allowed - clearly we’ll need to send
our precious data to a different route:
Ah, there we go. Note that it’s our responsibility to encode the data
there - that’s a little easier if we use JSON:
In fact, httpbin responds with JSON, returning in the response whatever data we
submit in our request. We can use
JSONPath to query that response data:
It’s also possible to use data from the preceding response in a new request:
Here we’re just using the Location header, but this technique also enables us
to go full HATEOAS and test hypermedia
Obviously coercing httpbin into providing hypermedia responses is a bit of a
hack, so we’ll stop here. Hopefully this is sufficient to get started - in a
future post, we might expand on this with a more realistic example. We might
also delve into gabbi’s extensibility, e.g. creating a custom response handler
to query HTML responses with CSS selectors.