Documenting REST APIs

STC Summit 2016 Workshop — Anaheim, California

By Tom Johnson / @tomjohnson
idratherbewriting.com

Workshop Outline

  1. Intro to APIs
  2. Using an API like a developer
  3. Documenting an API
  4. Publishing API documentation

Some Technologies to Explore

  • JSON
  • Postman
  • cURL
  • Command line
  • Chrome JavaScript Console
  • REST
  • JavaScript
  • Git

1.0 Documenting REST APIs

Where to find this online

1.1 The market for REST API doc

Doc is most important factor

Doc is  the interface

Architectural style requires users to consult docs

REST API growth

Services mashup

1.2 What is a REST API?

APIs allow systems to interact

REST API model

REST characteristics

  • REST == Representational State Transfer
  • Named by Roy Fielding, modeled after web
  • Nouns and verbs (resources and methods)
  • Stateless
  • Cacheable
  • Uses web protocols

The web follows REST

Put on your developer hat

1.3 Scenario for using an API

Show wind factors

See also yahoo weather

Mashape API Directory

Activity

  1. Go to market.mashape.com.
  2. Find Weather by fyhao (market.mashape.com/fyhao/weather-13)

Compare with Aeris Weather API

1.4 Getting authorization keys

The need for API keys

1.5 Submit requests via Postman

About Postman

Activity

Make a request to each weather endpoint using Postman.

1.7 Using cURL

Windows users: Use double quotes and add -k.

1.8 Understand cURL more

cURL commands




curl http://example.com

   curl http://example.com -i

   curl http://example.com -I

   curl -X GET http://example.com -I 

   /* GET, POST, PUT, DELETE */



 
  

Activity

On a command prompt, type and compare the following:

curl http://example.com -i
curl http://example.com -I

Unpacking the Mashape example

                  
curl --get --include 'https://simple-weather.p.mashape.com/aqi?lat=37.3
54108&lng=-121.955236' \
-H 'X-Mashape-Key: {api key}' \
-H 'Accept: text/plain'
                  
               

cURL commands

Command Description
-i or --include Include response headers
-d or --data Include data to post
-H or --header Submit header
-X POST The HTTP method to use
@filename Load content from a file

Full example



curl -i -H "Accept: application/json" -X POST -d "{status:MIA}" 
   http://personsreport.com/status/person123

   
   

Activity

Use cURL to make the same weather requests you made in Postman.

2.0 Analyze the JSON response

JSON objects are key-value pairs


{
"key1":"value1",
"key2":"value2"
}
 

JSON arrays are lists of items


    ["first", "second", "third"]
  

Objects can appear inside arrays


[  
   {  
      "name":"Tom",
      "age":39
   },
   {  
      "name":"Shannon",
      "age":37
   }
]
  

Arrays can appear inside objects


   {
"children": ["Avery","Callie","lucy","Molly"],
"hobbies": ["swimming","biking","drawing","horseplaying"]
}
   

Activity

Identify the objects and arrays in the weatherdata endpoint response.

2.1 Using the returned JSON

Generating code

Logging the response to the console

Activity

  1. Go to this sample page: idratherbewriting.com/files/restapicourse/weatherdata.html
  2. Open the JavaScript Console (View > Developer > JavaScript Console).
  3. Click Run the request
  4. Investigate the JSON object logged to the console. Find the wind details.

Now switch hats

Now you're a tech writer documenting a new endpoint

2.4 New endpoint to document

Endpoint wiki page details

Essential sections in API ref topics

  • Endpoint description
  • Request URL
  • Methods
  • Parameters
  • Request example
  • Response example
  • Status and error codes
  • Code samples

2.5 Endpoint descriptions

Terminology for "endpoint" varies

  • API calls
  • Endpoints
  • API methods
  • Calls
  • Resources
  • Objects
  • Services
  • Requests

Some examples

When it gets confusing to refer to resources by the endpoint


  api_site.com/{apikey}/users
// gets all users

api_site.com/{apikey}/users/{userId}
// gets a specific user

api_site.com/{apikey}/rewards
// gets all rewards

api_site.com/{apikey}/rewards/{rewardId}
// gets a specific reward

api_site.com/{apikey}/users/{userId}/rewards
// gets all rewards for a specific user

api_site.com/{apikey}/users/{userId}/rewards/{rewardId}
// gets a specific reward for a specific user

api_site.com/{apikey}/users/{userId}/rewards/{missionId}
// gets the rewards for a specfic mission related to a specific user

api_site.com/{apikey}/missions/{missionid}/rewards
// gets the rewards available for a specific mission
  

Activity

Critique the Mashape Weather API descriptions.

