본문으로 바로가기

CI 다운로드

codeigniter.com/download 

 

Download CodeIgniter

CodeIgniter comes in three flavors: CodeIgniter 3 (current), CodeIgniter 4 (future) and CodeIgniter 2 (legacy) CodeIgniter 2 CodeIgniter 2.2.6 is the legacy version of the framework. The 2.x branch was originally released January 2011, and the last version

codeigniter.com

 

 

php ver : 5.6.8

CI ver : 3.1.11

궁극적으로 사용할 API controller : controller/v1/Users.php

 

 

관련 코드 다운로드

github.com/chriskacerguis/codeigniter-restserver/releases

 

codeigniter-restserver-3.0.0.zip
3.26MB

3.0.0 다운로드 (이후 버전은 composer 사용)

 

 

내 서버에 파일 적용 

/application/config/rest.php

/application/controllers/api (디렉토리 전체)

/application/controllers/api/Rest_server.php  

/application/language/english/rest_controller_lang.php (다른언어가 필요하다면 각 언어팩의 해당 파일)

/application/libraries/Format.php

/application/libraries/REST_Controller.php

/application/views/rest_server.php

 

 

CI 에서 index.php 제거

/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond $1 !^(index\.php|images|captcha|data|include|uploads|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /api/v1/index.php/$1 [L]
</IfModule>

 

URL 설정 (URL을 특정해서 사용한다면)

/application/config/config.php

$config['base_url'] = 'http://localhost:8189';

이걸 안해주면 샘플 링크의 주소가 http://127.0.0.1 로 기본적용됨

 

 

http://localhost:8189/api/ 호출시 적용할 Controller

/application/config/routes.php

//http://localhost:8189/api/ 호출시 적용할 Controller
$route['api'] = 'Rest_server';

 

샘플 페이지 접속 확인

http://localhost:8189/api/

 

 

< 궁극적인 목적 >

/application/controllers/v1 디렉토리 생성

/application/controllers/v1/Users.php 생성 후 /application/controllers/api/Example.php 복사

 

http://localhost:8189/v1/users/all 형식으로 호출 (all 함수를 사용할 경우)

 

Routes.php 를 사용해서 URI와 함수명을 다르게 매치 시켜줄수 있음

함수명에 _(언더바)를 사용한 경우 URI를 따로 매치 가능

//v1 Route
$route['v1/users/all'] = 'v1/Users/all_users';

 

 

 

 

 

CORS 설정

 

/application/config/rest.php

//외부 접속 허용, true로 설정하지 않으면 405오류 발생
$config['check_cors'] = TRUE;


//헤더를 추가할경우 여기에 추가해 줘야 함
$config['allowed_cors_headers'] = [
  'Origin',
  'X-Requested-With',
  'Content-Type',
  'Accept',
  'Access-Control-Request-Method',
  'Authorization'
];


//클라이언트 주소 설정
$config['allowed_cors_origins'] = ['http://www.abc.com'];

 

controllers

/**
     * @method : GET
     */
    public function goods_list_get()
    {
        header("Access-Control-Allow-Origin:*");

        $data = $this->ProductsMdl->select_products();

        if($data){
            $this->response($data);
        }else{
            $message = array(
                'status' => false,
                'message' => "Data Null",
            );
            $this->response($message, REST_Controller::HTTP_NOT_FOUND);
        }

    }

 

 

 

 

클라이언트

$(document).ready(function(){
        var token = localStorage.getItem("token");

        $.ajax({
            url:'<?=$this->config->item('server_url');?>/v1/product/list', //request 보낼 서버의 경로
            type:'get', // 메소드(get, post, put 등)
            dataType: "json",
            async: false, //동기: false, 비동기(기본값): ture
            //data:{'변수 key':'변수 value'}, //보낼 데이터,
            timeout: 2000,
            headers: {
                "Content-type":"application/x-www-form-urlencoded",
                "Authorization":token
            },
            success: function(data) {
            	//성공
                console.log("data>>"+data);
            },
            error: function(err) {
                //서버로부터 응답이 정상적으로 처리되지 못햇을 때 실행
            }
        });

});

 

 

 

 

 

<추가>

Json을 보다 편하게 보기 위해서 크롬 + Json view extention 사용하면 좋음

 

 

 

 

<RestApi 참고>

CRUD

HTTP

URI

전체 리소스 조회

GET

/resources

특정 리소스 조회

GET

/resources/:id

리소스 생성

POST

/resources

리소스 전체 수정

PUT

/resources/:id

리소스 일부 수정

PATCH

/resources/:id

특정 리소스 삭제

DELETE

/resources/:id

  • GET: 조회 (받겠다)
  • POST: 리소스 생성 (보내겠다)
  • PUT: 리소스 전체 갱신(놓겠다/넣겠다)
  • PATCH: 리소스 부분 갱신(붙이겠다)
  • DELETE: 리소스 삭제 (지정한 서버의 파일을 삭제하겠다)
  1. URI 경로에는 소문자사용.
  2. 가독성을 높이기 위해 하이픈(-)을 사용할 수 있으나 언더바(_)를 사용하지 않음.
  3. URI의 마지막엔 슬래시(/)를 포함하지 않음.
  4. HTTP Method나 동사표현이 URI에 들어가면 안됨.
  5. 파일 확장자는 URI에 포함시키지 않는다.

 

참조

meetup.toast.com/posts/92

spoqa.github.io/2013/06/11/more-restful-interface.html