翻譯:【美國白宮網站的AP規範:WhiteHouse/api-standards】

White House Web API Standards

Guidelines【指導原則】

This document provides guidelines and examples for White House Web APIs, encouraging consistency, maintainability, and best practices across applications. White House APIs aim to balance a truly RESTful API interface with a positive developer experience (DX).javascript

這篇文檔爲白宮的web api提供了一些(準則)和例子,鼓勵一致、可維護、最好的實踐經過應用。白宮的接口是爲了提供一個真實的RESTful API,讓開發者有更好的體驗java

This document borrows heavily from:(該文檔大量參考瞭如下文章:)node

Pragmatic REST【實用的REST】

These guidelines aim to support a truly RESTful API. Here are a few exceptions:git

這些規則意在支持一個真實的RESTfull API,下面是一些例外:github

  • Put the version number of the API in the URL (see examples below). Don’t accept any requests that do not specify a version number.
  • 把版本號放到URL裏(下面有例子),不接受任何沒有明確API版本的請求
  • Allow users to request formats like JSON or XML like this:
  • 容許用戶用json或xml兩種請求格式,以下面:

RESTful URLs

General guidelines for RESTful URLs  [RESTful URLs一般的原則]

  • A URL identifies a resource.
  • 一個URL標識一個資源
  • URLs should include nouns, not verbs.
  • URLS應該包含名詞,不含動詞
  • Use plural nouns only for consistency (no singular nouns).
  • 用複數名詞爲了連貫性
  • Use HTTP verbs (GET, POST, PUT, DELETE) to operate on the collections and elements.
  • 用HTTP的請求方法(GET、POST、PUT、DELETE)進行資源上的操做
  • You shouldn’t need to go deeper than resource/identifier/resource.
  • 不須要比 resource/identifier/resource 層級更深
  • Put the version number at the base of your URL, for example http://example.com/v1/path/to/resource.
  • 在你的url中加進版本號,如:
  • URL v. header:
    • If it changes the logic you write to handle the response, put it in the URL.
    • 若是你處理相應的邏輯變了,把版本號放到URL裏
    • If it doesn’t change the logic for each response, like OAuth info, put it in the header.
    • 若是任何響應的邏輯都沒有變,像認證信息,把版本號放進頭信息裏
  • Specify optional fields in a comma separated list.
  • 明確可選的字段信息用逗號分隔開
  • Formats should be in the form of api/v2/resource/{id}.json
  • 格式應該像這樣 api/v2/resource/{id}.json

Good URL examples   [好的url例子]

Bad URL examples

HTTP Verbs

HTTP METHOD POST GET PUT DELETE
CRUD OP CREATE READ UPDATE DELETE
/dogs Create new dogs List dogs Bulk update Delete all dogs
/dogs/1234 Error Show Bo If exists, update Bo; If not, error Delete Bo

(Example from Web API Design, by Brian Mulloy, Apigee.)web

Responses

  • No values in keys
  • 在對應的名稱中沒有值
  • No internal-specific names (e.g. "node" and "taxonomy term")
  • 在內部沒有明確的命名
  • Metadata should only contain direct properties of the response set, not properties of the members of the response set
  • 元數據應該只包括相應集合的資源,而不是相應集合的成員的資源

Good examples

No values in keys:json

"tags": [
  {"id": "125", "name": "Environment"},
  {"id": "834", "name": "Water Quality"}
],

Bad examples

Values in keys:api

"tags": [
  {"125": "Environment"},
  {"834": "Water Quality"}
],

Error handling

Error responses should include a common HTTP status code, message for the developer, message for the end-user (when appropriate), internal error code (corresponding to some specific internally determined error number), links where developers can find more info. For example:服務器

錯誤的響應應該包含一個經常使用的http狀態碼、給開發者的錯誤信息、給最終用戶的信息、內部的錯誤碼、和給開發者的連接讓他們查閱更多的信息:restful

{
  "status" : "400",
  "developerMessage" : "Verbose, plain language description of the problem. Provide developers
   suggestions about how to solve their problems here",
  "userMessage" : "This is a message that can be passed along to end-users, if needed.",
  "errorCode" : "444444",
  "more info" : "http://www.example.gov/developer/path/to/help/for/444444,
   http://drupal.org/node/444444",
}

Use three simple, common response codes indicating (1) success, (2) failure due to client-side problem, (3) failure due to server-side problem:

用3個簡單、常見的響應碼標識(1)成功(2)失敗的緣由是客戶端問題(3)失敗的緣由是服務器端問題

  • 200 - OK
  • 400 - Bad Request
  • 500 - Internal Server Error

