Great API documentation requires code examples
James Higginbotham

Great API documentation requires code examples

Documentation is a very important element of the developer experience. Most API teams assume that the documentation of the API’s endpoints is enough. However, that is only the beginning of the API consumer journey. Code examples provide the important guidance necessary for developers to be able to apply the documentation in practice. They are the glue that helps connect-the-dots between reference documentation for your endpoints and developers integrating your API.

Write ‘Getting Started’ code examples first

Code examples come in a variety of forms, from just a few lines that demonstrate how a specific endpoint works, to more complex examples that demonstrate a complete workflow. Initially, the developer must overcome basic understanding of your API and how it will help solve their problem. It is important to remember that during this phase, the developer just wants to see something work.

“Time to first Hello World”, or TTFHW, is a key metric for determining API complexity. The longer it takes to get a developer to their first “win”, the more likely the developer will struggle with your API and perhaps abandon it or build their own solution.

To help developers get started quickly, provide concise examples that remove all need for explicit coding. Look at the following example from Stripe:

```ruby

    require "stripe"

    Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"

    Stripe::Token.create(

      :card => {

        :number => "4242424242424242",

        :exp_month => 6,

        :exp_year => 2016,

        :cvc => "314"

})

```

Notice in this example that there is little code to write – fill-in your API key and the credit card credentials and you are ready to go. Example code that requires that you write lots should be avoided at this stage, as it requires you to learn more about the API before you can try it out. Never require developers to write code to complete an example when first trying out your API – instead, make it easy to get started and see the request work successfully.

Workflow examples

After the developers have had some time to try our your API using some getting started examples, the next step is to begin to demonstrate common use cases and workflows.

Workflow examples focus more on achieving specific outcomes. As a result, we should use copious inline comments to explain why each step is necessary. Be willing to include hard-coded values for easier reading. Choose variable and method names that make the code easy to read and understand. Below is an example of charging a credit card using Stripe:

```ruby

# Set your secret key: remember to change this to your live secret key in production

# See your keys here: https://dashboard.stripe.com/account/apikeys

Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"

# Token is created using Stripe.js or Checkout!

# Get the payment token submitted by the form:

token = params[:stripeToken]

# Create a Customer:

customer = Stripe::Customer.create(

  :email => "[email protected]",

  :source => token,

)



# Charge the Customer instead of the card:

charge = Stripe::Charge.create(

  :amount => 1000,

  :currency => "usd",

  :customer => customer.id,

)



# YOUR CODE: Save the customer ID and other info in a database for later.



# YOUR CODE (LATER): When it's time to charge the customer again, retrieve the customer ID.

charge = Stripe::Charge.create(

  :amount => 1500, # $15.00 this time

  :currency => "usd",

  :customer => customer_id, # Previously stored, then retrieved

)

```

It is important to note that while these examples will be more complex than those found from the first milestone, they shouldn’t exceed the average screen size. The examples need to be short enough to explain the concepts but not too long that they require considerable time to understand. It is often best to demonstrate scenarios that are easily understood and likely map to your customer needs.

Error case examples

The final step is to help your developers understand how to integrate your API into their production environment. This includes how to catch errors to help developers properly troubleshoot problems, and retry loops when a minor outage occurs. You may also want to demonstrate how to catch and recover from bad data provided by end users. Finally, if you are enforcing rate limiting, then show how to obtain the current rate limits for their account.

Where do you include code examples?

Now that you have written some nice code examples to help get developers started, demonstrate common workflows, and how to handle error cases, we need a place to put them. There are a few options you may wish to consider:

  1. Embed the code examples into the description of your OpenAPI definition
  2. Utilize a static site generator such as Jekyll or Hugo to capture your code examples and additional documentation
  3. Select a third-party solution such as Readme.io or the documentation feature of your API management layer

No matter the method you choose, sharing code examples that guide developers throughout the integration process will help them be happy and successful – and no one likes a grumpy developer!

As part of our mission to cheer up grumpy developers everywhere, the Tyk team has recently made all Tyk documentation Open Source for your viewing, editing and ‘critiquing-until-it’s-borderline-ripped-to-shreds’ pleasure. Please – be our guest.