可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Our client had given me a REST API to which I need to make a PHP call to. But as a matter of fact the documentation given with the API is very limited, so I don\'t really know how to call the service.
I\'ve tried to Google it, but the only thing that came up was an already expired Yahoo! tutorial on how to call the service. Not mentioning the headers or anything in depth information.
Is there any decent information around how to call a REST API, or some documentation about it? Because even on W3schools, they only describes the SOAP method. What are different options for making rest API in PHP?
回答1:
You can access any REST API with PHPs cURL
Extension. However, the API Documentation (Methods, Parameters etc.) must be provided by your Client!
Example:
// Method: POST, PUT, GET etc
// Data: array(\"param\" => \"value\") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case \"POST\":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case \"PUT\":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf(\"%s?%s\", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, \"username:password\");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
回答2:
If you have a url and your php supports it, you could just call file_get_contents:
$response = file_get_contents(\'http://example.com/path/to/api/call?param1=5\');
if $response is JSON, use json_decode to turn it into php array:
$response = json_decode($response);
if $response is XML, use simple_xml class:
$response = new SimpleXMLElement($response);
http://sg2.php.net/manual/en/simplexml.examples-basic.php
回答3:
Use Guzzle. It\'s a \"PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services\". Working with Guzzle is much easier than working with cURL.
Here\'s an example from the Web site:
$client = new GuzzleHttp\\Client();
$res = $client->get(\'https://api.github.com/user\', [
\'auth\' => [\'user\', \'pass\']
]);
echo $res->getStatusCode(); // 200
echo $res->getHeader(\'content-type\'); // \'application/json; charset=utf8\'
echo $res->getBody(); // {\"type\":\"User\"...\'
var_export($res->json()); // Outputs the JSON decoded data
回答4:
CURL is the simplest way to go. Here is a simple call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, \"THE URL TO THE SERVICE\");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
回答5:
Use HTTPFUL
Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane. It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client.
Httpful includes...
- Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, and OPTIONS)
- Custom Headers
- Automatic \"Smart\" Parsing
- Automatic Payload Serialization
- Basic Auth
- Client Side Certificate Auth
- Request \"Templates\"
Ex.
Send off a GET request. Get automatically parsed JSON response.
The library notices the JSON Content-Type in the response and automatically parses the response into a native PHP object.
$uri = \"https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D\";
$response = \\Httpful\\Request::get($uri)->send();
echo \'The Dead Weather has \' . count($response->body->result->album) . \" albums.\\n\";
回答6:
There are plenty of clients actually. One of them is Pest - check this out. And keep in mind that these REST calls are simple http request with various methods: GET, POST, PUT and DELETE.
回答7:
You will need to know if the REST API you are calling supports GET
or POST
, or both methods. The code below is something that works for me, I\'m calling my own web service API, so I already know what the API takes and what it will return. It supports both GET
and POST
methods, so the less sensitive info goes into the URL (GET)
, and the info like username and password is submitted as POST
variables. Also, everything goes over the HTTPS
connection.
Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable
to make that json string availabe to the client.
So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.
This is how I connect to the API from the client side:
$processed = FALSE;
$ERROR_MESSAGE = \'\';
// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, \"http://www.myapi.com/api.php?format=json&action=subscribe&email=\" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,\"username=myname&password=mypass\"); // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);
// returned json string will look like this: {\"code\":1,\"data\":\"OK\"}
// \"code\" may contain an error code and \"data\" may contain error string instead of \"OK\"
$obj = json_decode($json);
if ($obj->{\'code\'} == \'1\')
{
$processed = TRUE;
}else{
$ERROR_MESSAGE = $obj->{\'data\'};
}
...
if (!$processed && $ERROR_MESSAGE != \'\') {
echo $ERROR_MESSAGE;
}
BTW, I also tried to use file_get_contents()
method as some of the users here suggested, but that din\'t work well for me. I found out the curl
method to be faster and more reliable.
回答8:
If you are using Symfony there\'s a great rest client bundle that even includes all of the ~100 exceptions and throws them instead of returning some meaningless error code + message.
You should really check it:
https://github.com/CircleOfNice/CiRestClientBundle
I love the interface:
try {
$restClient = new RestClient();
$response = $restClient->get(\'http://www.someUrl.com\');
$statusCode = $response->getStatusCode();
$content = $response->getContent();
} catch(OperationTimedOutException $e) {
// do something
}
Works for all http methods.
回答9:
If you are open to use third party tools you\'d have a look at this one:
https://github.com/CircleOfNice/DoctrineRestDriver
This is a completely new way to work with APIs.
First of all you define an entity which is defining the structure of incoming and outcoming data and annotate it with datasources:
/*
* @Entity
* @DataSource\\Select(\"http://www.myApi.com/products/{id}\")
* @DataSource\\Insert(\"http://www.myApi.com/products\")
* @DataSource\\Select(\"http://www.myApi.com/products/update/{id}\")
* @DataSource\\Fetch(\"http://www.myApi.com/products\")
* @DataSource\\Delete(\"http://www.myApi.com/products/delete/{id}\")
*/
class Product {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
Now it\'s pretty easy to communicate with the REST API:
$product = new Product();
$product->setName(\'test\');
// sends an API request POST http://www.myApi.com/products ...
$em->persist($product);
$em->flush();
$product->setName(\'newName\');
// sends an API request UPDATE http://www.myApi.com/products/update/1 ...
$em->flush();
回答10:
as @Christoph Winkler mentioned this is a base class for achieving it:
curl_helper.php
// This class has all the necessary code for making API calls thru curl library
class CurlHelper {
// This method will perform an action/method thru HTTP/API calls
// Parameter description:
// Method= POST, PUT, GET etc
// Data= array(\"param\" => \"value\") ==> index.php?param=value
public static function perform_http_request($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case \"POST\":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case \"PUT\":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf(\"%s?%s\", $url, http_build_query($data));
}
// Optional Authentication:
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($curl, CURLOPT_USERPWD, \"username:password\");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
}
Then you can always include the file and use it e.g.: any.php
require_once(\"curl_helper.php\");
...
$action = \"GET\";
$url = \"api.server.com/model\"
echo \"Trying to reach ...\";
echo $url;
$parameters = array(\"param\" => \"value\");
$result = CurlHelper::perform_http_request($action, $url, $parameters);
echo print_r($result)
回答11:
You can go with POSTMAN, an application who makes APIs easy.
Fill request fields and then it will generate code for you in different languages.
Just click code on the right side and select your prefered language.
回答12:
You can use file_get_contents
to issue any http POST/PUT/DELETE/OPTIONS/HEAD
methods, in addition to the GET
method as the function name suggests.
How to post data in PHP using file_get_contents?