Using CodeIgniter to create the RESTful service REST API

Source: Internet
Author: User
Tags error code require response code codeigniter

Introduced
In this day and age, you can easily integrate services such as BLOG,CMS and so on to your website. One thing you might not have thought about was using CodeIgniter to create API interfaces. After trying several implementations of the RESTful service, I found the process very cumbersome and lacked some of the restful features you expected. So I built one myself, and this tutorial will show you how to use the code to create your own rest API, and I'll give you some examples of how to interact with your own API.


Assume
You have your own Web server, either local localhost or online, and you know how to manage the file inside.
You have to read the CodeIgniter from scratch tutorial, which is to know how to use the CodeIgniter framework.
Know how to set up CodeIgniter
Know a little RESTful service knowledge
This tutorial will be divided into 2 sections. The first part will start with learning how to build restful services, then go deep, and the second part will talk about how to interact with your own rest API in a variety of ways.

Part I-Creating the rest API

The first step: Set up Demo
First, you'll need to download a copy of codeigniter-restserver code from git. Extract the inside of the code, placed in your Web server (translator Note: The download method as shown, the original author's picture is git before the revision, does not apply to the present, so I ventured to replace it)

After the download is unpacked, you will find that this is already a complete codeigniter framework. This allows you to use this REST demo completely without having to add it to your own file.

Open "application/config/config.php" , set Base_url According to your own situation. ( Translator Note: In fact, is the root directory of CI address, this I want to use CI of all understand it.) If you really do not understand anything, then you download the file back after decompression, and then renamed to Restserver, the entire folder to the WWW root directory, the Base_url set as shown in the picture

Step two: Learn about URLs
According to the first step, unzip the good file, configure good base_url, we have access to the CodeIgniter framework has been configured well restful. Open your Web server, enter the Base_url address you just set up, and see if you can access it properly.
The following explains the restful URL structure. The basic situation is as shown in the figure:
( Translator Note: The situation here I do not say much, just said restful codeigniter and normal situation of the URL structure differences, the previous value and URL structure are consistent with the normal situation, is the last added a parameter format, Here you can define the type returned )
For the type of format, you can look at the following figure
In order for the API to provide richer format choices ... The format type is not only the 3 cases listed above, but the specific types are as follows:
    • XML – XML format is recognized in almost all languages
    • JSON – Useful for JavaScript and PHP apps. ( Translator Note: There is actually a JSONP format )
    • CSV – can be opened by the spreadsheet program
    • HTML – not explained
    • PHP -returned PHP can be executed by the Eval function
    • serialized -serialization format, very useful for PHP ( Translator Note: Original error, remember that there is a D end )
A more restful way of sending Content-type HTTP headers will be mentioned later.
Step three: Understand the code
Now, you open " application/controllers/example_api.php" and you will immediately find something different from the normal CodeIgniter controller.
Rest_controller
In the MVC pattern, the controller is the center of the logical operation. The controller's methods are invoked when the user requests or obtains data from the controller or when it needs to output HTML. CodeIgniter has its own logic to direct the controller to how it works, but we are now in a different situation than CodeIgniter, and we need our Rest_controller class to command related rest logic operations, so we need to inherit Rest_ Controller this controller.
Normally, our controller is like this.
  1. <?php
  2. class Example_api extends Controller {
  3. }
Now we need to become like this
  1. <?php  
  2. require
  3.  
  4. class Example_api extends Rest_controller {  
  5. &NBSP;
  6. }  
( Translator Note: Can only require Rest_controller cannot join autoload inside, as for why, rub, I also do not understand )
Add method
Now that you've built an empty controller, let's start adding some methods in. In general, you want to name the method name based on the resources you need and the corresponding HTTP operation. So, in the following code you will see the user and users 2 methods.
  1. <?php
  2. require   (AppPath '. libraries/rest_controller.php ');
  3. class Example_api extends Rest_controller {
  4. function user_get ()
  5. {
  6. //Return information about 1 users
  7. }
  8. function users_get ()
  9. {
  10. //return information for all users
  11. }
  12. }
This may seem odd, but it lets you respond to different actions based on the actual HTTP request using an identical URL. If someone uses a method you do not allow to invoke your API, it will automatically return a 404 error code. If you don't understand the HTTP action, let me explain:
Get

Do not explain

POST
Do not explain
Put

A less-used HTTP action is not supported by most browsers, and put action is used to create a resource. ( Translator Note: corresponds to delete )

DELETE

As with put, it is rarely used. The delete action is used to remove a resource.

( Translator Note: In fact, Get,post already can completely replace the function of put and delete, so the following 2 actions are very rarely used )

