Creating Web Service

    We’ll use database named so create it. Then add book table with following structure:

    You can use in order to import it.

    Insert some data in the table, you can create more tables but for the sake of simplicity, in this tutorial we’ll use
    only book.

    Open config/db.php in the root of Yii web service application. Modify db configuration
    to specify your MySQL settings:

    Use Gii to generate model class for database tables (we have only one so far).
    for details on how to do it.

    You should get models/Book.php with the following content:

    1. namespace app\models;
    2. use Yii;
    3. class Book extends \yii\db\ActiveRecord
    4. {
    5. {
    6. return 'book';
    7. }
    8. public function rules()
    9. {
    10. [['title', 'author', 'publisher', 'year'], 'required'],
    11. [['id', 'year'], 'integer'],
    12. [['title'], 'string', 'max' => 255],
    13. [['description'], 'string'],
    14. [['author','publisher'], 'string', 'max' => 50]
    15. ];
    16. }

    There’s no ability to generate REST CRUD in Yii’s Gii code generator but doing it without it is easy and fun.

    First, create in the controllers directory.

    The controller class extends from yii\rest\ActiveController. By specifying modelClass as app\models\Book,
    the controller knows which model can be used for fetching and manipulating data.

    We’re adding CORS behavior in order to grant access to
    third party code (AJAX calls from external domain).

    If you have more models, create alike controllers for each one.

    Modify application configuration, urlManager component in in the config
    directory:

    1. 'urlManager' => [
    2. 'enableStrictParsing' => true,
    3. 'showScriptName' => false,
    4. 'rules' => [
    5. ['class' => 'yii\rest\UrlRule', 'controller' => 'book'],
    6. ],
    7. ]

    The above configuration mainly adds a URL rule for the book controller so that the book data can be accessed and
    manipulated with pretty URLs and meaningful HTTP verbs. If you have more controllers, specify them as array:

    To let the API accept input data in JSON format, configure the parsers property of the request application component
    to use the yii\web\JsonParser:

    1. 'request' => [
    2. 'parsers' => [
    3. 'application/json' => 'yii\web\JsonParser',
    4. ]

    Not it’s time to check what we’ve created so far with that little effort. We already have RESTful API for getting and
    managing book data:

    You may also access your API via Web browser by entering http://localhost/web-service/web/books.
    However, you may need some browser plugins to send specific request headers. For example,
    :

    Create Web Service - 图1