How to Build the Rest of API in Yii2?
How to Build a REST API in Yii2 Using ActiveController and Serializers
REST APIs have become a fundamental part of modern web and application development. They allow different software systems to communicate with one another using standard HTTP methods and structured data formats such as JSON.
Whether you are building a mobile application, single-page application, SaaS platform, or cross-platform solution, a REST API can act as a central communication layer between the client and the server.
Yii2, a component-based PHP framework, provides powerful tools for creating RESTful APIs. With features such as yii\rest\ActiveController, URL routing, HTTP verbs, content negotiation, and serializers, developers can build structured and scalable APIs with less repetitive code.
In this article, we will explore the fundamentals of building a REST API in Yii2, with particular focus on ActiveController and serializers.
What Is a REST API?
A REST API allows applications to communicate through HTTP requests.
A typical REST API uses resources. For example, an application may contain a users resource.
Different HTTP methods can represent different operations:
- GET – Retrieve data
- POST – Create a new resource
- PUT/PATCH – Update an existing resource
- DELETE – Remove a resource
For example:
GET /users Retrieve users
GET /users/10 Retrieve user 10
POST /users Create a user
PUT /users/10 Update user 10
DELETE /users/10 Delete user 10
This resource-based structure makes APIs predictable and easier for mobile and frontend developers to consume.
Why Use Yii2 for REST API Development?
Yii2 provides several features that make REST API development efficient:
- Component-based architecture
- Strong MVC structure
- Active Record support
- Flexible routing
- HTTP method handling
- Content negotiation
- Built-in REST controllers
- Data serialization
- Authentication support
- Validation and error handling
Instead of manually creating separate controller logic for every CRUD operation, Yii2 provides REST-specific components that reduce boilerplate code.
Prerequisites for Yii2 REST API Development
Before creating a Yii2 REST API, developers should have:
- PHP installed with the required extensions
- Composer
- A Yii2 application
- A database such as MySQL or PostgreSQL
- Basic PHP and Yii2 knowledge
- An API testing tool such as Postman or another REST client
You should also understand Yii2 models, controllers, Active Record, and database migrations.
Creating a Database Model
The first step is to create a database table that will be exposed through the API.
For example, a users table might contain:
- id
- name
- created_at
- updated_at
Once the database table is available, a Yii2 Active Record model can be created to interact with it.
For example:
class User extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'users';
}
}
The model acts as the connection between the database and the REST API controller.
What Is ActiveController in Yii2?
One of the most useful features of Yii2 REST API development is yii\rest\ActiveController.
ActiveController is designed specifically for RESTful APIs that work with Active Record models.
Instead of manually writing actions for listing, viewing, creating, updating, and deleting records, ActiveController provides many of these operations automatically.
A basic REST controller can look like this:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
This simple controller can provide standard REST operations for the User model.
The controller can support operations such as:
- Listing records
- Viewing a single record
- Creating a record
- Updating a record
- Deleting a record
This significantly reduces repetitive controller code.
Configuring REST URL Rules
To make the API accessible through clean URLs, Yii2 URL rules can be configured.
A REST URL rule may look like this:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['user'],
],
],
],
With this configuration, the API can expose endpoints such as:
GET /users
GET /users/1
POST /users
PUT /users/1
DELETE /users/1
This makes the API easier to understand and consume.
Understanding Serializers in Yii2
A serializer converts data from PHP objects and models into a format that can be returned to API clients.
Most modern REST APIs use JSON responses.
For example, a Yii2 model may contain:
[
'id' => 1,
'name' => 'John',
'email' => 'john@example.com'
]
The serializer converts this data into a structured JSON response:
{
"id": 1,
"name": "John",
"email": "john@example.com"
}
Yii2 provides the yii\rest\Serializer component for transforming response data.
This is particularly useful when an API returns:
- Individual model records
- Lists of models
- Pagination information
- Related records
- Links and metadata
Why Serializers Are Important
Without proper serialization, API responses can become inconsistent or expose unnecessary model data.
Serializers help developers control:
- Response structure
- Data fields
- Related resources
- Pagination information
- Links
- Metadata
For example, an API may return:
{
"items": [
{
"id": 1,
"name": "John"
}
],
"_links": {
"self": {
"href": "/users"
}
}
}
This structure provides the client with both data and useful metadata.
Controlling API Response Fields
Yii2 models can define which attributes should be returned through the API.
For example:
public function fields()
{
return [
'id',
'name',
'email',
];
}
This allows developers to control the public API response.
Sensitive fields such as passwords, internal tokens, or private system data should never be returned unnecessarily.
Developers can also define calculated fields:
public function fields()
{
return [
'id',
'name',
'displayName' => function ($model) {
return strtoupper($model->name);
},
];
}
This allows API responses to contain application-specific values without storing every value directly in the database.
Working with Related Data
Yii2 serializers can also work with related models.
For example, a user may have multiple orders.
A response may include:
{
"id": 1,
"name": "John",
"orders": [
{
"id": 1001,
"total": 250
}
]
}
Related data can be configured through model fields and controller responses.
However, developers should be careful when returning large relationships because excessive nested data can negatively impact API performance.
API Authentication and Security
A production REST API should not expose sensitive endpoints without authentication.
Yii2 APIs can implement authentication mechanisms such as:
- Bearer tokens
- Access tokens
- OAuth-based authentication
- JWT-based authentication through appropriate extensions
Authentication allows the API to identify the user making a request.
Authorization determines what that authenticated user is allowed to do.
For example:
- A customer can view their own orders.
- An administrator can manage all users.
- A support user may have limited access.
Authentication and authorization should be designed before exposing a production API.
Testing Yii2 REST APIs
After creating the API, developers should test each endpoint.
For example:
GET /users
POST /users
PUT /users/1
DELETE /users/1
Testing should verify:
- Correct HTTP status codes
- Request validation
- Authentication
- Error responses
- JSON structure
- Database changes
- Pagination
- Permissions
Tools such as Postman can be useful for manually testing REST endpoints during development.
Best Practices for Yii2 REST API Development
For a reliable and scalable Yii2 REST API:
Use Consistent URLs
Use resource-based endpoint structures such as:
/api/users
/api/orders
/api/products
Use Appropriate HTTP Methods
Do not use POST for every operation. Use HTTP methods according to the operation being performed.
Validate Input
Never trust client-side data. Validate all incoming API requests on the server.
Control Serialized Fields
Return only the data that clients actually need.
Use Pagination
Large datasets should not be returned in a single response.
Implement Authentication
Protect private resources with an appropriate authentication strategy.
Maintain Consistent Error Responses
Clients should receive predictable error formats and meaningful HTTP status codes.
Conclusion
Yii2 provides a powerful foundation for building modern REST APIs. With ActiveController, developers can quickly create standard CRUD endpoints while reducing repetitive controller code. Yii2 serializers further improve API development by converting models and related data into structured, controlled responses.
For intermediate Yii2 developers, understanding the relationship between Active Record models, ActiveController, URL rules, HTTP methods, and serializers is essential for creating maintainable APIs.
Whether you are building a mobile application backend, SaaS platform, enterprise system, or cross-platform web application, Yii2 can provide a structured approach to REST API development.
If you are looking for professional Yii2 development services, XcelTec can help you design and develop scalable APIs, web applications, and custom software solutions aligned with your business requirements.
Contact us for more information:
Phone: +91 987 979 9459 | +1 919 400 9200
Email: sales@xceltec.com
Frequently Asked Questions
1. What is ActiveController in Yii2?
ActiveController is a Yii2 REST controller designed to work with Active Record models. It provides standard REST operations such as listing, viewing, creating, updating, and deleting records with minimal custom code.
2. What is a serializer in Yii2 REST API development?
A serializer converts Yii2 models and other data structures into formats such as JSON for API responses. It also helps control response fields, related data, pagination, links, and metadata.
3. Can Yii2 ActiveController be customised?
Yes. Developers can customise actions, filters, authentication, access control, fields, validation, and response formats according to application requirements.
4. Why are serializers important in a Yii2 REST API?
Serializers help create consistent and controlled API responses. They also prevent unnecessary or sensitive model attributes from being exposed to API clients.