Post

Docs that cannot lie

API docs written by hand drift away from the API. Generating them from the code that handles the request is the only fix I've seen hold up.

Docs that cannot lie

Every API has two descriptions of itself. One is the code that actually handles requests. The other is the documentation that tells people what the code does. On the day they’re written, they agree. After that, they drift.

Someone adds an optional field and forgets the docs. Someone renames an error code and updates one page out of three. A required parameter quietly becomes optional. None of these are big mistakes, and nobody notices them until a merchant builds an integration against the docs and it fails against the API.

For a payment API, that’s a support ticket at best. At worst it’s an integration that looks fine in testing and breaks on a real edge case.

Why “be more careful” doesn’t work

The usual response is process: a checklist item in the pull request template, a reviewer who’s supposed to ask “did you update the docs?” It helps for a few weeks. Then a busy week comes along and the docs fall behind again, because keeping two things in sync by hand relies on people remembering, every time, forever.

The only approach I’ve seen hold up is to stop having two things. If the documentation is generated from the same code that validates requests and builds responses, it can’t describe an API that doesn’t exist. That’s what I mean by docs that cannot lie. They can still be incomplete or badly written, but they can’t be wrong about the shape of the API.

One definition, three jobs

The idea is to describe each endpoint once, in a form the application actually uses at runtime, and get three things out of it:

  1. The request is validated against it.
  2. The response is checked against it in tests.
  3. The OpenAPI spec is generated from it.

Here’s a simplified sketch of what that looks like in a Rails controller. This isn’t real library code, just the shape of the idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class PaymentsController < ApplicationController
  endpoint :create do
    summary "Create a payment"

    body do
      required :amount,   Integer, min: 100, description: "Amount in the smallest currency unit"
      required :currency, String,  enum: %w[SAR], description: "ISO 4217 code"
      optional :description, String, max_length: 255
      optional :metadata, Hash
    end

    response 201, PaymentSchema
    response 400, ErrorSchema
  end

  def create
    payment = Payments::Create.call(validated_params)
    render json: PaymentSchema.render(payment), status: :created
  end
end

The important part is that validated_params comes from the same body block that ends up in the docs. If someone makes description required in the block, the API starts rejecting requests without it and the docs say it’s required, in the same commit. There’s no second place to forget.

Responses need the same treatment

Requests are the easy half because the application already has to validate them. Responses are where drift hides, because nothing breaks when a serializer adds a field that isn’t documented, or stops sending one that is.

So the response schemas get checked in the test suite. Every request spec that hits an endpoint also checks that the body matches the schema for that status code:

1
2
3
4
5
6
it "returns the documented shape" do
  post "/v1/payments", params: valid_params, as: :json

  expect(response).to have_http_status(:created)
  expect(response).to match_documented_response
end

With that in place, a serializer change that isn’t reflected in the schema fails a test. A schema change that the serializer doesn’t follow also fails. Either way, the two can’t silently disagree.

Make CI the one who remembers

The last piece is making sure the published spec is the one the code produces. The spec gets generated as part of the build and compared with the committed copy. If they differ, the build fails and tells you to regenerate it.

1
2
bin/rails openapi:generate
git diff --exit-code openapi.yaml

It sounds strict, but in practice it’s freeing. Nobody has to remember anything during review. The diff in openapi.yaml shows up in the pull request next to the code change, and reviewers can see exactly how the public API is changing, which is often the most important thing to review.

What it doesn’t fix

Generated docs tell you what an endpoint accepts and returns. They don’t tell you why you’d call it, what order to call things in, or what a decline code means for your checkout page. Guides, examples and explanations still have to be written by people, and they can still go stale.

But they go stale in a different way. A guide that’s out of date is usually incomplete. A reference that’s out of date is wrong. Generating the reference means the part people copy into their code is always true, and the time spent on writing can go to the parts that need a person.

This post is licensed under CC BY 4.0 by the author.