Versions

  • Never release an API without a version number.
  • 決不開放沒有版本號的api
  • Versions should be integers, not decimal numbers, prefixed with ‘v’. For example:
  • 版本應該是帶‘v’前綴的整型,不該該是小數,如:
    • Good: v1, v2, v3
    • Bad: v-1.1, v1.2, 1.3
  • Maintain APIs at least one version back.
  • 維持APIS至少有一個回退版本

Record limits

  • If no limit is specified, return results with a default limit.
  • 若是沒有limit值,將使用默認的limit值返回結果
  • To get records 50 through 75 do this:

Information about record limits should also be included in the Example resonse. Example:

在響應的信息中應該包括limits信息

{
    "metadata": {
        "resultset": {
            "count": 50,
            "offset": 25,
            "limit": 25
        }
    },
    "results": [
        { .. }
    ]
}

Request & Response Examples

API Resources

GET /magazines

Example: http://example.gov/api/v1/magazines.json

{
    "metadata": {
        "resultset": {
            "count": 123,
            "offset": 0,
            "limit": 10
        }
    },
    "results": [
        {
            "id": "1234",
            "type": "magazine",
            "title": "Public Water Systems",
            "tags": [
                {"id": "125", "name": "Environment"},
                {"id": "834", "name": "Water Quality"}
            ],
            "created": "1231621302"
        },
        {
            "id": 2351,
            "type": "magazine",
            "title": "Public Schools",
            "tags": [
                {"id": "125", "name": "Elementary"},
                {"id": "834", "name": "Charter Schools"}
            ],
            "created": "126251302"
        }
        {
            "id": 2351,
            "type": "magazine",
            "title": "Public Schools",
            "tags": [
                {"id": "125", "name": "Pre-school"},
            ],
            "created": "126251302"
        }
    ]
}

GET /magazines/[id]

Example: http://example.gov/api/v1/magazines/[id].json

{
    "id": "1234",
    "type": "magazine",
    "title": "Public Water Systems",
    "tags": [
        {"id": "125", "name": "Environment"},
        {"id": "834", "name": "Water Quality"}
    ],
    "created": "1231621302"
}

POST /magazines/[id]/articles

Example: Create – POST http://example.gov/api/v1/magazines/[id]/articles

{
    "title": "Raising Revenue",
    "author_first_name": "Jane",
    "author_last_name": "Smith",
    "author_email": "jane.smith@example.gov",
    "year": "2012"
    "month": "August"
    "day": "18"
    "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam eget ante ut augue scelerisque ornare. Aliquam tempus rhoncus quam vel luctus. Sed scelerisque fermentum fringilla. Suspendisse tincidunt nisl a metus feugiat vitae vestibulum enim vulputate. Quisque vehicula dictum elit, vitae cursus libero auctor sed. Vestibulum fermentum elementum nunc. Proin aliquam erat in turpis vehicula sit amet tristique lorem blandit. Nam augue est, bibendum et ultrices non, interdum in est. Quisque gravida orci lobortis... "

}

Mock Responses  【模擬響應】

It is suggested that each resource accept a 'mock' parameter on the testing server. Passing this parameter should return a mock data response (bypassing the backend).

建議在測試機上每一個api接受一個‘模擬’的參數,經過這個參數返回一個模擬的響應

Implementing this feature early in development ensures that the API will exhibit consistent behavior, supporting a test driven development methodology.

較早在線上環境實現這個特徵,確保api顯示一致的行爲,支持測試驅動開發的方法

Note: If the mock parameter is included in a request to the production environment, an error should be raised.

注意:在線上環境,若是請求帶有模擬的參數,應該返回錯誤

JSONP

JSONP is easiest explained with an example. Here's a one from StackOverflow:

Say you're on domain abc.com, and you want to make a request to domain xyz.com. To do so, you need to cross domain boundaries, a no-no in most of browserland.

The one item that bypasses this limitation is <script> tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really DO anything with the results, the script just gets evaluated.

Enter JSONP. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.

For example, say the server expects a parameter called "callback" to enable its JSONP capabilities. Then your request would look like:

http://www.xyz.com/sample.aspx?callback=mycallback

Without JSONP, this might return some basic javascript object, like so:

{ foo: 'bar' }

However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:

mycallback({ foo: 'bar' });

As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:

mycallback = function(data){
        alert(data.foo);
    };

http://stackoverflow.com/questions/2067472/what-is-jsonp-all-about?answertab=votes#tab-top

相關文章
相關標籤/搜索