- Saved searches
- Use saved searches to filter your results more quickly
- License
- tcdent/php-restclient
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.markdown
- PHP Consume External REST APIs
- Prerequisites
- Project Directory
- CURL Helper
- Call External REST APIs
- Testing – Call External REST APIs
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A generic REST API client for PHP
License
tcdent/php-restclient
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.markdown
Requires PHP 7.2 or above. Use 0.1.7 for legacy versions of PHP.
$ composer require tcdent/php-restclient
$api = new RestClient([ 'base_url' => "https://api.twitter.com/1.1", 'format' => "json", // https://dev.twitter.com/docs/auth/application-only-auth 'headers' => ['Authorization' => 'Bearer '.OAUTH_BEARER], ]); $result = $api->get("search/tweets", ['q' => "#php"]); // GET http://api.twitter.com/1.1/search/tweets.json?q=%23php if($result->info->http_code == 200) var_dump($result->decode_response());
headers — An associative array of HTTP headers and values to be included in every request.
parameters — An associative array of URL or body parameters to be included in every request.
curl_options — cURL options to apply to every request; anything defined here: https://secure.php.net/manual/en/function.curl-setopt.php. These will override any automatically generated values.
build_indexed_queries (bool) — http_build_query automatically adds an array index to repeated parameters which is not desirable on most systems. Use this option to enable the default behavior. Defaults to FALSE . user_agent — User agent string to use in requests.
base_url — URL to use for the base of each request.
format — Format string is appended to resource on request (extension), and used to determine which decoder to use on response; a request URL like «api.twitter.com/1.1/statuses/user_timeline.json» would be expected to return well-formed JSON.
format_regex — Pattern to extract format from response Content-Type header, used to determine which decoder to use on response.
decoders — Associative array of format decoders. See «Direct Iteration and Response Decoding».
username — Username to use for HTTP basic authentication. Requires password .
password — Password to use for HTTP basic authentication. Requires username .
Options can be set upon instantiation, or individually afterword:
$api = new RestClient([ 'format' => "json", 'user_agent' => "my-application/0.1" ]);
$api = new RestClient; $api->set_option('format', "json"); $api->set_option('user_agent', "my-application/0.1");
Four HTTP verbs are implemented as convenience methods: get() , post() , put() and delete() . Each accepts three arguments:
url (string) — URL of the resource you are requesting. Will be prepended with the value of the base_url option, if it has been configured. Will be appended with the value of the format option, if it has been configured.
parameters (string), (array) — String or associative array to be appended to the URL in GET requests and passed in the request body on all others. If an array is passed it will be encoded into a query string. A nested, indexed array is passed for parameters with multiple values and will be iterated to populate duplicate keys See: «Duplicate Headers and Parameters»
headers (array) — An associative array of headers to include with the request. A nested, indexed array is passed for parameters with multiple values and will be iterated to populate duplicate keys See: «Duplicate Headers and Parameters»
You can make a request using any verb by calling execute() directly, which accepts four arguments: url , method , parameters and headers . All arguments expect the same values as in the convenience methods, with the exception of the additional method argument:
method (string) — HTTP verb to perform the request with.
After making a request with one of the HTTP verb methods, or execute , the returned instance will have the following data populated:
response (string) — The raw response body content. See «Direct Iteration and Response Decoding» for ways to parse and access this data.
headers (object) — An object with all of the response headers populated. Indexes are transformed to snake_case for access. Duplicate headers are available as an indexed array under the shared key.
$response->headers->content_type; $response->headers->x_powered_by;
info (object) — An object with information about the transaction. Populated by casting curl_info to an object. See PHP documentation for more info: http://php.net/manual/en/function.curl-getinfo.php Available attributes are:
url, content_type, http_code, header_size, request_size, filetime, ssl_verify_result, redirect_count, total_time, namelookup_time, connect_time, pretransfer_time, size_upload, size_download, speed_download, speed_upload, download_content_length, upload_content_length, starttransfer_time, redirect_time, certinfo, primary_ip, primary_port, local_ip, local_port, redirect_url
error (string) — cURL error message, if applicable.
response_status_lines (array) — Indexed array of raw HTTP response status lines. See: «Multiple HTTP Status Lines».
Direct Iteration and Response Decoding
If the the response data format is supported, the response will be decoded and accessible by iterating over the returned instance. When the format option is set, it will be used to select the decoder. If no format option is provided, an attempt is made to extract it from the response Content-Type header. This pattern is configurable with the format_regex option.
$api = new RestClient([ 'base_url' => "http://vimeo.com/api/v2", 'format' => "php" ]); $result = $api->get("tcdent/info"); // GET http://vimeo.com/api/v2/tcdent/info.php foreach($result as $key => $value) var_dump($value);
Reading via ArrayAccess has been implemented, too:
To access the decoded response as an array, call decode_response() .
‘json’ and ‘php’ formats are configured to use the built-in json_decode and unserialize functions, respectively. Overrides and additional decoders can be specified upon instantiation, or individually afterword. Decoder functions take one argument: the raw request body. Lambdas and functions created with create_function work, too.
function my_xml_decoder($data)< new SimpleXMLElement($data); > $api = new RestClient([ 'format' => "xml", 'decoders' => ['xml' => "my_xml_decoder"] ]);
$api = new RestClient; $api->set_option('format', "xml"); $api->register_decoder('xml', "my_xml_decoder");
Or, using a lambda; this particular example allows you to receive decoded JSON data as an array.
$api->register_decoder('json', function($data)< return json_decode($data, TRUE); >);
Duplicate Headers and Parameters
When duplicate (repeated) HTTP headers are received, they are accessible via an indexed array referenced by the shared key. Duplicated headers and parameters may also be constructed in requests using the same format.
Example (unlikely) response:
HTTP/1.1 200 OK Content-Type: text/html Content-Type: text/html; charset=UTF-8
Accessing repeated headers in the response instance:
$result = $api->get('/'); var_dump($result->headers->content_type); => ["text/html", "text/html; charset=UTF-8"]
Passing repeated headers and parameters in a request:
$result = $api->get('/', [ 'foo[]' => ['bar', 'baz'] ], [ 'Accept' => ['text/json', 'application/json'] ]);
Will create headers and a query string (GET) or response body (POST, etc) with the following content:
GET /?foo[]=bar&foo[]=baz HTTP/1.1 Accept: text/json Accept: application/json
Multiple HTTP Status Lines
Multiple status lines returned in a single response payload are supported, and available as response_status_lines which is an indexed array populated on the response instance.
Example response with multiple status lines (truncated):
HTTP/1.1 100 Continue HTTP/1.1 200 OK Cache-Control: no-cache .
$result = $api->get('/'); var_dump($result->response_status_lines); => ["HTTP/1.1 100 Continue", "HTTP/1.1 200 OK"]
This library will never validate or construct PATCH JSON content, but it can be configured to communicate well-formed data.
PATCH JSON content with correct content type:
$result = $api->execute("http://httpbin.org/patch", 'PATCH', json_encode([foo' => 'bar']), [ 'X-HTTP-Method-Override' => 'PATCH', 'Content-Type' => 'application/json-patch+json']);
The test package includes a simple server script which returns debug information for verifying functionality. Start the server first, then run tests:
$ php -S localhost:8888 RestClientTest.php $ phpunit RestClientTest
- Requires PHP > 5.5.7 in order for getallheaders data to populate.
- If you specify an alternate port number or hostname to the PHP server you need to re-configure it in your phpunit.xml file:
php>var name="TEST_SERVER_URL" value="http://localhost:8888"/>php>
PHP Consume External REST APIs
In this PHP example, I am going to show you how to call external REST APIs in PHP programming. I am not going to build here any new REST API, but I will call or consume those REST APIs which are already available for testing purpose. But if you want to know then you can check my tutorial about how to build REST APIs in PHP.
The full form of REST acronym is Representational State Transfer that works over stateless HTTP or HTTPS protocol only.
I will use CURL to call the REST URL resources (REST APIs). CURL is a command line tool for transferring data using various network protocols.
Prerequisites
Project Directory
It’s assumed that you have setup PHP in your system.
Now I will create a project root directory called php-consume-external-rest-apis anywhere in your system. I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project’s root directory.
CURL Helper
I will create a common helper function for CURL operations on various HTTP methods – GET, POST, PUT, etc. – for calling external REST APIs.
The following code is written into a file common.php.
break; case "PUT": curl_setopt($curl, CURLOPT_PUT, 1); break; default: if ($data) < $url = sprintf("%s?%s", $url, http_build_query($data)); >> curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //If SSL Certificate Not Available, for example, I am calling from http://localhost URL $result = curl_exec($curl); curl_close($curl); return $result; >
In the above function I have used switch case to segregate operations according to the HTTP methods.
I have set SSL verification to false for https protocol because I am not using any valid certificate at client side and more over, I am calling from my localhost over non-secured http protocol. If you are calling http-based REST API URLs then you don’t need to set this option on your localhost.
Call External REST APIs
Here is the PHP file php-consume-external-rest-apis.php that has the necessary code to call external REST APIs for performing operations and fetching data from the server.
"Soumitra", "job" => "Blog Author", "avatar" => "https://roytuts.com/about/")); $response = perform_http_request('POST', $rest_api_base_url . $post_endpoint, $request_data); echo 'New User' . "\n"; echo $response . "\n"; //PUT - update user $put_endpoint = '/api/users'; $request_data = json_encode(array("name" => "Soumitra", "job" => "Roy Tutorials Author", "avatar" => "https://roytuts.com/about/")); $response = perform_http_request('PUT', $rest_api_base_url . $put_endpoint, $request_data); echo 'Update User' . "\n"; echo $response;
I have loaded the required common file using require_once.
In the above PHP file, I have shown examples on GET, POST and PUT methods.
The base URL for all REST endpoints is same only individual endpoint for each operation is different.
I have fetched list of users as well as single user using HTTP GET method from the external REST API.
For POST and PUT methods, I have sent the data in JSON format using jsong_encode() . The POST method has been used for creating a new user and PUT method has been used for updating the existing user.
Testing – Call External REST APIs
To run your PHP file using CLI, use the following command. Note php-consume-external-rest-apis is the project root directory.
php-consume-external-rest-apis>php php-consume-external-rest-apis.php
You will see the following output in the console:
Hope you got an idea how to call external REST services in PHP.