By Dmitriy Mironov
One of the most common types of APIs that technical communicators document are REST APIs. REST APIs facilitate the interaction of client-server technology: a client sends a request to the server and, after some processing, the server returns a response to the client. Some servers are actually clients for other servers.
An Example
As an example, an online hotel booking service might have a module called “user registration” that allows users to register on the site. However, the service might prefer to use ready-made solutions provided by social networks for logging in, so that any user can register on the hotel booking site using his or her Facebook or Twitter account.
In this case, the hotel-booking website (which is a server for clients seeking hotels) acts as a client for social networks when requesting user authentication information.
Such inter-service requests go through an API (Application Programming Interface). On today’s Web, this API is often implemented in accordance with the recommendations of REST (REpresentational State Transfer), a kind of style guide for Web developers about how to conveniently and effectively construct their API. An API that follows REST recommendations is called a RESTful API.
Web Service Communication
Web services communicate with each other over the network using the application layer protocol HTTP as “transport” for their transmittable data. A discrete portion of information in this case is one HTTP message—strictly formalized, structured, and standardized.
An HTTP message contains the following:
- Host (http://server.com);
- Request line (consists of three parts):
- Method (GET, HEAD, POST, TRACE, etc.);
- Resource (/api/v2/users/);
- HTTP version (HTTP/1.1);
- Headers (Content-Length, User-Agent, User-Agent, etc.);
- Message body, also called Payload (optional).
Any HTTP response has one of a number of defined HTTP status codes. Generally, the most common status codes used are as follows:
- 2XX—for successful requests;
- 4XX—for errors on the client side (for example, errors in request’s parameters format); and
- 5XX—for errors on the server side (for example, server is down or some network problems).
For a full list of error codes, see “List of HTTP status codes” at en.wikipedia.org/wiki/List_of_HTTP_status_codes. There is no point in listing all of them in your documentation, because they are commonly known. However, in some cases it can be useful to point out a few codes, especially if some codes are specified by API developers to indicate specific conditions or API states.
Making Requests Through URLs
As noted earlier, HTTP is just a transport for messages. REST recommends using some HTTP options to communicate API requests.
Developers should specify the object of their request directly through a URL, use the appropriate HTTP method to define an action with the resource, and use the message body only for required data.
Sending your parameters through the URL helps separate service data from essential information in the message body. These parameters are called a query string, which is common terminology for Web developers.
To use additional parameters in a query string, you add them to the URL after a “?” and list them with the help of a separator “&”. Each parameter is a pair consisting of a name and value, separated by “=”. For example:
http://server.com/api/v2/users/?action=auth&login=user89&pass=fds983k
This URL consists of several components:
- Host (http://server.com);
- Resource (api/v2/users);
- Query string:
- Parameter “action” with value “auth” (for authorization);
- Parameter “login” with value “user89”;
- Parameter “pass” with value “fds983k”.
This is the main difference between REST and other development styles and standards, where all ancillary information (pointer to the object, method, service data) is transmitted inside the message body of HTTP message.
RESTful API uses four of nine common HTTP methods:
- GET—retrieve data from the server;
- POST—edit data on the server;
- PUT—create a new object on the server;
- DELETE—delete an existing object on the server.
Message Body Through XML or JSON
The message body may contain data in any format, depending on service specialization and object types. However, there are two common and well-known standards: XML and JSON.
- XML stands for eXtensible Markup Language.
- JSON stands for JavaScript Object Notation.
Both of these formats are used to describe some data in a definite, strict, and formal way. Both allow defining hierarchical structures.
Since XML is markup language, it uses pair tags. This mean that every property consists of opening tag <tag> and closing tag </tag>, while the value of the property stays between the tags.
When you put one pair tag inside another, you construct a hierarchical structure. Here’s an example:
<class>
<pupil>
<name>Bob Clarkson</name>
<dateofbirth>05032005</dateofbirth>
<gender>male</gender>
</pupil>
<pupil>
<name>Clarissa Starks</name>
<dateofbirth>08112004</dateofbirth>
<gender>female</gender>
</pupil>
<pupil>
<name>Steven Scott</name>
<dateofbirth>25082005</dateofbirth>
<gender>male</gender>
</pupil>
</class>
JSON is a younger, lightweight alternative to XML. JSON doesn’t use pair tags, just a “property”—”value” format and some JavaScript syntax. Quotation marks are used to define text values called strings. Here is the same data about our class in JSON:
{
"class":
{
"pupil":
{
"name": "Bob Clarkson",
"dateofbirth": 05032005,
"gender": "male"
},
"pupil":
{
"name": "Clarissa Starks",
"dateofbirth": 08112004,
"gender": "female"
},
"pupil":
{
"name": "Steven Scott",
"dateofbirth": 25082005,
"gender": "male"
}
}
}
Be careful with curly braces { … } because they mean the start and end of a property value. Also be careful with commas, since a comma means there are more values. If there is no comma, the range is considered to be finished.
Indentations can provide a more readable presentation of the data. Plain messages will look more compact:
XML:
<class><pupil><name>Bob Clarkson</name><dateofbirth>05032005
</dateofbirth><gender>male</gender></pupil><pupil><name
>Clarissa Starks</name><dateofbirth>08112004</dateofbirth><gender
>female</gender></pupil><pupil><name>Steven Scott</name>
<dateofbirth>25082005</dateofbirth><gender>male</gender></pupil>
</class>
JSON:
{"class": {"pupil": {"name": "Bob Clarkson", "dateofbirth":
05032005, "gender": "male" }, "pupil": {"name": "Clarissa Starks",
"dateofbirth": 08112004, "gender": "female"}, "pupil": {"name":
"Steven Scott", "dateofbirth": 25082005, "gender": "male"}}}
Documenting REST APIs
Now that you understand the foundation of REST APIs, how should you document RESTful APIs for Web developers?
First, make a list of all API methods. After that, describe each of them, following these simple steps:
- Define the HTTP method.
- Define the resource.
- Define the host.
- Define HTTP headers.
- Define the query string.
- Define the message body.
- Data format
- Message structure
- All possible parameters
- Value types
Points 1 though 3 are required in any case, while points 4 through 6 can be optional. It depends on the method described.
Let’s imagine a RESTful API of some online-notebook service (such as Evernote.com), which allows different developers to build their own desktop or mobile clients. These clients must provide some functionality: creating a new note, editing a note, deleting a note, attaching a file to an existing note, etc. These functions are your list of API methods.
Here is a bare-bones example of a documented method for an API that involves online notebooks.
Creating a New Note
PUT /api/v2/notes
Host: server.com
Query string:
userid: user’s identification inside the service (required)
cat: note’s category (required)
scope: visibility scope
Example
PUT http://server.com/api/v2/notes?userid=4535&cat=personal&scope=3
Request payload example:
{"note": {
"header": "note #7",
"note": "Some text for this note…",
"editable": true
}}
Parameter | Data Type | Description |
---|---|---|
header | string | Header of new note |
note | string | Body of new note |
editable | boolean | Is the note editable? |
Response payload example:
{"data": {
"status": "success",
"noteid": 102554
}}
Parameter | Type | Description |
---|---|---|
status | string | Success – in case of successError – if something went wrong |
noteid | int | Id of new note |
Examples of REST API Documentation
A standard for RESTful API formalized documentation doesn’t really exist. You can define your own way of presenting the information. As a best practice, make sure to use your company’s style guide (if one exists) and ask UX designers for help (if they’re available).
Here are a few API documentation examples from well-known companies that are worth studying:
- Instagram, instagram.com/developer/endpoints/likes/
- Google, developers.google.com/+/api/latest/people/search
- Twitter, dev.twitter.com/docs/api/1.1
In writing API documentation, the most important principle to remember is to get feedback. Your main customer and consumer is the Web developer—he or she is the end user for API documentation. Therefore, you need a way to get their feedback about your work. They will usually tell you what to improve and what else to describe.
Getting Information to Document REST APIs
Writing and organizing API information is one task, but how do you gather this information in the first place? There are three main approaches to gathering API information: you can interview developers, you can analyze their code, or you can analyze HTTP messages (requests and responses) sent by client to server and back (API in action).
Ways and tools for interviewing developers and analyzing code are numerous and depend on the developer and code. But I do want to emphasize the importance of traffic analysis. Through traffic analysis you can see the API in action, check different options and cases, and see vivid examples of requests and responses used in the API.
As you explore an API in action, I recommend a couple of add-ons for Firefox and Chrome:
- Firebug or RESTClient (Firefox)
- Postman – REST Client or Advanced REST client (Chrome)
These tools allow you to generate requests to a server without writing any application code as well as analyze responses from server in convenient and easy ways.
Conclusion
Keep in mind that developers don’t need long narration. They need good documentation. Good API documentation has the following characteristics:
- Uniform style—use templates for similar look of different method descriptions;
- Working examples—return appropriate results according to the URL used in your examples;
- Clear parameter specifications—define types, obligation, and purpose;
- Visual navigation—provide easy to browse lists and groups of methods;
- References—reference general rules in your examples about how the API works (e.g. signature methods for all requests);
- Brief description of methods—keep any verbal description succinct, since a good REST API is “self-descriptive” and often obvious.
Dmitriy Mironov is originally from the Russian Federation. After working at more than 10 companies for more than 10 years, generally in roles of “system administrator” and “quality manager,” he found that the most interesting activities involve investigating and structuring technical information—in other words, technical writing. Dmitriy now lives in the Ukraine and works as a technical writer with an advanced development team. They’re building a high-load gaming Web service, using REST style for the API. He is producing documentation for this REST API.
Thanks for writing this, Dmitriy!
It’s exactly what I needed!