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
Related
This is very basic, but I am kind of confused where I am going wrong (learning how to implement a RESTful Web Service). The context is, I have a simple simulator.php file that simulates an HTTP request to one of my local PHP files. The local PHP file (index.php) does nothing but return a variable with a value. So it's pretty much like this:
<?php
$variable = 'hello';
return $variable;
?>
and my simulator.php file has the following:
?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/kixeye/index.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
var_dump($contents);
curl_close($ch);
?>
However, var_dump($contents) does not quite spit out the value of $variable which is being returned from index.php. I don't quite understand why not.
returning something outside of a function won't actually do anything. The cURL request you are making will return the HTML response from the requested page, so what your really want to do is echo the response rather than using return.
Just change the index.php script to this:
<?php
$variable = 'hello';
echo $variable;
?>
And your var_dump() in the second script will output hello.
The $contents variable will contain the web page being returned by the http request done with Curl. If you only need one value from index.php, just echo it, and its value will end up in $contents as a string.
If you want to retrieve several variables, you could try json encode them and then echo the result in index.php. Then you would have to do the reverse in your second script by json decoding $contents.
Alternatively, you could generate and echo valid php code in the first script, and then eval it in the second, but this is very bad practice (the use of eval is strongly discouraged).
See:
json_encode
eval
I'm trying to figure out how to use the Cheddar API (http://cheddarapp.com/developer) in my PHP application.
Cheddar's API uses curl requests - which have been fine for me using in terminal but not in my index.php.
I'd like to create a button that when clicked, creates a task in a list call Colors. If a list does not exist, it'll create the list.
Have anybody used Cheddar's API or even included curl requests in PHP or even how to include them in Javascript which I'm guessing you use for things of this matter.
Update
Here's the Curl request for creating a task in Cheddar: https://cheddarapp.com/developer/tasks#create.
I'd like to make a button that onclick, it will create a task. Is it not as a simple as creating a function in Javascript and using onclick on an anchor?
I am using now days curl Php
$LOCAL_REST_URL = 'whateverurlofyourrestapi'
$json_part = { pass the data for post }
you will get your response in $buffer in json format iterate it use the response
As u said how to make a curl request i would like to give you a simple POST example
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,$LOCAL_REST_URL);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,20);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS,$json_part);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
Where $json_partis the request body and $LOCAL_REST_URL is is your rest url
I am hoping this post will help you
You could run your terminal program with shell_exec from php.
Or transcript the curl-code to curl-requests from php, http://se2.php.net/manual/en/ref.curl.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
From within the HTML code in one of my server pages I need to address a search of a specific item on a database placed in another remote server that I don’t own myself.
Example of the search type that performs my request: http://www.remoteserver.com/items/search.php?search_size=XXL
The remote server provides to me - as client - the response displaying a page with several items that match my search criteria.
I don’t want to have this page displayed. What I want is to collect into a string (or local file) the full contents of the remote server HTML response (the code we have access when we click on ‘View Source’ in my IE browser client).
If I collect that data (it could easily reach reach 50000 bytes) I can then filter the one in which I am interested (substrings) and assemble a new request to the remote server for only one of the specific items in the response provided.
Is there any way through which I can get HTML from the response provided by the remote server with Javascript or PHP, and also avoid the display of the response in the browser itself?
I hope I have not confused your minds …
Thanks for any help you may provide.
As #mario mentioned, there are several different ways to do it.
Using file_get_contents():
$txt = file_get_contents('http://www.example.com/');
echo $txt;
Using php's curl functions:
$url = 'http://www.mysite.com';
$ch = curl_init($url);
// Tell curl_exec to return the text instead of sending it to STDOUT
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Don't include return header in output
curl_setopt($ch, CURLOPT_HEADER, 0);
$txt = curl_exec($ch);
curl_close($ch);
echo $txt;
curl is probably the most robust option because you have options for more control over the exact request parameters and possibilities for error handling when things don't go as planned
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);
?>