Create RESTful API with Code Igniter #3 : Create Endpoint for Users and User detail, Dynamic functions

in #utopian-io6 years ago (edited)

Repository

https://github.com/bcit-ci/CodeIgniter

What Will I Learn?

  • Create Endpoint for Users and User detail
  • Create Dynamic functions

Requirements

  • Basic PHP
  • Install Ci > 3.1
  • Local server (Xampp, Wampp, or etc)
  • Mysqli

Resources

Difficulty

Basic

Tutorial Content

This tutorial is a continuation of a tutorial series on the RESTful API with Code Igniter. I suggest you to see the previous tutorial from this tutorial series, because this tutorial will relate to the previous tutorial. in this tutorial we will develop the authentication system more advance. We will create an API to retrieve data from users who have registered in our database. Let's just start the tutorial.

RESTful API for get user

We have created an Endpoint for the user API in the previous tutorial for those of you who don't know the endpoint, here is a list of endpoints that we use in our authentication system.

routes.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

//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'] 

to connected with user data, We have two endpoints that we can use, both of which have their own uses. The endpoints are:

$route['api/users']['GET']          = "UsersController/all_users";
$route['api/users/(:num)']['GET']   = "UsersController/detail_user/$1";
  • API for all users

The API that we will use first is the API to check all users registered in our database, the endpoint is $route['api/users']['GET'] = "UsersController/all_users";. for that we will create a new function at UsersController.php, The function is all_users(). for more details, we can see it in the code below

UsersController.php

public function all_users() {
        return $this->response($this->user->get_all());
}
  • all_users(): According to the function that we make at the API endpoint.

  • We have created a JSON response functions dynamically, So we just use it in the following way $this->response($this->user->get_all());

  • Then in the all_user function we will create a new function in the model to retrieve all data in the database, The function is get_all(). We will make the function in the model User.php.

User.php

public function get_all(){
        $query  = $this->db->get('users');
        return $query->result();
}
  • get_all(): According to the function that we make at the UsersControllers.php.

  • $this->db->get('users');: to get all the data in the users table.

  • And we must return the result with result(). then to test the endpoint, we can run our postman and also localhost.

Screenshot_12.png

Endpoint API: $route['api/users']['GET'] = "UsersController/all_users";

ezgif.com-video-to-gif (2).gif

We can see in the picture above we have done to fetch the data of the all user, the following are the results in the form of JSON.

[
    {
        "id": "7",
        "email": "[email protected]",
        "password": "$2y$10$b/jfxikXEheyyol50qo4neRvE8NRGzZJ.Jt8eLXYJtYoHV50g3nMu",
        "created_at": "2018-10-14 22:11:56",
        "updated_at": "0000-00-00 00:00:00"
    },
    {
        "id": "8",
        "email": "[email protected]",
        "password": "$2y$10$2pPecvO6P2qADyytFiHQKuqJxzjYFX9D5C7kdStpbhWl2Etul4n5m",
        "created_at": "2018-10-16 19:19:28",
        "updated_at": "0000-00-00 00:00:00"
    }
]


  • API for detail user

Now we will continue with another user API, that is $route['api/users/(:num)']['GET'] = "UsersController/detail_user/$1";. This endpoint will be used for detail user data, If the previous endpoint we get the user with the function get_all () , in this endpoint we will fetch the user details dengan metodefunction get($id). We can see the example in UsersController.php as follows.

public function detail_user($id) {
        return $this->response($this->user->get_all($id));
}

Because we will fetch detailed data from users, we need something unique from the user data that is Id. then where do we get the parameter id that we can use in the function detailuser($id) ?

We can get it from the route API that we use, like the following:
$route['api/users/(:num)']['GET'] = "UsersController/detail_user/$1";

  • We can use(:num) to define that the parameter that we are going to pass is a number(int).

  • and after we passed the parameter we also have to accept it in the controller, we can use the method as follows UsersController/detail_user/$1.

  • to avoid repeating the functions we will make the function get_all () become dynamic by adding parameters as references get_all($id). This means we need to make changes to the get_all () function in the User.php model.

  • Dynamic function

In making an important API we remember is how we make a function that can be as dynamic as possible and can be used in all conditions. In this tutorial, I will give an overview of how to create dynamic functions based on the system authentication that we use in this tutorial. Before we created the get_all() function in models/user.php, we will now change the function We can see an example like this:

User.php

public function get_all($id = null){
        if($id != null) {
            $query  = $this->db->get_where('users', array('id' => $id));
            return $query->result();
        }
        $query  = $this->db->get('users');
        return $query->result();
    }
  • Default parameter: We will accept a parameter that is $id, but we need to know this function also allows us not to accept the parameter $id , therefore we need to create the default value of the parameter so that later there will be no error even though this function does not accept the $id. We can make it as follows $id= null. Because the parameter that we will receive the number(int) , we can set the default value is null, If the parameter is a string then we can set the default value is ' '.

  • Get Specific data: then we will use the parameter $Id in the function get_where() to select data specifically $this->db->get_where('users', array('id' => $id));. In the get_where() we have 2 parameters, the first is the table name 'users' and the second is the array key and value array('id' => $id) to match the data in the database, the key is the column name 'id' and the value we get from the $id parameter.

  • to test it we can run postman and run our localhost on the endpoint $route['api/users/(:num)']['GET'] = "UsersController/detail_user/$1";

Route: $route['api/users/(:num)']['GET'] = "UsersController/detail_user/$1";

ezgif.com-video-to-gif (3).gif

Endpoint: http://localhost/tutorial-ci/api/users/8

[
    {
        "id": "8",
        "email": "[email protected]",
        "password": "$2y$10$2pPecvO6P2qADyytFiHQKuqJxzjYFX9D5C7kdStpbhWl2Etul4n5m",
        "created_at": "2018-10-16 19:19:28",
        "updated_at": "0000-00-00 00:00:00"
    }
]



Endpoint: http://localhost/tutorial-ci/api/users/7

[
    {
        "id": "7",
        "email": "[email protected]",
        "password": "$2y$10$b/jfxikXEheyyol50qo4neRvE8NRGzZJ.Jt8eLXYJtYoHV50g3nMu",
        "created_at": "2018-10-14 22:11:56",
        "updated_at": "0000-00-00 00:00:00"
    }
]

We have succeeded in creating a new API that is related to Users and we have also learned how to make functions dynamic, in the next tutorial we will change our authentication system by using Tokens. Hopefully, this tutorial can help you. Don't forget to follow my tutorial that was previously in the curriculum below, thank you...

Curriculum

Create RESTful API with Code Igniter #1 : Basic installation, Setup configuration and Database, Create Routes API
Create RESTful API with Code Igniter #2 : Create API register, Models and Controllers, JSON Response

Proof of work done

https://github.com/milleaduski/RESTful-CI

Sort:  

Thank you for your contribution @duski.harahap.

  • In your code post comments to help the user to understand well.
  • Please improve your tutorial language, sometimes it gets a bit difficult to understand what you are explaining.

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]

thanks @portugalcoin, i'll improve it

Thank you for your review, @portugalcoin!

So far this week you've reviewed 16 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!