Yii2 RESTful API Development

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:

  • Setting up a REST API in Yii2 (Basic & Advanced templates)
  • Creating a RESTful Controller
  • Handling authentication (Token-based & JWT)
  • Versioning APIs
  • Rate limiting
  • Best practices for Yii2 API development

1. Setting Up a Yii2 RESTful API

Yii2 provides built-in REST functionality through the yii\rest\ActiveController.

1.1 Configuring URL Manager for APIs

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 users
  • GET /users/1 → Fetch user with ID 1
  • POST /users → Create a new user
  • PUT /users/1 → Update user with ID 1
  • DELETE /users/1 → Delete user with ID 1

2. Creating a RESTful Controller

Yii2 provides yii\rest\ActiveController, which handles basic CRUD actions automatically.

2.1 Creating a REST API Controller

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.com

3. Authentication in Yii2 APIs

Yii2 supports multiple authentication methods, including Basic Auth, Token Auth, and JWT.

3.1 Token-Based Authentication

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_token

3.2 JWT Authentication

JWT (JSON Web Token) is a secure way to authenticate users.

Step 1: Install Yii2 JWT Extension

composer require sizeg/yii2-jwt

Step 2: Configure JWT in UserController

use 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_token

Step 3: Generating JWT Token

Create 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.


4. API Versioning

To prevent breaking changes, it’s best to version your API.

4.1 Folder-Based Versioning

controllers/
    v1/UserController.php
    v2/UserController.php

Modify 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/users

5. Rate Limiting (Throttling)

Yii2 allows rate-limiting API requests per user.

5.1 Enabling Rate Limiting

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.


6. Best Practices for Yii2 REST API Development

  • Use versioning to maintain backward compatibility.
  • Enable authentication (Token or JWT) to secure your API.
  • Use pagination for large data responses.
  • Enable CORS to allow cross-origin requests.
  • Implement rate limiting to prevent abuse.
  • Use caching (Redis/Memcached) to improve performance.

Conclusion

Yii2 provides a powerful and flexible framework for building RESTful APIs. By following these steps, you can build a secure, scalable, and efficient API.