This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Create a Cross-Platform REST API in Yii2

Updated on June 15, 2021

6 Min Read

When you are working on the cross-platform application, REST API’s become essential requirements of the process. This is why the Internet is full of third party API’s that provide a wide range of functionality and usability. Yii is a major PHP framework for rapid web development with a well-defined MVC architecture. In order to create a cross-platform Yii2 application, you need to create a REST API in Yii2.

In this article, I will develop a REST API in Yii 2 framework. The process covers:

  • Installation of Yii 2 framework on Cloudways
  • Database and table(s) creation
  • Database model using Gii
  • Controller creation using Gii
  • HTTP Calls (GET, PUT, POST, DELETE)

Introduction to REST API

REST stands for Representational State Transfer.  A REST API is a web service implemented using HTTP protocol and the principles of REST. It is a group of resources which uses HTTP methods likes GET, PUT, POST, DELETE.

Install Yii 2 Framework on Cloudways

First of all, sign up for a free account at Cloudways which provides flawless hosting for PHP websites. Next, login to your account and create a new server. Fill in the server and the application detail and select PHP Stack as your application. Enter your application, server and project’s name.

Note: You can host unlimited applications on a single server.

Select your favorite cloud provider, scale your server size according to your needs, select your location and click the Launch button. In a matter of minutes, the cloud server and the application is ready for next steps. Check out the following GIF for more details:


Now that your server and application is ready, open your server by clicking the server name.

Click Launch SSH Terminal as shown below:

Login with the username and password provided in the Master Credentials.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Now that you are connected to your server, install Yii2 framework using composer.

Type the following commands in the given order to go to the newly created Yii2 folder and start the installation process:

cd /applications/{your_app_folder}
cd public_html
composer create-project --prefer-dist yiisoft/yii2-app-basic restapi

The installation of the Yii 2 framework will begin:

Once the installation finishes, go to the application tab on Cloudways and select your application. Click on the button (as shown below) to access your application. Add /restapi/web/ to the URL and hit Enter.

You will see the main page:

Create Database and Table

Next, I will create a simple database with a table named Student. In order to create the database, go to the application and launch the database manager.

Type in the following command in the SQL command field:

CREATE TABLE `student` (

`ID` int(11) NOT NULL PRIMARY KEY,

`Name` varchar(40) NOT NULL,

`Last_Name` varchar(40) NOT NULL,

`Email` varchar(255) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

The database is now ready. Next, add its credentials in the db.php file.  Go to your application in Cloudways to get the database credentials.

Next, go to config/db.php and add dbname, username and password as shown below:

Create Database Model Using Gii

Go to the application URL and add restapi/web/index.php?r=gii at the end. Click on to Model Generator as shown below:

Fill in the table name and model name as student, and generate the model.

Now that the model has been created, I will create the scenario in the model for validation. Go to models/Student.php file and type the following command in the first line of the Student Class.

  const SCENARIO_CREATE = 'create';


After that add the following function:

public function scenarios()
 {
        $scenarios = parent::scenarios();
        $scenarios['create'] = ['Name','Last_Name','Email']; 
        return $scenarios; 
    }

Create Controller Using Gii

To create the controller, go to the restapi/web/index.php?r=gii again and click on the Controller Generator.

Create HTTP Calls

Now to manipulate data across different platforms, I will create the following API Actions.

Create Student Record

To create a Student record using the API, I will use the POST method.

Go to the controllers/StudentController.php file and create a new function called actionCreateStudent(). In this function, first set the application response format to JSON. After that, create a Student model object to create a record in the database. Then, in order to validate, I will use the scenario that I created in the Model.

Now if the validation is successful, I will add the record to the database through the save() function. This will save the model object in the database and return the status accordingly.

  public function actionCreateStudent()

   {
    
      \Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;

      $student = new Student();

      $student->scenario = Student:: SCENARIO_CREATE;

      $student->attributes = \yii::$app->request->post();


      if($student->validate())

      {

       $student->save();

       return array('status' => true, 'data'=> 'Student record is successfully updated');

      }

      else

      {

       return array('status'=>false,'data'=>$student->getErrors());    

      }

}

Now to test the Create Student action, i will use Postman extension. Go to the application URL and add /restapi/web/index.php?r=student/create-student  to the URL. Copy the complete link and paste it in the Postman as shown below:

Get All the Students Record

Now create another function in the Controller for getting the list of all the Student records in the JSON format.

This is how this will be done. Create a function actionGetStudent(). Set the response in JSON format. Then get all the data by using the find() function.

public function actionGetStudent()

{

\Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;

$student = Student::find()->all();

if(count($student) > 0 )

{

return array('status' => true, 'data'=> $student);

}

else

{

return array('status'=>false,'data'=> 'No Student Found');

}

}

Now to test the GET Student action, go to your application URL and add /restapi/web/index.php?r=student/get-student  to it. Copy the complete link and paste it in the Postman as shown below:

Update Student Records

Now, create another function in the Controller to update student records.

The process involves: Create a function actionUpdateStudent(). Set the response in JSON format. Then get the attribute in the variable and get the student record for a particular id by using find()->where. Then, set the value of attributes in the Student object, and then update through save() function.

    public function actionUpdateStudent()

   {

           \Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;     

         $attributes = \yii::$app->request->post();
       
         $student = Student::find()->where(['ID' => $attributes['id'] ])->one();

          if(count($student) > 0 )

          {

           $student->attributes = \yii::$app->request->post();

           $student->save();

           return array('status' => true, 'data'=> 'Student record is updated successfully');

          

          }



        else

        {

           return array('status'=>false,'data'=> 'No Student Found');

        }

   }

Now to test the Update Student action, go to your application URL and add /restapi/web/index.php?r=student/Update-student  to the URL. Copy the complete link and paste it in the Postman:

Delete Student Records

Create another function in the Controller for updating student records.

This function will create a function actionUpdateStudent() and set the response in JSON format. Then, get attribute in the variable and get the student record for the specific id by using find()->where. Next, delete student through delete() function.

 

public function actionDeleteStudent()

{

\Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;

 $attributes = \yii::$app->request->post();

     $student = Student::find()->where(['ID' => $attributes['id'] ])->one();  

      if(count($student) > 0 )

  {

       $student->delete();

  return array('status' => true, 'data'=> 'Student record is successfully deleted'); 

      }

else

{

return array('status'=>false,'data'=> 'No Student Found');

}

}

Conclusion

In this rather long tutorial, I created a REST API in Yii 2. In addition, I also discussed four API actions that handle data manipulation on the HTTP request calls and returns the output in JSON format.

 

Share your opinion in the comment section. COMMENT NOW

Share This Article

Saquib Rizwan

Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now