HomePHP FrameworkHow to Create a RESTful API with Yii2 Advanced Template

How to Create a RESTful API with Yii2 Advanced Template

Advertisement

This comprehensive guide outlines practical steps for building a RESTful API using the Yii2 Advanced Template. You will learn endpoint configuration, controller creation, and API testing methods for data exposure. This tutorial is designed for developers seeking to implement a modern and scalable REST architecture.

Advertisement

An Application Programming Interface (API) is a software interface that facilitates integration and data exchange between applications. A RESTful API is an API implementation that adheres to the principles of REST (Representational State Transfer) architecture. This architecture uses the standard HTTP protocol for communication, making it a performant, scalable, and easy-to-develop solution.

Building a RESTful API in Yii2 can be done efficiently. The framework provides a robust MVC foundation and built-in support for REST development. This article will guide you in creating a separate API endpoint, distinct from typical frontend and backend logic.

Advertisement

We will use a case study of exposing data from a user table. The basic assumption is that you have successfully installed the Yii2 Advanced Template. If not, you can refer to the official Yii Framework documentation for installation guidance.

Advertisement

Steps to Implement a RESTful API in Yii2

The implementation process consists of three main stages: endpoint preparation, application configuration, and testing. Let’s discuss each stage in detail.

1. Creating the API Directory Structure

The first step is to create a dedicated working environment for the API. In the Yii2 Advanced Template, we will create a new application directory named api.

  1. Copy the entire contents of the backend directory to the same location, then rename the copy to api.
  2. Open the common/config/bootstrap.php file. Add an alias for the api directory by adding the following line:
    Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
  3. Inside the environments directory, copy the backend folder within both dev and prod. Rename each copy to api.
  4. Edit the environments/index.php file. Add configuration paths for the api directory in the setWritable and setCookieValidationKey sections.
  5. Use the “Find and Replace” feature in your code editor. Replace all occurrences of the string backend with api in all files within the newly created api folder.
Creating an api directory from a backend copy in Yii2
Figure 1: The process of duplicating the backend directory into api.

2. Configuring the Controller and URL Rules

Once the structure is ready, the next step is to configure the controller that will handle API requests.

  1. Create the API Controller. Create a new file named UserController.php inside the api/controllers directory. Fill it with the following code:
    <?php
    namespace api\controllers;
    use yii\rest\ActiveController;
    
    class UserController extends ActiveController
    {
        public $modelClass = 'common\models\User';
    }
    This controller inherits from ActiveController, which automatically provides full RESTful endpoints (GET, POST, PUT, DELETE) for the User model.
  2. Configure the URL Manager. Open the api/config/main.php file. Add or modify the request and urlManager components within the components array:
    'components' => [
        'request' => [
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
            ],
        ],
    ],
    This configuration enables JSON input parsing and defines routing rules for the User controller.
  3. Configure the Web Server (Optional). For Apache servers, create an .htaccess file inside the api/web folder with the following content:
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php
    This file directs all requests to Yii2’s main index.php file.

3. Testing the API Endpoints

Once configuration is complete, you can test the created API endpoints. Here are some commonly used testing methods.

  1. Using Postman. Download and install Postman. Create a new request using the GET method and the URL: http://localhost/[your-project-name]/api/web/users. If successful, you will receive a JSON response containing user data.
  2. Using cURL. Run the following command in a terminal or command prompt:
    curl -H "Accept: application/json" "http://localhost/[your-project-name]/api/web/users"
  3. Access via Browser. Open the endpoint URL in a browser. However, this method is usually only suitable for simple GET request testing.
Example RESTful API Yii2 testing result in Postman
Figure 2: Test result for the GET /users endpoint using Postman.

By completing all the steps above, you have successfully built a basic RESTful API in Yii2. For further development, consider adding authentication mechanisms (like JWT), authorization, rate limiting, and good API documentation. Always consult the official Yii2 documentation to ensure your implementation follows current best practices.

Latest Articles