Create RESTful API with Code Igniter #2 : Create API register, Models and Controllers, JSON Response
Repository
https://github.com/bcit-ci/CodeIgniter
What Will I Learn?
- Create Endpoint for Register
- Learn how to relate between models and controllers
- Make a JSON response
Requirements
- Basic PHP
- Install Ci > 3.1
- Local server (Xampp, Wampp, or etc)
- Mysqli
Resources
- Code igneter - https://www.codeigniter.com/
Difficulty
Basic
Tutorial Content
This tutorial is a continuation of the previous tuturial series, in the previous tutorial we have learned how to set up for the RESTful API application needs and we have also set up the database configuration that we use, in this tutorial I use Mysqli as the database driver, you can adjust it to your needs. in this tutorial, we will create a RESTful API to create an authentication system that can be used for any application. for that, we just start this tutorial.
Create API's endpoint
We will make endpoints that we will use in this authentication system. here is the endpoint that we will use, there are 6 endpoints that we will use.
routes.php
//Routes
$route['api/users']['GET'] = "UsersController/all_users";
$route['api/users/(:num)']['GET'] = "UsersController/detail_user/$1";
$route['api/register']['POST'] = "UsersController/register";
$route['api/user/(:num)']['PUT'] = "UsersController/update/$1";
$route['api/user/(:num)']['DELETE'] = "UsersController/delete/$1";
$route['api/login'] = "UsersController/login";
From the endpoint above we will use the endpoint $route['api/register']['POST'] = "UsersController/save";
.
api/register
This is a route API to handle user register.['POST']
This is a method which we will use, we use the POST method so that the data we send will be safer and hidden.UsersController/save
This is the controller that we will use to handle the registration process and the function we will use issave
.
- Use POSTMAN
We need to know that we will only build the RESTful API for the authentication system, so there isn't process data in the frontend, but we will use POSTMAN. Maybe for some of you already familiar with this tool, POSTMAN is widely used to help developers to test the API used. The following is a screenshot of using POSTMAN, by using POSTMAN we can send input data as we usually do in the frontend.
We will start creating the authentication system by registering the user.
- Create a Controller
On the route API register, we use the UserController
to handle the registration process, We will make it in this section. please create a new file to adjust the name of the controller we use on the route UserController.php
.
UserController.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UsersController extends CI_Controller { // UserController is the name of controller that we use in route.
// you can add any method that you will use.
}
With the above code we have initialized the UsersController
as the controller we use to handle the Register. Why all this can happen?. The secret is in the extends of the Core Code igniter. The UsersController can be a controller in Code igniter that's because we extend from Core CI which is CI_controller class UsersController extends CI_Controller
.
- Create a model
We have made a controller at the top. the controller only handles the process, which is related to the database is the model. The model is an abstraction of a table in the database. We will create a model with the file name user.php in the folder models.We can see the example as shown below.
<?php
class User extends CI_Model
{
// you can create a function or anything in here
}
This is the basic of the model structure. as in the controller, we can extend the Core model in Code Igniter class User extends CI_Model
- Inject a model in the controller
The model is just a table abstraction, to process the data we do in the controller for that we have to inject the model in the controller, we can do it using the __construct()
. We can see the example as follows.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UsersController extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('user');
}
}
- The
__construct()
is a function that will first be called in a controller class. So here we will do the inject a model in the controller. We useparent
to refer to the class that we used. - To load a model, we can use like this one
$this->load->model('user');
. in this tutorial, I used the user model so we can pass the name of model like thismodel('user')
.
RESTful API for Register user
The endpoint that we will create in our authentication system. That is to create a user register. Before we go to the next stage it's good to check whether the routing has been done, we can check by doing var_dump ()
, we can see the example as shown below.
- Check Routing
Route :$route['api/register']['POST'] = "UsersController/register";
public function register(){
var_dump("You are in the routing register");exit;
}
- Create function register in Model
Now we will create a function in the model, which we will use to related with the database. We will store the two values that are posted, those are email $this->input->post('email')
and password $this->input->post('password')
.
user.php
<?php
class User extends CI_Model
{
public function save(){
$data = [
'email' => $this->input->post('email'), // This the post value of email
'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT) //This the post value of password
];
$result = $this->db->insert('users',$data); //insert to database
if($result){
return [
'id' => $this->db->insert_id(),
'status' => true,
'message' => 'Data successfully added'
];
}
}
}
Retrieve post data: Because we use method post, we can retrieve the post data using the method
$this->input->post()
and the name of keypost('key')
.Hash password: Surely before we save the password we are obliged to have a hash, this is for security, we can use the method provided by PHP to have a hash that is
password_hash($parameter, PASSWORD_DEFAULT)
Insert data in Code igniter: to access the database we can use
$this-> db
, This is a rule of code igniter and to insert data to the database we can use theinsert ()
and we can pass the data that we will insert in the database in the form of arrays() with a key that adjusts the column name in the database. Theinsert()
method requires two parameters, the first is the table name in database Example: users and the second is the data that will be inserted for** example:**
$data = [
'email' => $this->input->post('email'),
'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT)
];
- Return json: Of course we will give a response to User if they are successfully registers, because the system we make is the RESTful API, then we have to give a response in the form of JSON. We can see the JSON response that we will return as follows.
return [
'id' => $this->db->insert_id(),
'status' => true,
'message' => 'Data successfully added'
];
- Access function register in Model
The function of the controller is only as a process, which is directly related to the database is a model. So what we need to do in the controller is to access the functions in the model. to use functions in the model we can do it like this $this->user->save();
. for more details, we can see it as follows.
UsersController.php
public function register(){
$this->user->save();
}
We can use
$this
for access the property in controller, termasuk property model yang ada pada function__construct()
.$this->user
user is the name of the model that we will access, This refers to the model that we load in the __construct()$this->load->model('user');
Create Response to JSON
Because we built the RESTful API of course, we have to give a response in the form of JSON, for that we need to change the response into JSON form, we can use the libraries to convert response to JSON, but in this tutorial, I will make our response function. We can see it as follows:
public function response($data){
$this->output
->set_content_type('application/json')
->set_status_header(200)
->set_output(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}
We will create a function, the name is
response($data)
and will receive a parameter that contains the data we change into a JSON form.In the code igniter we can set the output using the
$this-> output
method, We can set content type with->set_content_type('application/json')
, set status header with->set_status_header(200)
, and set the output withjson_encode()
, and you can use method_display()
to show the output.
Use thefunction response()
We have created the function response ()
now we will use it in the function register()
like the following:
public function register(){
return $this->response($this->user->save());
}
Now we can see the results we have done, the results will be like the following picture.
You can see the results like the picture above we have created an API that can be used by Users to register and not only that we also have learned how to relate between models and controllers, of course by understanding it we will be easier to develop applications that we make in code igniter, So many tutorials this time. I hope this tutorial can help you. thanks
Thank you for your contribution @duski.harahap.
After reviewing your contribution we suggest only one point below:
Your tutorial is great, thank you very much for developing your tutorial.
We are waiting for your next tutorial.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Thank you for your review, @portugalcoin!
So far this week you've reviewed 10 contributions. Keep up the good work!
Hi @duski.harahap!
Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server
Hey, @duski.harahap!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!