Yii2 base Rest API Creation

As i shared in my previous article that Yii2 framework hold all power of php with quite good modifications. Today i am going to explain you how you can make your web service using Yii2 core functions and provided libraries.

Without any web services mobile application is same as like a human which has not any soul.

 

Yii2 web service /REST API is the give a power to mobile application by which application can request for new data or add or delete data from database without any complications.

Let Start

  1. Action Register
  2. Action Login
  3. Action Getprofile 
  4. Action Delete
Action Register

For create controller and its action create a controller file ApiController.php in your yii2 basic controller folder.

<?php

namespace app\controllers;

use Yii;
use yii\rest\ActiveController;
use app\models\your model name;// your model name
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Session;
use yii\db\Query;


class ApiController extends ActiveController {

 public $modelClass = 'app\models\name';// your model name

After creation ApiController.php file then create action for user register,create,delete,update and view.

 public function actionRegister() 
 {
 if(!empty($_FILES['files']['tmp_name'])) 
 {
 $params = Yii::$app->request->post();
 $date = date('Y-m-d H:i:s');
 $params['date_created'] = $date;
 $params['password'] = $params['password'];
 $model = new Api(['scenario' => 'register']);
 $username = $params['username'];
 $target_path = yii::$app->basePath . "/uploads/" . $_FILES['files']['name'];
 $ext = pathinfo($target_path, PATHINFO_EXTENSION);
 $ext=($ext)?$ext:'.jpg';
 $img_name = time() . "." . $ext;
 $path = yii::$app->basePath . "/uploads/" . $img_name;
 $syntax = move_uploaded_file($_FILES['files']['tmp_name'], $path);
 if($syntax)
 {
 $params['image'] = $img_name;
 $params['is_active']=1;
 $model->attributes = $params;
 if ($model->save()) 
 {//mail sending
 $mail = Yii::$app->mailer->compose()
 ->setFrom('no-reply@yourwebsite.com')
 ->setTo($model->email)
 ->setHtmlBody('Dear ' . ucfirst($model->username) . ', <br> <br>You have been successfully registered with Your Website Name. Below are your login credentials you can use to login in the app.<br><br>

Email address: "'.$model->email.'"<br>
Password: "'.$model->password.'" <br>
<br>
Thanks.')
 ->setSubject('Welcome to Your Website Name ');
 $mail->send();
 $response['isSuccess'] = 1;
 $response['message'] = 'Thank you for registering on Your Website Name!';
 $response['userid'] = $model->id;
 $response['username'] = $model->username;
 $response['profileImageUrl'] = "http://".$_SERVER['SERVER_NAME']."/client/yourwebsite/uploads/".$model->image;
 } 
 else
 {
 $c = count($model->errors);
 $i = 0;
 if (array_key_exists("username", $model->errors) || array_key_exists("email", $model->errors))
 {
 if (array_key_exists("username", $model->errors))
 {
 $response['isSuccess']= 2 ;
 $response['error_code']= 400 ;
 $response['message'] = 'An account with this username already exist, please try another one.';
 } 
 else
 {
 $response['isSuccess'] = 2 ;
 $response['error_code'] = 400;
 $response['message'] = 'There is an existing account associated with this email address';
 } 
 } 
 
 }
 }
 else
 {
 $response['isSuccess'] = 0 ; 
 $response['error_code'] = 400;
 $response['message'] = 'Profile picture could not be uploaded, please try again.';
 }
 }
 else
 {
 $response['error']= 1;
 $response['message'] = 'Please upload an image.';
 }
 echo json_encode($response, JSON_PRETTY_PRINT);
 
 }
Action Login
public function actionLogin() 
 {
 $params = Yii::$app->request->post();
 if (!empty($params['email']) && !empty($params['password']))
 {
 $email = $params['email'];
 $pass1 = $params['password'];
 $pass = $params['password'];
 if (($model = Api::findOne(['email' => $email, 'password' => $pass])) !== null)
 {
 if ($model->is_active == 0)
 {
 $data['isSuccess'] = 2;
 $data['message'] = 'Your account has been deactivated by Your Website Name.';
 } 
 else 
 {
 $date = date('Y-m-d H:i:s');
 $model->last_login = $date;
 if ($model->save()) 
 {
 $data['isSuccess'] = 1;
 $data['userid'] = $model->id;
 $data['username'] = $model->username;
 $data['profileImageUrl'] = "http://".$_SERVER['SERVER_NAME']."/yourwebsite/uploads/".$model->image;
 $data['message'] = 'You have been logged in successfully!';
 }
 }
 } 
 else 
 {
 $data['isSuccess'] = 0;
 $data['message'] = 'Invalid email ID or password.'; //'Either username or password is wrong.';
 }
 }
 
 else
 {
 $data['isSuccess'] = 0;
 $data['message'] = '<Field name> cannot be blank.'; 
 }
 echo json_encode($data, JSON_PRETTY_PRINT);
 }
3 Action Getprofile
 public function actionGetprofile() 
 {
 $params = Yii::$app->request->post();
 if (!empty($params['id']) )
 {
 $id = $params['id'];
 if (($model = Api::findOne(['id'=>$id])) !== null)
 {
 if ($model->is_active == 0)
 {
 $data['isSuccess'] = 2;
 $data['message'] = 'Your account has been deactivated by our Website Name.';
 } 
 else 
 {
 $data['isSuccess'] = 1;
 $data['userid'] = $model->id;
 $data['username'] = $model->username;
 $data['email'] = $model->email;
 $data['profileImageUrl'] = "http://".$_SERVER['SERVER_NAME']."/yourwebsite/uploads/".$model->image; 
 }
 } 
 else 
 {
 $data['isSuccess'] = 0;
 $data['message'] = 'Unable to load user profile.'; //'Either username or password is wrong.';
 }
 }
 
 else
 {
 $data['isSuccess'] = 0;
 $data['message'] = '<Field name> cannot be blank.'; 
 }
 echo json_encode($data, JSON_PRETTY_PRINT);
 }
Action Delete
 public static function actionDelete()
 {
 $params = Yii::$app->request->post();
 $userid = $params['id'];
 $email = $params['email'];
 if (($model = Api::findOne(['id' => $userid])) !== null)
 {
 if ($model->is_active == 0)
 {
 $response['isSuccess'] = 2;
 $response['message'] = 'Your account has been deactivated by Your Website Name.';
 } 
 else 
 {
 $query =' DELETE FROM tablename WHERE id="'.$userid.'"';
 $connection = Yii::$app->db;
 $command = $connection->createCommand($query);
 $result = $command->execute();
 if($result)
 {
 $response['isSuccess'] = 1;
 }else{
 $response['isSuccess'] = 0;//$totalItems=$query->count();
 }
 }
 }
 //echo json_encode(array('status'=>1,'data'=>$models,'totalItems'=>$totalItems),JSON_PRETTY_PRINT);
 echo json_encode($response, JSON_PRETTY_PRINT);
 }

After create all actions then call test your Api’s from postman extension of your chrome browser.

By that way your basic web services will create . I’m waiting for your views.

Happy coding 🙂 .

6 thoughts on “Yii2 base Rest API Creation

  1. Hi in model file what we have to add?
    I am a beginner in yii framework.
    In config/main.php what will be the url format to run this

    1. Ajay Kr. Maheshwari

      Never need to any thing with model for API part. After define you can use this model same as like your previous controller adn for run this in browser you need to use this url http://your localaddress/api/actionname

  2. Thank you for this tutorial. Would you like to allow me to download the full source code + database? I am beginner in yii2 framework, I want to explore more, please.

Leave a Comment

Your email address will not be published. Required fields are marked *