- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
-
Special Topics
- Dependency Injection (DI) in Yii2
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 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 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.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- What is YII? and How to Install it?
- Quantum AI – The Future of AI Powered by Quantum Computing
- Big Data: The Future of Data-Driven Decision Making
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Government Datasets from 50 Countries for Machine Learning Training
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- Python Challenging Programming Exercises Part 2
- Types of Numbers in Python
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Python Challenging Programming Exercises Part 1
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- 15 Amazing Keyword Research Tools You Should Explore
- Extract RGB Color From a Image Using CV2
- Ideas for Content of Every niche on Reader’s Demand during COVID-19
- Mastering Python in 2025: A Complete Roadmap for Beginners
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset