Writing and testing API specifications with API Blueprint, Dredd and Apiary

By Jeff

Photo by Jantine Doornbos on Unsplash

In this article, we are going to learn how to create API’s specifications using API Blueprint, running automated tests against the back-end implementation using Dredd, and how to use Apiary to build an API prototype without even writing a single line of code.

I really got inspired to learn about this topics after hearing the last http://twentypercent.fm podcast about API’s. Thanks to Daniel Couldbourne and Caleb Porzio for their amazing work.

Commonly, when we develop web applications, we do it based on a defined visual design that tells us the story of what the client expects the site to look like in the end.

At the same time having a visual of the product gives the client this confidence about how good the end product is going to be.

What happens when we develop API’s?

Probably the client, send us the same design, so we have to figure it out how to translate that visual design into a bright, friendly and useful API specification, an API that can be used by other developers (web, mobile, etc.) to build a user interface to interact with the product.

So, at the end we probably end up building step by step every endpoint of the API, without thinking in the next one, then we can go back, fix something and repeat the process.

The problem with this approach is that when we build API’s we have a higher responsibility because this part of the project is going to be the heart of the business.
So, it needs to be consistent, and we have to respect the “contract” (the specification), because every change we made on any endpoint, could mean more work on every front-end implementation of our API.

https://apiblueprint.org/

API Blueprint is a “Hight level API description language for web API’s” and allows us to design our API using a simple syntax.

This is how a simple API specification looks like:

FORMAT: 1A
HOST: http://127.0.0.1:8000
# Basic ACME Blog API
Welcome to the **ACME Blog** API. This API provides access to the **ACME Blog** service.
# Group Blog Posts
## Posts [GET /api/post]
+ Response 200 (application/json)

+ Body
            [
{
"id": 1,
"title": "foo title",
"body": "bar body",
"author": 1
}
]

But is this not just a plain doc?

At the moment, yes, but let’s see how we can use other tools to add more value to our developing process.

https://github.com/apiaryio/dredd
Dredd is a language-agnostic command-line tool for validating API description document against backend implementation of the API.

Yes, you are reading fine. Blueprint not only allows you to write the documentation/specification of your API but also it works as set of tests that could be executed by other tools like “dredd” to check if every endpoint is working as it should be.

The first thing you need to do is install dredd using node:

// Globally install
npm install -g dredd
// Local install
npm install — save-dev dredd

Now we can start creating our API specification by creating an API-description.apib file in the root of the project (apib stands for API blueprint file).

FORMAT: 1A
HOST: http://127.0.0.1:8000
# Basic ACME Blog API
Welcome to the **ACME Blog** API. This API provides access to the **ACME Blog** service.
# Group Blog Posts
## Posts [GET /api/post]
+ Response 200 (application/json)

+ Body
            [
{
"id": 1,
"title": "foo title",
"body": "bar body",
"author": 1
}
]
# Group Authors
Resources in this groups are related to **ACME Blog** authors.
## Authors [GET /api/author]
+ Response 200 (application/json)

+ Body
            [
{
"id": 1,
"name": "jhon",
"email": "jhon@mail.com"
}
]

Let’s create a dredd config file from the command line by running dredd init.

$ dredd init
? Location of the API description document api-description.apib
? Command to start API backend server e.g. (bundle exec rails server)
? URL of tested API endpoint http://127.0.0.1:8000
? Programming language of hooks php
? Do you want to use Apiary test inspector? No
? Dredd is best served with Continuous Integration. Create CircleCI config for Dredd? No
Configuration saved to dredd.yml
Install hooks handler and run Dredd test with:
$ composer require ddelnano/dredd-hooks-phpdev
$ dredd

At the end, we should have a dredd.yml file similar to this one:

dry-run: null
hookfiles: null
language: php
sandbox: false
server: null
server-wait: 3
init: false
custom: {}
names: false
only: []
reporter: []
output: []
header: []
sorted: false
user: null
inline-errors: false
details: false
method: []
color: true
level: info
timestamp: false
silent: false
path: []
hooks-worker-timeout: 5000
hooks-worker-connect-timeout: 1500
hooks-worker-connect-retry: 500
hooks-worker-after-connect-wait: 100
hooks-worker-term-timeout: 5000
hooks-worker-term-retry: 500
hooks-worker-handler-host: 127.0.0.1
hooks-worker-handler-port: 61321
config: ./dredd.yml
blueprint: api-description.apib
endpoint: 'http://127.0.0.1:8000'

Remember, the advantage of using dredd and API Blueprint is that you can use your documentation as a set of tests to check the back-end implementation of your API.

Something fundamental here: you are testing your API specifications, these are high-level tests that don’t even care which programming language you are using to write your API.

To run the tests just type dredd on the command line and hit enter:


complete: 0 passing, 2 failing, 0 errors, 0 skipped, 2 total
complete: Tests took 96ms

Of course, we are receiving a failure because we haven’t written the code of the API yet. In this case, I’m using Laravel so, let’s create a quick implementation just by editing the api.php routes file.

Route::get('post', function () {
    return response()->json([
        [
            "id" => 1,
            "title" => "foo title",
            "body" => "bar body",
            "author" => 1
        ]
    ]);
});
Route::get('author', function () {
    return response()->json([
        [
            "id" => 1,
            "name" => "jhon",
            "email" => "jhon@mail.com"
        ]
     ]);
});

Let’s execute dredd again.

info: Configuration ‘./dredd.yml’ found, ignoring other arguments.
info: Beginning Dredd testing…
pass: GET (200) /api/post duration: 62ms
pass: GET (200) /api/author duration: 36ms
complete: 2 passing, 0 failing, 0 errors, 0 skipped, 2 total
complete: Tests took 103ms

And now we can see how the output changes to let us now that our API is working as expected.

Apiary is a platform that uses API Blueprint and helps you to generate your documentation, run automated tests, report errors, and even gives you a place to test your API in different environments, like your production app.
Also, it will create a Mock of your API, so you can start testing event without haven’t written a single line of code.

The first thing you need to do is create an account on apiary.com and link your GitHub profile to it.

Then you can create a new project using apiary.

and link this project to one of your GitHub repositories by clicking the button at the top left corner.

Click on “link this project to GitHub”.

And search for the specific repository.

At the end, Apiary will open a window to create a new commit that will add the apiary.apib file to your repository.

That’s it!

You are ready to start creating your API specification docs and tests. And because Apiary uses API Blueprint, you can also run your local tests using dredd.

What is beautiful about Apiary is that gives you set of tools out of the box, like a nice documentation interface.

If you click on any title of the docs, You’ll have access to the interactive panel.

Then you can select the environment to try any endpoint

You can even add form params or headers to the request if you need to.
And this is the best part, remember this is entirely new, and we haven’t built the API.

You can select the Mock Sever option and send the request. Apiari will mock the back-end implementation and will return whatever you specify in your docs as response.

Isn’t that great? Now you can design your API, write the documentation, and thanks to Apiary the rest of the team could start to write the front-end implementation using the mocked API, and in the meanwhile, you can begin developing the back-end side of the project.

Of course, both tools Apiary and dredd have more complex configurations that you can use to take more advantage of them and bring more value to your developing process.

I hope this article could give you enough background so you can start using this tools from the basics and keep going to develop better API’s.

Say hi on twitter!!