Compare with Aeris Weather API descriptions.

2.6 Request URL

Terminology for "request URL" varies

  • Requests
  • Endpoints
  • API methods
  • Resource URLs
  • URLs
  • URL syntax
  • Path

Represent parameter values with curly braces


  /campaigns/{campaign_id}/actions/send
  

The method

2.7 Parameters

Parameters configure the endpoint

4 Types of Parameters

  • Path parameters
  • Header parameters
  • Query parameters
  • Request body parameters

Listing data types

  • string
  • integer
  • boolean
  • object

Query parameter order is irrelevant


 /surfreport/{beachId}?days=3&units=metric&time=1400

 /surfreport/{beachId}?time=1400&units=metric&days=3
 

Parameters in the request body


 {
"days": 2,
"units": "imperial",
"time": 1433524597
}
  

2.8 Request example

Requests clarify syntax

API Explorers provide interactivity with your own data

2.9 Response example

A sample response

Strategies for nested objects

JS wizardry

Where to include sample responses

3.0 Code samples

Which language?

See also Twilio

Auto-generating code samples

3.1 Putting it all together

3.2 Creating the user guide

Sample template

Essential sections

  • Overview
  • Getting started
  • Authorization keys
  • Code samples/tutorials
  • Response and error codes
  • Quick reference

3.3 The overview

3.4 "Getting Started"

Other examples: Hipchat, Aeris, Smugmug

3.5 Authorization

API keys

Basic Auth


                 Authorization: Basic bG9sOnNlY3VyZQ==
               

HMAC

OAuth 2.0

Rate limits

3.6 Response codes

Error codes, status codes

Status codes specific to endpoints

Possible reasons for errors

  • Invalid API keys
  • Wrong data types
  • Bad JSON syntax in post body
  • No resource to return
  • Rate limits exceeded
  • Max or min values exceeded
  • Missing parameter
  • Network-related error

3.7 Code samples

3.8 Quick reference guide

See also the Shopify cheat sheet.

7.9 My biggest tip:
Test everything

Switch focuses from content creation to publishing

4.5 Publishing API doc

Why devs don't use HATs

  1. No integration into version control
  2. No auto-generation of doc from source
  3. No reference templating engines
  4. No interactive API consoles
  5. No sexy outputs that sell

4.6 List of 100 APIs

Programmable Web

Activity

Look at about 5 different APIs from this list: idratherbewriting.com/pubapis_apilist. Identify one thing that the APIs have in common.

4.8 Tool decisions

  • Who will write? Engineers or tech writers?
  • Pros of having engineers write...
  • Cons of having engineers write...

4.9 Github wikis

Collaboration platform

Activity

  1. Create a Github wiki and publish content on a sample page.
  2. Save the Github repository locally.
  3. Make a change locally, commit it, and push the commit to the Github repository.

5.0 More about Markdown

Sample syntax


## Heading 2

This is a bulleted list:

* first item
* second item
* third item

This is a numbered list:

1. Click this **button**.
2. Go to [this site](http://www.example.com).
3. See this image:

![My alt tag](myimagefile.png)

5.2 Pull request workflows

Merging branches

5.3 REST API specifications

5.4 Swagger

Petstore

Activity

Using the Swagger Petstore (http://petstore.swagger.io/):

  1. Create a new pet.
  2. Find your new pet by the ID.
  3. Delete your pet.

5.5 More about YAML

Code without < markup >

Sample syntax



reindeer:
  - Donner
  - Blitzen
  - Comet
  - Cupid
hobbies:
  active:
    - flying
    - prancing
  inactive:
    - pawing
    - driving

items:
  - title: Course overview
    url: /docapis_course_overview/
    weight: 1.0
    audience: writers

address: 1234 main street
route: Google maps
   
   

My YAML tutorial

Lucybot

5.6 RAML

Sample output

5.7 API Blueprint

Sample output

5.8 Static site generators

Documentation theme for Jekyll

Writing in Jekyll

Github Pages

5.9 Readme.io

Sample output

6.1 Custom UX solutions

6.2 Help authoring tools

6.3 Design patterns

Common themes

Five patterns

  • Structure and templates
  • Website platform
  • Abundant code samples
  • Long-ish pages
  • API Interactivity

What engineers want

6.9 Challenging factors

  • Translation
  • Versioning
  • PDF

Getting a job with API doc

Strategies

  • Demonstrate technical aptitude with samples
  • Build wide (not deep) knowledge of programming
  • Participate in open source projects
  • Create tech tutorials
  • Create Swagger UI outputs for a company's docs

Questions

Thanks!

Tom Johnson
idratherbewriting.com
@tomjohnson
tomjohnson1492@gmail.com