Jump to content

Documentation/API Documentation Template

From mediawiki.org

API Documentation

[edit]

This document provides a simple template that can be used as a starting point for technical documentation that is intended to guide the audience through the use of REST APIs.

Who should use this template?

[edit]

This template is suitable for writing any form of REST API documentation and is limited to just that. Writing any other form of API documentation is well beyond the scope of this template.

Template

[edit]

Below is the provided template for this particular genre and is to be duly followed when creating documentation.

Overview

[edit]

API documentation should start with a detailed description of what the API is about, what is it used for, and who should make use of it.

URL structure

[edit]

Often, REST APIs have a basic URL structure for requests made to any of their endpoints. Since no interaction can be made with an API without the URL, it becomes important to explicitly state the structure of the API before moving on to any other aspect of the documentation.

The URL structure provided should include the following;

  • The base URI
  • The version of the API (if the API has versions)
  • The endpoint

Here's an example of the above put together:

https://www.example.com/v1/route

Versioning

[edit]

Some APIs might have evolved over time, therefore, they have different versions. Each version of an API is quite distinct and some are not backwards compatible.

The version of an API should be explicitly stated as well as the appropriate revisions.

Request format

[edit]

Querying data over an API requires making some sort of requests and sending some payload or data with that request. How requests should be made to your API should be clearly defined here.

Request headers

[edit]

Some requests need certain headers to be sent as a part of the request. Most often, the headers that are sent are the Method, Content-Type, and Authorization headers.

  • The specific headers that might be needed to access some endpoints should be stated here and why that header may be required.
  • Clearly state all methods that are allowed. The most common are GET, POST, PUT, and DELETE.
  • You should also state if some endpoints require authorization before access is provided.

Authentication

[edit]

Some endpoints are protected and need authorized access. You should explain how you authenticate endpoints here and how authenticated requests should be made.

Additionally, code samples in the appropriate language or using curl should be added here so the audience can get a better understanding of the explanation provided.

API request example
fetch('https://www.example.com/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer <token>'
    },
    body: JSON.stringify({
        username: 'Username',
        password: 'Password'
    })
})
.then(res => res.json())
.then(res => {
    // Do something with the data
})
.catch(err => {
    // Do something with the errors
})

Response format

[edit]

People who consume an API need to have an understanding of what kind of data is returned from that API and how the data is structured. The response returned from an API when a request is successful is quite different from the response when the request fails. Both success and error responses should be explained in detail. Here's an example:

All responses from this API have a JSON response body with the Content-Type set to application/json in the response header. The structure of the body solely depends on the endpoint being queried.

All successful response will have an HTTP status code within the 2xx range, errors caused by the client will have a status code within the 4xx range, while errors caused by the server (such errors are very rare) will have a status code within the 5xx range. There is also a type attribute sent with errors, which simplifies the error handling on the client-side with a human-readable error message attached.

Errors

[edit]

Different APIs respond to errors differently. Consumers of your API must know which error to expect, so it can be handled adequately.

MediaWiki API for example returns an error object with an error code and error message; you can read about it at API:Errors and warnings.

API error response example
{
    "error": {
        "code": "error-code",
        "info": "the message as-is, with parameter substitution but without any parsing",
        ...any extra data...
    }
}

The sample above shows what the error responses look like. Explain each field of the response and what it means, especially the error types and status codes. This can be done in a table:

Error codes
Status code Explanation
200 - OK Everything worked as expected
400 - Bad Request The request was unacceptable this is often due to missing parameters
403 - Forbidden Incorrect permissions to perform this request
404 - Not Found The requested resource does not exist
5xx Something went wrong on the servers
Error types
Code Info
unknownerror Unknown error: This usually means something unusual like a rare race condition occurred. If you get this error, retry your request until it succeeds or returns a more informative error message
unknownerror Unknown error: "errorcode"
unknownerror-nocode Unknown error
unsupportednamespace Pages in the Special namespace can't be edited
protectednamespace-interface You're not allowed to edit interface messages
protectednamespace You're not allowed to edit pages in the "namespace" namespace
customcssjsprotected You're not allowed to edit custom CSS and JavaScript pages

The above shows how the status codes and types should be displayed to the audience. You could also have a look at API:Errors and warnings#Standard error messages and API:REST API/Reference to see how errors are presented in MediaWiki APIs.

Success

[edit]

When a request is successful, the audience should have an idea of what the expected response looks like. This responses may vary from endpoint to endpoint, but it is expected that they are of similar structure.

Here's a good example:

All successful requests to this API return a success parameter set to true and a data parameter containing the response object of that request:

Success response example
{
    "success": true,
    "data": {
        "fullname": "John Doe",
        "email": "johndoe@mail.com",
        "age": 45
    }
}

Pagination

[edit]

Some requests result in more matching responses than can be returned on a single API call. You should explain in detail how the responses to the API endpoints are paginated. Some APIs use the page and perPage query parameters, which gives the users full control over how much data they intend to query at a time, while some simply automate these paginations. You should discuss in detail how pagination is handled in your API.

API endpoints

[edit]

The audience of this documentation needs to have a place where they can reference all endpoints this API provides. They need to know:

  • What is the body of the request of this endpoint?
  • What query parameters are necessary to add to this request?
  • What does the expected response look like?

Additionally, it would be really nice to take advantage of the Special:ApiSandbox, so the audience can test each endpoint without having to set up anything or write any code. Here's a table of some MediaWiki Action API endpoints:

NOTE: This is prefilled with mock responses and data. Some endpoints of the Action API require authenticated access, so this is just an example of how you could present endpoints to the audience. You don't necessarily have to use this format.

S/N Endpoint Description Query parameters Error responses
1 GET

abusefiltercheckmatch

Check to see if an AbuseFilter matches a set of variables, an edit, or a logged AbuseFilter event.
filter:
The full filter text to check for a match.
This parameter is required.
vars:
JSON encoded array of variables to test against.
rcid
Recent change ID to check against.
Type: integer
logid
Abuse filter log ID to check against.
Type: integer
code: Permission Denied


Info: You don't have permission to test abuse filters.


Request

null

Response
{
    "success": true,
    "data": "Some data"
}
2 GET

checktoken

Check the validity of a token
type
Type of token being tested.
This parameter is required.
One of the following values: createaccount, csrf, deleteglobalaccount, login, patrol, rollback, setglobalaccountstatus, userrights, watch
token
Token to test.
This parameter is required
maxtokenage
Maximum allowed age of the token, in seconds.
Type: integer
code: Permission Denied


Info: You don't have permission to test abuse filters.

Request
{
    "checktoken": {
        "result": "invalid"
    }
}
Response


code: Invalid Token


Info: Please input a valid

Stewardship

[edit]

Here, you would share useful information about the following:

  • Who maintains this page
  • What projects are included
  • How to contact the author and maintainers of this project (only share public information here, like Zulip or IRC)
  • Links to discussion pages or threads

Example

[edit]