RESTful API를 구축하는 방법은 무엇입니까?
문제는 이것이다 : PHP 서버에서 실행되는 웹 애플리케이션이 있습니다. 이를위한 REST API를 만들고 싶습니다.
몇 가지 조사를 수행 한 결과 REST API가 인증 키 (반드시 아님)가있는 특정 URI에 대해 HTTP 메서드 (GET, POST ...)를 사용하고 정보가 XML 또는 JSON 정보와 함께 HTTP 응답으로 다시 제공된다는 사실을 알아 냈습니다. (차라리 JSON).
내 질문은 :
- 앱 개발자로서 URI를 어떻게 빌드합니까? 해당 URI에 PHP 코드를 작성해야합니까?
- 응답으로 반환 할 JSON 개체를 어떻게 빌드합니까?
다음은 간단한 PHP의 아주 간단한 예입니다.
client.php 및 api.php 두 파일이 있습니다 . 두 파일을 동일한 URL에 넣었 http://localhost:8888/
으므로 링크를 자신의 URL로 변경해야합니다. (파일은 두 개의 다른 서버에있을 수 있습니다.)
이것은 단지 예일 뿐이며 매우 빠르고 더럽습니다. 또한 PHP를 사용한 지 오래되었습니다. 그러나 이것은 API의 아이디어입니다.
client.php
<?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.php
<?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 웹 사이트의 일반적인 패턴은 다음과 같습니다.
- 사용자가 URL을 입력
- The server get the url, parse it and execute a action
- In this action, you get/generate every information you need for the page
- You create the html/php page with the info from the action
- The server generate a fully html page and send it back to the user
With a api, you just add a new step between 3 and 4. After 3, create a array with all information you need. Encode this array in json and exit or return this value.
$info = array("info_1" => 1; "info_2" => "info_2" ... "info_n" => array(1,2,3));
exit(json_encode($info));
That all for the api. For the client side, you can call the api by the url. If the api work only with get call, I think it's possible to do a simply (To check, I normally use curl).
$info = file_get_contents(url);
$info = json_decode($info);
But it's more common to use the curl library to perform get and post call. You can ask me if you need help with curl.
Once the get the info from the api, you can do the 4 & 5 steps.
Look the php doc for json function and file_get_contents.
curl : http://fr.php.net/manual/fr/ref.curl.php
EDIT
No, wait, I don't get it. "php API page" what do you mean by that ?
The api is only the creation/recuperation of your project. You NEVER send directly the html result (if you're making a website) throw a api. You call the api with the url, the api return information, you use this information to create the final result.
ex: you want to write a html page who say hello xxx. But to get the name of the user, you have to get the info from the api.
So let's say your api have a function who have user_id as argument and return the name of this user (let's say getUserNameById(user_id)), and you call this function only on a url like your/api/ulr/getUser/id.
Function getUserNameById(user_id)
{
$userName = // call in db to get the user
exit(json_encode($userName)); // maybe return work as well.
}
From the client side you do
$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>
So the client never access directly the databases, that the api's role.
Is that clearer ?
(1) How do I ... build those URI's? Do I need to write a PHP code at that URI?
There is no standard for how an API URI scheme should be set up, but it's common to have slash-separated values. For this you can use...
$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
...to get an array of slash-separated values in the URI after the file name.
Example: Assuming you have an API file api.php
in your application somewhere and you do a request for api.php/members/3
, then $apiArgArray
will be an array containing ['members', '3']
. You can then use those values to query your database or do other processing.
(2) How do I build the JSON objects to return as a response?
You can take any PHP object and turn it into JSON with json_encode. You'll also want to set the appropriate header.
header('Content-Type: application/json');
$myObject = (object) array( 'property' => 'value' ); // example
echo json_encode($myObject); // outputs JSON text
All this is good for an API that returns JSON, but the next question you should ask is:
(3) How do I make my API RESTful?
For that we'll use $_SERVER['REQUEST_METHOD']
to get the method being used, and then do different things based on that. So the final result is something like...
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);
Sources: https://stackoverflow.com/a/897311/1766230 and http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services
Another framework which has not been mentioned so far is Laravel. It's great for building PHP apps in general but thanks to the great router it's really comfortable and simple to build rich APIs. It might not be that slim as Slim or Sliex but it gives you a solid structure.
See Aaron Kuzemchak - Simple API Development With Laravel on YouTube and
Laravel 4: A Start at a RESTful API on NetTuts+
I know that this question is accepted and has a bit of age but this might be helpful for some people who still find it relevant. Although the outcome is not a full RESTful API the API Builder mini lib for PHP allows you to easily transform MySQL databases into web accessible JSON APIs.
As simon marc said, the process is much the same as it is for you or I browsing a website. If you are comfortable with using the Zend framework, there are some easy to follow tutorials to that make life quite easy to set things up. The hardest part of building a restful api is the design of the it, and making it truly restful, think CRUD in database terms.
It could be that you really want an xmlrpc interface or something else similar. What do you want this interface to allow you to do?
--EDIT
Here is where I got started with restful api and Zend Framework. Zend Framework Example
In short don't use Zend rest server, it's obsolete.
참고URL : https://stackoverflow.com/questions/4684075/how-to-build-a-restful-api
'development' 카테고리의 다른 글
Git에서 원격 브랜치를 어떻게 삭제합니까? (0) | 2020.10.24 |
---|---|
Rails has_many 관계에서 기본적으로 범위 사용 (0) | 2020.10.24 |
주어진 데코레이터로 파이썬 클래스의 모든 메소드를 얻는 방법 (0) | 2020.10.24 |
jQuery .val () 대 .attr ( "값") (0) | 2020.10.24 |
키보드 상호 작용없이 gpg 암호화 파일 (0) | 2020.10.24 |