PHP REST client API call - php

I'm wondering, is there an easy way to perform a REST API GET call? I've been reading about cURL, but is that a good way to do it?
I also came across php://input but I have no idea how to use it. Does anyone have an example for me?
I don't need advanced API client stuff, I just need to perform a GET call to a certain URL to get some JSON data that will be parsed by the client.
Thanks!

There are multiple ways to make REST client API call:
Use CURL
CURL is the simplest and good way to go. Here is a simple call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
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
Use file_get_contents
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);
Use Symfony's RestClient
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.
try {
$restClient = new RestClient();
$response = $restClient->get('http://www.someUrl.com');
$statusCode = $response->getStatusCode();
$content = $response->getContent();
} catch(OperationTimedOutException $e) {
// do something
}
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";

You can use file_get_contents if the fopen wrappers are enabled. See: http://php.net/manual/en/function.file-get-contents.php
If they are not, and you cannot fix that because your host doesn't allow it, cURL is a good method to use.

You can use:
$result = file_get_contents( $url );
http://php.net/manual/en/function.file-get-contents.php

Related

HOW TO USE API's in PHP LARAVEL [duplicate]

I'm planning to use PHP for a simple requirement. I need to download a XML content from a URL, for which I need to send HTTP GET request to that URL.
How do I do it in PHP?
Unless you need more than just the contents of the file, you could use file_get_contents.
$xml = file_get_contents("http://www.example.com/file.xml");
For anything more complex, I'd use cURL.
For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):
$ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.
$response = http_get("http://www.example.com/file.xml");
Remember that if you are using a proxy you need to do a little trick in your php code:
(PROXY WITHOUT AUTENTICATION EXAMPLE)
<?php
$aContext = array(
'http' => array(
'proxy' => 'proxy:8080',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);
$sFile = file_get_contents("http://www.google.com", False, $cxContext);
echo $sFile;
?>
Guzzle is a very well known library which makes it extremely easy to do all sorts of HTTP calls. See https://github.com/guzzle/guzzle. Install with composer require guzzlehttp/guzzle and run composer install. Now code below is enough for a http get call.
$client = new \GuzzleHttp\Client();
$response = $client->get('https://example.com/path/to/resource');
echo $response->getStatusCode();
echo $response->getBody();
Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )
Edit: Re-reading the question I'm not certain whether you're looking to pass variables or not - if you're not you can simply send the fopen request containg http://example.com/filename.xml - feel free to ignore the variable=value part
I like using fsockopen open for this.
On the other hand, using the REST API of servers is very popular in PHP. You can suppose all URLs are parts of a REST API and use many well-designed PHP packages.
Actually, REST API is a way to use services from a site.
So, there are many PHP packages developed to simplify REST API call. For example here is a very nice one:
https://github.com/romanpitak/PHP-REST-Client
Using such packages helps you to fetch resources easily.
So, getting the xml file (that you mentioned about) is as easy as:
$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();

Laravel 4 make post request from controller to external url with data

I am looking for a way to make a post request from a controller to an external url. The data being posted is a php array. The url to recieve is an ecommerce API in an external url. The post has to be done from the controller method. The url should reply with 'success', 'error', 'failure' or 'trylater' string. I have tried the following with no success:
return Redirect::to("https://backoffice.host.iveri.com/Lite/Transactions/New/Authorise.aspx", compact($array));
I have tried curl too:
$url = 'https://backoffice.host.iveri.com/Lite/Transactions/New/Authorise.aspx';
//url-ify the data for the POST
$fields_string ='';
foreach($array as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'& ');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($array));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Part of the array being sent is the callbacks that the API uses to responds:
'Lite_Website_Successful_url' => 'https://mydomain.com/order/'.$order_id,
'Lite_Website_Fail_url' => 'https://mydomain.com/checkout/fail',
'Lite_Website_TryLater_url' => 'https://mydomain.com/checkout/trylater',
'Lite_Website_Error_url' => 'https://mydomain.com/checkout/error'
Please let me know how to do a POST request properly with data carried with it to an external url. An ajax post from the controller too would help but I have tried with no success. But I would prefer a laravel php answer more. Thank you.
We can use package Guzzle in Laravel, it is a PHP HTTP client to send HTTP requests.
You can install Guzzle through composer
composer require guzzlehttp/guzzle:~6.0
Or you can specify Guzzle as a dependency in your project's existing composer.json
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
Example code of POST Request in laravel, using Guzzle is as shown below,
use GuzzleHttp\Client;
class yourController extends Controller {
public function saveApiData()
{
$client = new Client();
$res = $client->request('POST', 'https://url_to_the_api', [
'form_params' => [
'client_id' => 'test_id',
'secret' => 'test_secret',
]
]);
$result= $res->getBody();
dd($result);
}
Let me clarify some stuff and try to point you in the right direction.
First, what you're attempting to do sounds like "making an API request from your web app". The difference in that wording in how I stated it vs yours is that it's more general.
You can make an API request anywhere in your application, not necessarily in your controller (Don't be afraid to make extra classes/models for things like API calls!)
I'm curious about why it "has to be" done in your controller? What's your use case?
AJAX doesn't exist on the server-side (in PHP). That's purely a javascript-specific "technology" that describes javascript making a request to a URL on the client-side.
Lastly, what are you trying to do? Do you need a user to be redirected? Or do you need to make an API call and parse the result within your application?
The cURL request you've attempted should work for making an API request. That's one of the main ways of making an API request within PHP code. It won't, however, allow a user on the front-end to see that request being made and processed. With cURL (and any API request), the processing is all happening behind the scenes in your PHP (which your users can't see).
Either use CURL the way you've been trying, or check this thread for a brief answer on doing it with the Guzzle http client. Guzzle seems to be the preferred client for use with Laravel...
Call external API function from controller, LARAVEL 4

Reading REST API Response in PHP

I am trying to read Raven SEO Tools API. It is a REST API and currently it is serving the data backup as an XML (or JSON if I choose) when I just request the URL through a web browser. What is the best method to get the response from their server into my own PHP script for me to then play around with.
Any help much appreciated
Cheers
If you only needs to retrieve a URL and parse its info. The easiest way is curl/JSON combination. Note that parsing JSON is faster than parsing XML.
http://www.php.net/manual/en/function.curl-exec.php
http://www.php.net/manual/en/function.json-decode.php
Something simple as:
$url = "http://api.raventools.com/api?key=B1DFC59CA6EC76FF&method=domains&format=json";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
echo curl_error($ch);
}
curl_close($ch);
print_r(json_decode($json));
But if you need to call other methods from this API such as DELETE/PUT, etc. Then to have a REST client in PHP is more elegant solution. A comparison on those clients can be found in PHP REST Clients
I founded this code specifically for Raven API https://github.com/stephenyeargin/raventools-api-php
Sample code:
require 'path/to/raventools-api-php/raventools-api-php.class.php';
$Raven = new RavenTools( 'B1DFC59CA6EC76FF' );
$method = 'domains';
$options = array('format'=> 'json');
$responseString = $Raven->getJSON($method, $options);
print_r(json_decode($responseString));
cUrl
cUrl is a command line tool for getting or sending files using URL syntax.
curl -o example.html www.example.com
file_get_contents
<?php
$homepage = file_get_contents('http://www.example.com/api/parameters');
echo $homepage;
?>
Pecl's HTTPRequest class is a very nice client, I've been using it for a couple of Projects. http://pecl.php.net/package/pecl_http
Another pretty cool client is the Buzz client https://github.com/kriswallsmith/Buzz
It also plays nice with Symfony2 if that's of interest to you :)
You can use either one of them, but I think JSON is the easiest and more hassle-free, unless you use SimpleXML. The decision depends on the complexity of your data.
Given that the JSON returned by the API is valid you can convert it to an array or object by using PHP's json_decode() function.
<?php
# retrieve JSON from API here...
# i.e. it is stored in $data as a string
$object = json_decode($data);
$array = json_decode($data, true);
?>
In SimpleXML, it would be as follows:
<?php
$object = simplexml_load_string($data);
?>

How can I implement my PHP curl request to Python

This PHP code below fetches html from server A to server B. I did this to circumvent the same-domain policy of browsers. (jQuery's JSONP can also be used to achieve this but I prefer this method)
<?php
/*
This code goes inside the body tag of server-B.com.
Server-A.com then returns a set of form tags to be echoed in the body tag of Server-B
*/
$ch = curl_init();
$url = "http://server-A.com/form.php";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER,FALSE);
curl_exec($ch); // grab URL and pass it to the browser
curl_close($ch); // close cURL resource, and free up system resources
?>
How can I achieve this in Python? Im sure there is Curl implementation in Python too but I dont quite know how to do it yet.
There are cURL wrappers for Python, but the preferred way of doing this is using urllib2
Note that your code in PHP retrieves the whole page and prints it. The equivalent Python code is:
import urllib2
url = 'http://server-A.com/form.php'
res = urllib2.urlopen(url)
print res.read()
I'm pretty sure this is what you're looking for: http://pycurl.sourceforge.net/
Good luck!
You can use Requests library
Sample Get Call
import requests
def consumeGETRequestSync():
params = {'test1':'param1','test2':'param2'}
url = 'http://httpbin.org/get'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = requests.get(url, headers = headers,data = params)
print "code:"+ str(response.status_code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "content:"+ str(response.text)
consumeGETRequestSync()
You can check this blog post http://stackandqueue.com/?p=75

How to send a GET request from PHP?

I'm planning to use PHP for a simple requirement. I need to download a XML content from a URL, for which I need to send HTTP GET request to that URL.
How do I do it in PHP?
Unless you need more than just the contents of the file, you could use file_get_contents.
$xml = file_get_contents("http://www.example.com/file.xml");
For anything more complex, I'd use cURL.
For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):
$ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.
$response = http_get("http://www.example.com/file.xml");
Remember that if you are using a proxy you need to do a little trick in your php code:
(PROXY WITHOUT AUTENTICATION EXAMPLE)
<?php
$aContext = array(
'http' => array(
'proxy' => 'proxy:8080',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);
$sFile = file_get_contents("http://www.google.com", False, $cxContext);
echo $sFile;
?>
Guzzle is a very well known library which makes it extremely easy to do all sorts of HTTP calls. See https://github.com/guzzle/guzzle. Install with composer require guzzlehttp/guzzle and run composer install. Now code below is enough for a http get call.
$client = new \GuzzleHttp\Client();
$response = $client->get('https://example.com/path/to/resource');
echo $response->getStatusCode();
echo $response->getBody();
Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )
Edit: Re-reading the question I'm not certain whether you're looking to pass variables or not - if you're not you can simply send the fopen request containg http://example.com/filename.xml - feel free to ignore the variable=value part
I like using fsockopen open for this.
On the other hand, using the REST API of servers is very popular in PHP. You can suppose all URLs are parts of a REST API and use many well-designed PHP packages.
Actually, REST API is a way to use services from a site.
So, there are many PHP packages developed to simplify REST API call. For example here is a very nice one:
https://github.com/romanpitak/PHP-REST-Client
Using such packages helps you to fetch resources easily.
So, getting the xml file (that you mentioned about) is as easy as:
$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();

Categories