If we change the code above to allow each HTTP action to respond to a resource requesting user, you can write this:
  1. <?php
  2. require   (AppPath '. libraries/rest_controller.php ');
  3. class Example_api extends Rest_controller {
  4. function user_get ()
  5. {
  6. //respond with information about a user
  7. //Return a user information
  8. }
  9. function user_put ()
  10. {
  11. //Create a new user and respond with a status/errors
  12. //Create a new user and return the corresponding status code
  13. }
  14. function user_post ()
  15. {
  16. //Update an existing user and respond with a status/errors
  17. //Update an existing user information and return the corresponding status code
  18. }
  19. function user_delete ()
  20. {
  21. //Delete a user and respond with a status/errors
  22. //delete a user and return response status code
  23. }
  24. }
Accept parameters and return data
So, now the controller has added appropriate methods to respond to different HTTP actions, we now need to accept some parameters, and then we can use the CodeIgniter model and library methods. Because of this benefit, we use CodeIgniter to build our API, and of course we can use the models and Libraryies methods that exist in our projects without having to write them again.
  1. <?php
  2. require   (AppPath '. libraries/rest_controller.php ');
  3. class Example_api extends Rest_controller {
  4. function user_get ()
  5. {
  6. $data = array(' returned: '). $this   ->get (' id '));
  7. $this->response ($data);
  8. }
  9. &nbsp
    ; function user_post ()
  10. {
  11. $data = array(' returned: '). $this   ->post (' id '));
  12. $this->response ($data);
  13. }
  14. function user_put ()
  15. {
  16. $data = array(' returned: '). $this   ->put (' id '));
  17. $this->response ($data;
  18. }
  19. function user_delete ()
  20. {
  21. $data = array(' returned: '). $this -> Delete   (' id '));
  22. $this->response ($data);
  23. }
  24. }
$this->get ()
Used to receive a get parameter
$this->post ()
is an alias for the CodeIgniter built-in method $this->input->post () that receives $_post parameters and is subject to XSS protection.
$this->put ()

Receive put parameter

$this->delete ()
Receive Delete parameter
$this->response ()
Send data to the browser, what is the data format, the default is XML format, you can set the return of the HTTP status code, such as the user example, add ID does not exist, you can use $this->response (' Error ' => ' user not Found. '), 404);

Step Fourth: Use your models.
From the beginning to the present, a simple demo API is ready to work. So, next, let's run these APIs with our own models.
From the downloaded CodeIgniter, find the 2 files shown above, in the following locations:
    • application/config/rest.php
    • application/libraries/rest_controller.php
Copy these 2 files into your existing project and keep the position unchanged. The full project below the controller demo
  1. <?php
  2. require (AppPath. ')   /libraries/rest_controller.php ');
  3. class Api extends Rest_controller
  4. {
  5. function user_get ()
  6. {
  7. if(! $this ->get (' id '))
  8. {
  9. $this->response (NULL, 400);
  10. }
  11. $user = $this->user_model->get ( $this->get (' ID   ’) );
  12. if($user)
  13. {
  14. $this->response ($user); //Being the HTTP response code
  15. }
  16. Else
  17. {
  18. $this->response (NULL, 404);
  19. }
  20. }
  21. function user_post ()
  22. {
  23. $result = $this->user_model->update ( $this->p OST (' ID '), array(
  24. ' name ' => $this ->post (' name '),
  25. ' email ' => $this ->post (' email ')
  26. ));
  27. if($result = = FALSE) &
    nbsp
  28. {
  29. $this->response (' status ' => ' failed '));
  30. }
  31. Else
  32. {
  33. $this->response (' status ' => ' success '));
  34. }
  35. }
  36. function users_get ()
  37. {
  38. $users = $this->user_model->get_all ();
  39. if($users)
  40. {
  41. $this->response ($users, 200);
  42. }
  43. Else
  44. {
  45. $this->response (NULL, 404);
  46. }
  47. }
  48. }
  49. ?>
This is a generic demo, in the first method, we first judge whether there is an ID this parameter, if there is no return 400 status code, if there is to continue to execute, let User_model to get user, there is return data, and return 200 status code, Null and 404 status Codes are not returned.
Fifth Step: API security
Now, your API has been set up. You need to give the appropriate invocation authority to protect it. Set login permissions, username and password can open "application/config/rest.php" file to modify.
    1. $config [' rest_auth '] = ' basic '; //Set rest permissions
None

If set to none, everyone can call this API.

Basic

If set to basic, it is a relatively insecure login method that should be used only for internal/security networks.

Digest

This is a more secure option that requires an encrypted username and password, and if you want the protected API to be invoked by someone with permission, use this option.

    1. $config [' rest_valid_logins '] = Array (' admin ' => ' 1234′);
This option, you can set the user's account and password, the account number is the key of the array, the password is the corresponding value; You can add as many users as you have permission to call your API in.
( Translator Note: The first part ends here ... A little tired, the second part of the next translation ... Notice that the next section focuses on creating publicly invoked rest APIs, such as the Twitter API, the Sina API, and so on .

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.