Yii2 makes it easy to build RESTful APIs with built-in support for routing, request handling, authentication, and response formatting. In this tutorial, we’ll cover:
Yii2 provides built-in REST functionality through the yii\rest\ActiveController.
Modify config/web.php (Basic Template) or config/main.php (Advanced Template) to enable pretty URLs and remove index.php.
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
],
],This automatically creates RESTful routes like:
GET /users → Fetch all usersGET /users/1 → Fetch user with ID 1POST /users → Create a new userPUT /users/1 → Update user with ID 1DELETE /users/1 → Delete user with ID 1Yii2 provides yii\rest\ActiveController, which handles basic CRUD actions automatically.
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}This exposes CRUD operations for the User model.
🔹 Customizing actions
You can override default actions inside UserController.
public function actions()
{
$actions = parent::actions();
unset($actions['delete']); // Disable delete
return $actions;
}🔹 Custom Action Example
public function actionSearch($email)
{
return \app\models\User::find()->where(['email' => $email])->one();
}Now you can call:
GET /users/search?email=test@example.comYii2 supports multiple authentication methods, including Basic Auth, Token Auth, and JWT.
Add an access_token field to your User model and modify behaviors() in UserController.
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => \yii\filters\auth\QueryParamAuth::class, // Token in query param
'tokenParam' => 'access_token',
];
return $behaviors;
}Now, API requests require an access_token:
GET /users?access_token=your_tokenJWT (JSON Web Token) is a secure way to authenticate users.
composer require sizeg/yii2-jwtUserControlleruse sizeg\jwt\Jwt;
use sizeg\jwt\JwtHttpBearerAuth;
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => JwtHttpBearerAuth::class,
];
return $behaviors;
}API calls must include the JWT token in the Authorization header:
Authorization: Bearer your_jwt_tokenCreate an endpoint to generate JWT tokens:
public function actionLogin()
{
$user = User::findOne(['email' => Yii::$app->request->post('email')]);
if (!$user || !$user->validatePassword(Yii::$app->request->post('password'))) {
throw new \yii\web\UnauthorizedHttpException('Invalid credentials.');
}
$jwt = Yii::$app->jwt;
$signer = $jwt->getSigner('HS256');
$key = $jwt->getKey();
$token = $jwt->getBuilder()
->issuedBy('http://your-app.com')
->identifiedBy(uniqid(), true)
->issuedAt(time())
->expiresAt(time() + 3600)
->withClaim('uid', $user->id)
->getToken($signer, $key);
return ['token' => (string) $token];
}Now, users can log in and get a JWT token for authentication.
To prevent breaking changes, it’s best to version your API.
controllers/
v1/UserController.php
v2/UserController.phpModify urlManager to support multiple versions:
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['v1/user', 'v2/user']],
],Clients can now request specific API versions:
GET /v1/users
GET /v2/usersYii2 allows rate-limiting API requests per user.
Modify UserController:
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['rateLimiter'] = [
'class' => \yii\filters\RateLimiter::class,
];
return $behaviors;
}Then, implement RateLimitInterface in the User model:
class User extends \yii\db\ActiveRecord implements \yii\filters\RateLimitInterface
{
public function getRateLimit($request, $action)
{
return [100, 600]; // 100 requests per 10 minutes
}
public function loadAllowance($request, $action)
{
return [Yii::$app->cache->get('rate_limit') ?? 100, time()];
}
public function saveAllowance($request, $action, $allowance, $timestamp)
{
Yii::$app->cache->set('rate_limit', $allowance);
}
}If users exceed the rate limit, they get an HTTP 429 Too Many Requests error.
Yii2 provides a powerful and flexible framework for building RESTful APIs. By following these steps, you can build a secure, scalable, and efficient API.
Sign in to join the discussion and post comments.
Sign in