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:
namespace app\models;
use Yii;
class Book extends \yii\db\ActiveRecord
{
{
return 'book';
}
public function rules()
{
[['title', 'author', 'publisher', 'year'], 'required'],
[['id', 'year'], 'integer'],
[['title'], 'string', 'max' => 255],
[['description'], 'string'],
[['author','publisher'], 'string', 'max' => 50]
];
}
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:
'urlManager' => [
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'book'],
],
]
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
:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
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,
: