programing

RESTful API 구축 방법

goodcopy 2022. 11. 7. 22:54
반응형

RESTful API 구축 방법

을 사용하다PHP 서버에서 실행되는 웹 응용 프로그램이 있습니다.REST api 를 。
조사를 해보니 REST api는 인증키를 가진 특정 URI에 HTTP 메서드(GET, POST...)를 사용하고 있으며, 정보는 XML 또는 JSON(JSON)으로 HTTP 응답으로 반환됩니다.

질문입니다.

  1. 앱 개발자로서 어떻게 URI를 구축하면 좋을까요?그 URI에 PHP 코드를 써야 하나요?
  2. 응답으로 반환되는 JSON 개체를 작성하려면 어떻게 해야 합니까?

여기 간단한 php의 예가 있습니다.

파일 클라이언트는 2개입니다.php api.disples참조하십시오.두 파일을 같은 URL에 저장했습니다.http://localhost:8888/URL의 다른).(파일은 2개의 다른 서버에 배치할 수 있습니다).

이것은 하나의 예에 불과하고, 매우 빠르고 지저분하며, 게다가 php를 한 지 오래되었습니다.하지만 이것은 api의 아이디어입니다.

client.displaces를 설정합니다.

<?php

/*** this is the client ***/


if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_user") // if the get parameter action is get_user and if the id is set, call the api to get the user information
{
  $user_info = file_get_contents('http://localhost:8888/api.php?action=get_user&id=' . $_GET["id"]);
  $user_info = json_decode($user_info, true);

  // THAT IS VERY QUICK AND DIRTY !!!!!
  ?>
    <table>
      <tr>
        <td>Name: </td><td> <?php echo $user_info["last_name"] ?></td>
      </tr>
      <tr>
        <td>First Name: </td><td> <?php echo $user_info["first_name"] ?></td>
      </tr>
      <tr>
        <td>Age: </td><td> <?php echo $user_info["age"] ?></td>
      </tr>
    </table>
    <a href="http://localhost:8888/client.php?action=get_userlist" alt="user list">Return to the user list</a>
  <?php
}
else // else take the user list
{
  $user_list = file_get_contents('http://localhost:8888/api.php?action=get_user_list');
  $user_list = json_decode($user_list, true);
  // THAT IS VERY QUICK AND DIRTY !!!!!
  ?>
    <ul>
    <?php foreach ($user_list as $user): ?>
      <li>
        <a href=<?php echo "http://localhost:8888/client.php?action=get_user&id=" . $user["id"]  ?> alt=<?php echo "user_" . $user_["id"] ?>><?php echo $user["name"] ?></a>
    </li>
    <?php endforeach; ?>
    </ul>
  <?php
}

?>

api.module

<?php

// This is the API to possibility show the user list, and show a specific user by action.

function get_user_by_id($id)
{
  $user_info = array();

  // make a call in db.
  switch ($id){
    case 1:
      $user_info = array("first_name" => "Marc", "last_name" => "Simon", "age" => 21); // let's say first_name, last_name, age
      break;
    case 2:
      $user_info = array("first_name" => "Frederic", "last_name" => "Zannetie", "age" => 24);
      break;
    case 3:
      $user_info = array("first_name" => "Laure", "last_name" => "Carbonnel", "age" => 45);
      break;
  }

  return $user_info;
}

function get_user_list()
{
  $user_list = array(array("id" => 1, "name" => "Simon"), array("id" => 2, "name" => "Zannetie"), array("id" => 3, "name" => "Carbonnel")); // call in db, here I make a list of 3 users.

  return $user_list;
}

$possible_url = array("get_user_list", "get_user");

$value = "An error has occurred";

if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))
{
  switch ($_GET["action"])
    {
      case "get_user_list":
        $value = get_user_list();
        break;
      case "get_user":
        if (isset($_GET["id"]))
          $value = get_user_by_id($_GET["id"]);
        else
          $value = "Missing argument";
        break;
    }
}

exit(json_encode($value));

?>

이 예에서는 데이터베이스에 콜을 발신하지 않았지만, 보통은 그렇게 해야 합니다.또한 "file_get_contents" 함수를 "curl"로 대체해야 합니다.

2013년에는 Silex나 Slim 같은 것을 사용해야 합니다.

Silex의 예:

require_once __DIR__.'/../vendor/autoload.php'; 

$app = new Silex\Application(); 

$app->get('/hello/{name}', function($name) use($app) { 
    return 'Hello '.$app->escape($name); 
}); 

$app->run(); 

슬림한 예:

$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
    echo "Hello, $name";
});
$app->run();

그것은 일반 웹사이트를 만든 것과 거의 같다.

php 웹사이트의 일반적인 패턴은 다음과 같습니다.

  1. 사용자가 URL을 입력합니다.
  2. 서버가 URL을 가져와 해석하고 액션을 실행합니다.
  3. 이 작업에서는 페이지에 필요한 모든 정보를 수집/생성합니다.
  4. 액션의 정보를 사용하여html/php 페이지를 만듭니다.
  5. 서버는 완전한 html 페이지를 생성하여 사용자에게 반송합니다.

api를 사용하면 3과 4 사이에 새로운 단계를 추가할 수 있습니다.3 뒤에 필요한 정보를 모두 포함하는 어레이를 만듭니다.이 어레이를 json으로 인코딩하고 이 값을 종료하거나 반환합니다.

$info = array("info_1" => 1; "info_2" => "info_2" ... "info_n" => array(1,2,3));
exit(json_encode($info));

API는 여기까지입니다.클라이언트 측에서는 api를 URL로 호출할 수 있습니다.api가 get call만으로 동작한다면 간단하게 할 수 있다고 생각합니다(확인하기 위해서는 보통 curl을 사용하고 있습니다.

$info = file_get_contents(url);
$info = json_decode($info);

그러나 Get 및 Post Call을 수행하기 위해 컬 라이브러리를 사용하는 것이 일반적입니다.컬링에 도움이 필요하시면 말씀하세요.

API에서 정보를 가져오면 4단계와 5단계를 수행할 수 있습니다.

php 문서에서 json 함수와 file_get_contents를 찾습니다.

컬 : http://fr.php.net/manual/fr/ref.curl.php


편집

아니, 잠깐만, 이해가 안 돼."php API 페이지"는 무슨 뜻입니까?

api는 프로젝트의 작성/복제일 뿐입니다.html 결과(웹사이트를 만드는 경우)를 직접 전송하지 않습니다.url과 함께 api를 호출하고 api 반환 정보를 사용하여 최종 결과를 작성합니다.

ex: 인사하는 html 페이지를 작성하려고 합니다.그러나 사용자의 이름을 얻으려면 api에서 정보를 얻어야 합니다.

예를 들어 user_id를 인수로 하여 이 사용자의 이름을 반환하는 함수가 api/ulr/getUser/id와 같은 URL에서만 이 함수를 호출한다고 가정합니다.

Function getUserNameById(user_id)
{
  $userName = // call in db to get the user
  exit(json_encode($userName)); // maybe return work as well.
}

클라이언트 측에서는

    $username = file_get_contents(your/api/url/getUser/15); // You should normally use curl, but it simpler for the example
// So this function to this specifique url will call the api, and trigger the getUserNameById(user_id), whom give you the user name.
    <html>
    <body>
    <p>hello <?php echo $username ?> </p>
    </body>
    </html>

따라서 클라이언트는 api의 역할인 데이터베이스에 직접 액세스하지 않습니다.

더 명확해졌나요?

(1) 이러한 URI를 어떻게 구축하면 좋을까요?그 URI에 PHP 코드를 써야 하나요?

API URI 스킴의 설정 방법에 대한 표준은 없지만 슬래시로 구분된 값이 있는 것이 일반적입니다.이 경우 사용할 수 있습니다.

$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));

파일 이름 뒤에 슬래시로 구분된 값의 배열을 URI에서 가져옵니다.

: : 파일 API가 합니다.api.php해 주세요.api.php/members/3 , , , 「 」$apiArgArray 포함하는 .['members', '3']그런 다음 이러한 값을 사용하여 데이터베이스를 쿼리하거나 다른 처리를 수행할 수 있습니다.

(2) 응답으로 반환하는 JSON 오브젝트를 작성하려면 어떻게 해야 합니까?

임의의 PHP 객체를 json_encode를 사용하여 JSON으로 변환할 수 있습니다.적절한 헤더를 설정할 수도 있습니다.

header('Content-Type: application/json');
$myObject = (object) array( 'property' => 'value' ); // example
echo json_encode($myObject); // outputs JSON text

JSON을 반환하는 API에서는 이 모든 것이 좋지만 다음 질문은 다음과 같습니다.

(3) API를 RESTFul로 만들려면 어떻게 해야 하나요?

위해서는 러러해 for를 합니다.$_SERVER['REQUEST_METHOD']그 방법을 사용하고, 그것을 바탕으로 다른 일을 할 수 있습니다.★★★★★★★★★★★★★★...

header('Content-Type: application/json');
$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
$returnObject = (object) array();
/* Based on the method, use the arguments to figure out
   whether you're working with an individual or a collection, 
   then do your processing, and ultimately set $returnObject */
switch ($_SERVER['REQUEST_METHOD']) {
  case 'GET':
    // List entire collection or retrieve individual member
    break;
  case 'PUT':       
    // Replace entire collection or member
    break;  
  case 'POST':      
    // Create new member
    break;
  case 'DELETE':    
    // Delete collection or member
    break;
}
echo json_encode($returnObject);

출처 : https://stackoverflow.com/a/897311/1766230 및 http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services

지금까지 언급되지 않은 또 다른 프레임워크는 라라벨이다.일반적으로 PHP 앱을 구축하는데 매우 유용하지만, 훌륭한 라우터 덕분에 풍부한 API를 구축하기가 매우 쉽고 편리합니다.슬림이나 Sliex만큼 슬림하지는 않지만 견고한 구조를 제공합니다.

Aaron Kuzemchak - YouTube에서 Larabel을 사용한 간단한 API 개발

Larabel 4: NetTuts+ RESTful API 시작

나는 이 질문이 받아들여지고 나이가 좀 있다는 것을 알지만, 이것은 여전히 관련이 있다고 생각하는 사람들에게 도움이 될 수 있다.결과는 완전한 RESTful API는 아니지만 API Builder mini lib for PHP를 사용하면 MySQL 데이터베이스를 웹 액세스 가능한 JSON API로 쉽게 변환할 수 있습니다.

simon marc가 말했듯이, 그 과정은 당신이나 내가 웹사이트를 브라우징하는 것과 거의 동일합니다.Zend 프레임워크를 사용하는 데 익숙하다면, 설정하기 쉬운 튜토리얼이 몇 가지 있습니다.restful api를 구축하는 데 있어 가장 어려운 부분은 api의 설계이며, 이를 진정으로 편안하게 하기 위해서는 데이터베이스 용어로 CRUD를 생각할 수 있습니다.

xmlrpc 인터페이스 또는 이와 유사한 인터페이스가 정말로 필요한 경우가 있습니다.이 인터페이스로 무엇을 할 수 있을까요?

--편집

여기서부터 Restful api와 Zend Framework를 시작하였습니다.Zend 프레임워크 예시

즉, Zend Rest 서버를 사용하지 마십시오. 더 이상 사용되지 않습니다.

언급URL : https://stackoverflow.com/questions/4684075/how-to-build-a-restful-api

반응형