RESTful Web Services
Content of the «RESTful Web Services» section The Definitive Guide to Yii 2.0:
- Quick Start
- Response Formatting
- Rate Limiting
- Error Handling
Articles section «RESTful Web Services» The Definitive Guide to Yii 2.0:
When handling a RESTful API request, if there is an error in the user request or if something unexpected happens on the server, you may simply throw an exception to notify the user that something went wrong. If you can identify the cause of the error (e.g., the requested resource does not exist), you should consider throwing an exception along with a proper HTTP status code (e.g., [[yii\web\NotFoundHttpException]] represents a 404 status code). Yii will send the response along with the corresponding HTTP status code and text. Yii will also include the serialized representation of the exception in the response body. For example:
A good API is versioned: changes and new features are implemented in new versions of the API instead of continually altering just one version. Unlike Web applications, with which you have full control of both the client-side and server-side code, APIs are meant to be used by clients beyond your control. For this reason, backward compatibility (BC) of the APIs should be maintained whenever possible. If a change that may break BC is necessary, you should introduce it in new version of the API, and bump up the version number. Existing clients can continue to use the old, working version of the API; and new or upgraded clients can get the new functionality in the new API version.
To prevent abuse, you should consider adding rate limiting to your APIs. For example, you may want to limit the API usage of each user to be at most 100 API calls within a period of 10 minutes. If too many requests are received from a user within the stated period of the time, a response with status code 429 (meaning "Too Many Requests") should be returned.
Unlike Web applications, RESTful APIs are usually stateless, which means sessions or cookies should not be used. Therefore, each request should come with some sort of authentication credentials because the user authentication status may not be maintained by sessions or cookies. A common practice is to send a secret access token with each request to authenticate the user. Since an access token can be used to uniquely identify and authenticate a user, API requests should always be sent via HTTPS to prevent man-in-the-middle (MitM) attacks.
With resource and controller classes ready, you can access the resources using the URL like
http://localhost/index.php?r=user/create, similar to what you can do with normal Web applications.
In practice, you usually want to enable pretty URLs and take advantage of HTTP verbs. For example, a request
POST /users would mean accessing the
user/create action. This can be done easily by configuring the
urlManager application component in the application configuration like the following:
After creating the resource classes and specifying how resource data should be formatted, the next thing to do is to create controller actions to expose the resources to end users through RESTful APIs.
RESTful APIs are all about accessing and manipulating resources. You may view resources as models in the MVC paradigm.
While there is no restriction in how to represent a resource, in Yii you usually would represent resources in terms of objects of [[yii\base\Model]] or its child classes (e.g. [[yii\db\ActiveRecord]]), for the following reasons:
Yii provides a whole set of tools to simplify the task of implementing RESTful Web Service APIs. In particular, Yii supports the following features about RESTful APIs:
- Quick prototyping with support for common APIs for Active Record;
- Response format negotiation (supporting JSON and XML by default);
- Customizable object serialization with support for selectable output fields;
- Proper formatting of collection data and validation errors;
- Collection pagination, filtering and sorting;
- Support for HATEOAS;
- Efficient routing with proper HTTP verb check;
- Built-in support for the
- Authentication and authorization;
- Data caching and HTTP caching;
- Rate limiting;