YARAS 为编写 RESTful API 提供了标准、指南和惯例,旨在促进一致性、可维护性和一致地使用 b
Yet Another RESTful API Standard (YARAS) - Introduction
YARAS provides standards, guidelines and conventions for writing a RESTful API and is intended to encourage consistency, maintainability, and consistent use of best practices.
Anyone who's spent time writing or using RESTful APIs knows that one size does NOT fit all. REST leaves a tremendous gap between what REST defines and what goes into a full API.
Before I started writing my own I thought I thought I'd be able to find a great RESTful standard that I could use with a quick search or two. In my search I found lots of great APIs, lots of articles on best practices and yes - even a standard or two.
Unfortunately I didn't find anything that captured what I was looking for. What I found was that some API Standards did what I wanted and some did not. For example I very much liked the documentation for PayPal's API but disliked the use of the version in the url. However, I very much liked the way that github uses media types for versioning. The Eve framework uses Mongo DB syntax for filters (e.g. where, sorting and field inclusion). Further these examples where standards so are written in the wrong way to guide RESTful API developers. This standard this is a blend of the best of what I could find that's already out there combined with (very few) of my own ideas.
The bottom line is that nothing out there did quite what I wanted. While nothing was new - it's a combination of what some of the best APIs are doing that I think represents the best practices.
What's in the Standard
At a very high level I wanted support for these things - though there is much more below:
A strongly opinionated RESTful structure that while flexible are bounded so that APIs are very consistent.
It is absolutely clear how to name resources.
It is absolutely clear how to do paging, sorting, filtering, and searching.
The standard has an opinion about how errors should be handled.
Support for versioning using media types.
Part of the standard is that APIs must have a well known and easy to find specification that developers and consumers can validate requests and responses against (e.g. JSON-schema).
Supports HATEOAS.
This document borrows heavily from these EXCELLENT sources (many more are at the end of this document):
Consider allowing query filters with YAML-like syntax for improved readability especially after encoding (i.e. 'where={"lastname":"Doe"}&...' is equivalent to 'where=lastname:Doe&...').
Take a look at HATEOAS templates - is there a standard process that clearly defines how to name parameters so they can be easily populated/navigated by the client? If so - update the examples herein and reference the model.
Versions of this Standards
I plan on moving this standard along over time so just as with any other software project I will create branches and versions and encourage you to reference the appropriate version number if you refer to this document so people are aware of what version you speak of.
Requests - the Basics
RESTful URIs - General Guidelines
A URI uniquely identifies a resource.
URIs should include nouns, not verbs.
Use plural nouns only for consistency (no singular nouns).
Some servers ignore case so use lower-case in URI segments, separating words with underscores ('_').
Use appropriate HTTP verbs (GET, POST, PUT, PATCH, DELETE) to operate on the collections and elements .
Keep URIs as short as possible, with as few segments as makes sense.
Parameters in URI versus header:
If it changes the logic you write to handle the response, put it in the URI.
If it does not change the logic for each response, like OAuth info, put it in the header.
Good URI examples
List of magazines:
GET /magazines
A single magazine:
GET /magazines/1234
All articles in (or belonging to) this magazine:
GET /magazines/1234/articles
Add a new article to a particular magazine:
POST /magazines/1234/articles
Filtering is done via query parameters:
GET /magazines?where={"year":2011}
GET /articles?where={"topic":"economy","year":2011}
Two alternative ways you might allow to get to magazines by publisher (though I prefer using the where filter):
GET /publishers/somepublisher/magazines
GET /magazines?where={"publisher":"somepublisher"}
Sorting is done via query parameters:
GET /magazines?sort=[("year", "asc"),("topic", "desc")]
Note: the where clauses above are shown un-encoded for clarity.
Bad URI examples
Non-plural noun:
/magazine
/magazine/1234
/publisher/somepublisher/magazine/1234
Verb in URI:
/magazine/1234/create
Sorting outside of query parameters
/magazines/2011/desc
HTTP Verbs
APIs can support the full range of CRUD operations. Within the same API, you can have a read-only resource accessible at one endpoint, along with a fully editable resource at another endpoint. The following table shows our implementation of CRUD via REST:
Action
HTTP Verb
Context
Create
POST
Collection
Read
GET, HEAD
Collection/Document
Update
PATCH
Document
Replace
PUT
Document
Delete
DELETE
Collection/Document
X-HTTP-Method-Override
As a fallback for the odd client not supporting any of these methods, the API should honor X-HTTP-Method-Override requests. For example a client not supporting the PATCH method could send a POST request with a X-HTTP-Method-Override: PATCH header. This indicates that the server should perform a PATCH, overriding the original request method.
Responses - the Basics
The Response Body
The overall JSON response for this standard follows the HAL standard with a couple additional elements:
Part of the HAL standard:
_links - required - part of the HAL standard - provides for HATEOAS links.
_embedded - optional - part of the HAL standard - used to embed resources in the response. When used properly can improve read performance and reduce application chattiness.
Compatible with but not part of the HAL Standard:
data - required - not part of HAL - data specific to the resource in question is grouped under the 'data' element to make it clear what is related to the resource.
_metadata - required - includes various elements that describe the data included in the parent object including but not limited to sorting, filtering, pagination data and field exclusion.
At the top level every HATEAOS response looks like this (though _embedded is optional):
The data for every resource falls within the data element. As an API designer this where the resource model is populated and is the meat of what you'll be defining. If there is a single resource the data object represents that resource. If there is more than one resource data may be an array or map of resources.
Generally follow Google JSON Style Guide when building out JSON objects. This is because tools will tend to follow these guides.
Required Fields:
id - (required) yep - this is the only required field - this is an id that uniquely identifies this resource vs other resources of the same type. Some may opt to use guids in this field - still it must be called an 'id'.
Beyond that here are some guidelines for building sensible JSON response bodies:
No values as keys.
No internal-specific names (e.g. "node" and "taxonomy term")
May exclude computationally expensive or rarely used fields by default.
JSON elements should be meaningful but short if possible
no values in keys (i.e. {"id": "125", "name": "Health concerns related to increased use of cellphones"} not {"125", "Health concerns related to increased use of cellphones"})
to make the API consistent consider using common suffixes to denot