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 🙂 .

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

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

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.

same request : 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.

7 Comments

Leave a Reply

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

Google
PC/Internet Tricks

101 Amazing PC / Internet Tricks no one told you before   You Can Search Google Timer In Google For A Timer With Alarm Search This In Google For Direct Mp3 Links intitle:index.of?mp3 Your song name here Use Your Chrome Browser As Notepad Quickly. Just copy the text below to the address Bar. …

Android
2
Animated Splash Screen to you Android App using Android Studio

Today I am switching you to one finest technology of this world and that is Android. In this tutorial I am showing you how you can create a animated Splash screen which is the first part of any android application creation.

develope
Yii2.0 Dynamic Model Creation

As per my previous shared post you have to know what is Yii 2.0 and its awesome features. If you not read these posts please read this and know little bit about Yii2.0 basic(API Web APP) . Today I am sharing you a very new feature of Yii 2.0 which will …